qcustomplot.cpp 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529
  1. /***************************************************************************
  2. ** **
  3. ** QCustomPlot, an easy to use, modern plotting widget for Qt **
  4. ** Copyright (C) 2011-2022 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: https://www.qcustomplot.com/ **
  22. ** Date: 06.11.22 **
  23. ** Version: 2.1.1 **
  24. ****************************************************************************/
  25. #include "qcustomplot.h"
  26. /* including file 'src/vector2d.cpp' */
  27. /* modified 2022-11-06T12:45:56, 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 2022-11-06T12:45:56, 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 2022-11-06T12:45:56, 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 2022-11-06T12:45:56, 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 2022-11-06T12:45:56, 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 2022-11-06T12:45:56, 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 2022-11-06T12:45:56, 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(mRect.left()+mRect.width())};
  2337. else
  2338. return {axis->pixelToCoord(mRect.top()+mRect.height()), axis->pixelToCoord(mRect.top())};
  2339. } else
  2340. {
  2341. qDebug() << Q_FUNC_INFO << "called with axis zero";
  2342. return {};
  2343. }
  2344. }
  2345. /*!
  2346. Sets the pen that will be used to draw the selection rect outline.
  2347. \see setBrush
  2348. */
  2349. void QCPSelectionRect::setPen(const QPen &pen)
  2350. {
  2351. mPen = pen;
  2352. }
  2353. /*!
  2354. Sets the brush that will be used to fill the selection rect. By default the selection rect is not
  2355. filled, i.e. \a brush is <tt>Qt::NoBrush</tt>.
  2356. \see setPen
  2357. */
  2358. void QCPSelectionRect::setBrush(const QBrush &brush)
  2359. {
  2360. mBrush = brush;
  2361. }
  2362. /*!
  2363. If there is currently a selection interaction going on (\ref isActive), the interaction is
  2364. canceled. The selection rect will emit the \ref canceled signal.
  2365. */
  2366. void QCPSelectionRect::cancel()
  2367. {
  2368. if (mActive)
  2369. {
  2370. mActive = false;
  2371. 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 2022-11-06T12:45:56, size 78863 */
  2441. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2442. //////////////////// QCPMarginGroup
  2443. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2444. /*! \class QCPMarginGroup
  2445. \brief A margin group allows synchronization of margin sides if working with multiple layout elements.
  2446. QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that
  2447. they will all have the same size, based on the largest required margin in the group.
  2448. \n
  2449. \image html QCPMarginGroup.png "Demonstration of QCPMarginGroup"
  2450. \n
  2451. In certain situations it is desirable that margins at specific sides are synchronized across
  2452. layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will
  2453. provide a cleaner look to the user if the left and right margins of the two axis rects are of the
  2454. same size. The left axis of the top axis rect will then be at the same horizontal position as the
  2455. left axis of the lower axis rect, making them appear aligned. The same applies for the right
  2456. axes. This is what QCPMarginGroup makes possible.
  2457. To add/remove a specific side of a layout element to/from a margin group, use the \ref
  2458. QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call
  2459. \ref clear, or just delete the margin group.
  2460. \section QCPMarginGroup-example Example
  2461. First create a margin group:
  2462. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-1
  2463. Then set this group on the layout element sides:
  2464. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-2
  2465. Here, we've used the first two axis rects of the plot and synchronized their left margins with
  2466. each other and their right margins with each other.
  2467. */
  2468. /* start documentation of inline functions */
  2469. /*! \fn QList<QCPLayoutElement*> QCPMarginGroup::elements(QCP::MarginSide side) const
  2470. Returns a list of all layout elements that have their margin \a side associated with this margin
  2471. group.
  2472. */
  2473. /* end documentation of inline functions */
  2474. /*!
  2475. Creates a new QCPMarginGroup instance in \a parentPlot.
  2476. */
  2477. QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) :
  2478. QObject(parentPlot),
  2479. mParentPlot(parentPlot)
  2480. {
  2481. mChildren.insert(QCP::msLeft, QList<QCPLayoutElement*>());
  2482. mChildren.insert(QCP::msRight, QList<QCPLayoutElement*>());
  2483. mChildren.insert(QCP::msTop, QList<QCPLayoutElement*>());
  2484. mChildren.insert(QCP::msBottom, QList<QCPLayoutElement*>());
  2485. }
  2486. QCPMarginGroup::~QCPMarginGroup()
  2487. {
  2488. clear();
  2489. }
  2490. /*!
  2491. Returns whether this margin group is empty. If this function returns true, no layout elements use
  2492. this margin group to synchronize margin sides.
  2493. */
  2494. bool QCPMarginGroup::isEmpty() const
  2495. {
  2496. QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
  2497. while (it.hasNext())
  2498. {
  2499. it.next();
  2500. if (!it.value().isEmpty())
  2501. return false;
  2502. }
  2503. return true;
  2504. }
  2505. /*!
  2506. Clears this margin group. The synchronization of the margin sides that use this margin group is
  2507. lifted and they will use their individual margin sizes again.
  2508. */
  2509. void QCPMarginGroup::clear()
  2510. {
  2511. // make all children remove themselves from this margin group:
  2512. QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
  2513. while (it.hasNext())
  2514. {
  2515. it.next();
  2516. const QList<QCPLayoutElement*> elements = it.value();
  2517. for (int i=elements.size()-1; i>=0; --i)
  2518. elements.at(i)->setMarginGroup(it.key(), nullptr); // removes itself from mChildren via removeChild
  2519. }
  2520. }
  2521. /*! \internal
  2522. Returns the synchronized common margin for \a side. This is the margin value that will be used by
  2523. the layout element on the respective side, if it is part of this margin group.
  2524. The common margin is calculated by requesting the automatic margin (\ref
  2525. QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin
  2526. group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into
  2527. account, too.)
  2528. */
  2529. int QCPMarginGroup::commonMargin(QCP::MarginSide side) const
  2530. {
  2531. // query all automatic margins of the layout elements in this margin group side and find maximum:
  2532. int result = 0;
  2533. foreach (QCPLayoutElement *el, mChildren.value(side))
  2534. {
  2535. if (!el->autoMargins().testFlag(side))
  2536. continue;
  2537. int m = qMax(el->calculateAutoMargin(side), QCP::getMarginValue(el->minimumMargins(), side));
  2538. if (m > result)
  2539. result = m;
  2540. }
  2541. return result;
  2542. }
  2543. /*! \internal
  2544. Adds \a element to the internal list of child elements, for the margin \a side.
  2545. This function does not modify the margin group property of \a element.
  2546. */
  2547. void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element)
  2548. {
  2549. if (!mChildren[side].contains(element))
  2550. mChildren[side].append(element);
  2551. else
  2552. qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast<quintptr>(element);
  2553. }
  2554. /*! \internal
  2555. Removes \a element from the internal list of child elements, for the margin \a side.
  2556. This function does not modify the margin group property of \a element.
  2557. */
  2558. void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element)
  2559. {
  2560. if (!mChildren[side].removeOne(element))
  2561. qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast<quintptr>(element);
  2562. }
  2563. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2564. //////////////////// QCPLayoutElement
  2565. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2566. /*! \class QCPLayoutElement
  2567. \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system".
  2568. This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses.
  2569. A Layout element is a rectangular object which can be placed in layouts. It has an outer rect
  2570. (QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference
  2571. between outer and inner rect is called its margin. The margin can either be set to automatic or
  2572. manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be
  2573. set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic,
  2574. the layout element subclass will control the value itself (via \ref calculateAutoMargin).
  2575. Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level
  2576. layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref
  2577. QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested.
  2578. Thus in QCustomPlot one can divide layout elements into two categories: The ones that are
  2579. invisible by themselves, because they don't draw anything. Their only purpose is to manage the
  2580. position and size of other layout elements. This category of layout elements usually use
  2581. QCPLayout as base class. Then there is the category of layout elements which actually draw
  2582. something. For example, QCPAxisRect, QCPLegend and QCPTextElement are of this category. This does
  2583. not necessarily mean that the latter category can't have child layout elements. QCPLegend for
  2584. instance, actually derives from QCPLayoutGrid and the individual legend items are child layout
  2585. elements in the grid layout.
  2586. */
  2587. /* start documentation of inline functions */
  2588. /*! \fn QCPLayout *QCPLayoutElement::layout() const
  2589. Returns the parent layout of this layout element.
  2590. */
  2591. /*! \fn QRect QCPLayoutElement::rect() const
  2592. Returns the inner rect of this layout element. The inner rect is the outer rect (\ref outerRect, \ref
  2593. setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins).
  2594. In some cases, the area between outer and inner rect is left blank. In other cases the margin
  2595. area is used to display peripheral graphics while the main content is in the inner rect. This is
  2596. where automatic margin calculation becomes interesting because it allows the layout element to
  2597. adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect
  2598. draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if
  2599. \ref setAutoMargins is enabled) according to the space required by the labels of the axes.
  2600. \see outerRect
  2601. */
  2602. /*! \fn QRect QCPLayoutElement::outerRect() const
  2603. Returns the outer rect of this layout element. The outer rect is the inner rect expanded by the
  2604. margins (\ref setMargins, \ref setAutoMargins). The outer rect is used (and set via \ref
  2605. setOuterRect) by the parent \ref QCPLayout to control the size of this layout element.
  2606. \see rect
  2607. */
  2608. /* end documentation of inline functions */
  2609. /*!
  2610. Creates an instance of QCPLayoutElement and sets default values.
  2611. */
  2612. QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) :
  2613. QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout)
  2614. mParentLayout(nullptr),
  2615. mMinimumSize(),
  2616. mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX),
  2617. mSizeConstraintRect(scrInnerRect),
  2618. mRect(0, 0, 0, 0),
  2619. mOuterRect(0, 0, 0, 0),
  2620. mMargins(0, 0, 0, 0),
  2621. mMinimumMargins(0, 0, 0, 0),
  2622. mAutoMargins(QCP::msAll)
  2623. {
  2624. }
  2625. QCPLayoutElement::~QCPLayoutElement()
  2626. {
  2627. setMarginGroup(QCP::msAll, nullptr); // unregister at margin groups, if there are any
  2628. // unregister at layout:
  2629. if (qobject_cast<QCPLayout*>(mParentLayout)) // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor
  2630. mParentLayout->take(this);
  2631. }
  2632. /*!
  2633. Sets the outer rect of this layout element. If the layout element is inside a layout, the layout
  2634. sets the position and size of this layout element using this function.
  2635. Calling this function externally has no effect, since the layout will overwrite any changes to
  2636. the outer rect upon the next replot.
  2637. The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect.
  2638. \see rect
  2639. */
  2640. void QCPLayoutElement::setOuterRect(const QRect &rect)
  2641. {
  2642. if (mOuterRect != rect)
  2643. {
  2644. mOuterRect = rect;
  2645. mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
  2646. }
  2647. }
  2648. /*!
  2649. Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all
  2650. sides, this function is used to manually set the margin on those sides. Sides that are still set
  2651. to be handled automatically are ignored and may have any value in \a margins.
  2652. The margin is the distance between the outer rect (controlled by the parent layout via \ref
  2653. setOuterRect) and the inner \ref rect (which usually contains the main content of this layout
  2654. element).
  2655. \see setAutoMargins
  2656. */
  2657. void QCPLayoutElement::setMargins(const QMargins &margins)
  2658. {
  2659. if (mMargins != margins)
  2660. {
  2661. mMargins = margins;
  2662. mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
  2663. }
  2664. }
  2665. /*!
  2666. If \ref setAutoMargins is enabled on some or all margins, this function is used to provide
  2667. minimum values for those margins.
  2668. The minimum values are not enforced on margin sides that were set to be under manual control via
  2669. \ref setAutoMargins.
  2670. \see setAutoMargins
  2671. */
  2672. void QCPLayoutElement::setMinimumMargins(const QMargins &margins)
  2673. {
  2674. if (mMinimumMargins != margins)
  2675. {
  2676. mMinimumMargins = margins;
  2677. }
  2678. }
  2679. /*!
  2680. Sets on which sides the margin shall be calculated automatically. If a side is calculated
  2681. automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is
  2682. set to be controlled manually, the value may be specified with \ref setMargins.
  2683. Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref
  2684. setMarginGroup), to synchronize (align) it with other layout elements in the plot.
  2685. \see setMinimumMargins, setMargins, QCP::MarginSide
  2686. */
  2687. void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides)
  2688. {
  2689. mAutoMargins = sides;
  2690. }
  2691. /*!
  2692. Sets the minimum size of this layout element. A parent layout tries to respect the \a size here
  2693. by changing row/column sizes in the layout accordingly.
  2694. If the parent layout size is not sufficient to satisfy all minimum size constraints of its child
  2695. layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot
  2696. propagates the layout's size constraints to the outside by setting its own minimum QWidget size
  2697. accordingly, so violations of \a size should be exceptions.
  2698. Whether this constraint applies to the inner or the outer rect can be specified with \ref
  2699. setSizeConstraintRect (see \ref rect and \ref outerRect).
  2700. */
  2701. void QCPLayoutElement::setMinimumSize(const QSize &size)
  2702. {
  2703. if (mMinimumSize != size)
  2704. {
  2705. mMinimumSize = size;
  2706. if (mParentLayout)
  2707. mParentLayout->sizeConstraintsChanged();
  2708. }
  2709. }
  2710. /*! \overload
  2711. Sets the minimum size of this layout element.
  2712. Whether this constraint applies to the inner or the outer rect can be specified with \ref
  2713. setSizeConstraintRect (see \ref rect and \ref outerRect).
  2714. */
  2715. void QCPLayoutElement::setMinimumSize(int width, int height)
  2716. {
  2717. setMinimumSize(QSize(width, height));
  2718. }
  2719. /*!
  2720. Sets the maximum size of this layout element. A parent layout tries to respect the \a size here
  2721. by changing row/column sizes in the layout accordingly.
  2722. Whether this constraint applies to the inner or the outer rect can be specified with \ref
  2723. setSizeConstraintRect (see \ref rect and \ref outerRect).
  2724. */
  2725. void QCPLayoutElement::setMaximumSize(const QSize &size)
  2726. {
  2727. if (mMaximumSize != size)
  2728. {
  2729. mMaximumSize = size;
  2730. if (mParentLayout)
  2731. mParentLayout->sizeConstraintsChanged();
  2732. }
  2733. }
  2734. /*! \overload
  2735. Sets the maximum size of this layout element.
  2736. Whether this constraint applies to the inner or the outer rect can be specified with \ref
  2737. setSizeConstraintRect (see \ref rect and \ref outerRect).
  2738. */
  2739. void QCPLayoutElement::setMaximumSize(int width, int height)
  2740. {
  2741. setMaximumSize(QSize(width, height));
  2742. }
  2743. /*!
  2744. Sets to which rect of a layout element the size constraints apply. Size constraints can be set
  2745. via \ref setMinimumSize and \ref setMaximumSize.
  2746. The outer rect (\ref outerRect) includes the margins (e.g. in the case of a QCPAxisRect the axis
  2747. labels), whereas the inner rect (\ref rect) does not.
  2748. \see setMinimumSize, setMaximumSize
  2749. */
  2750. void QCPLayoutElement::setSizeConstraintRect(SizeConstraintRect constraintRect)
  2751. {
  2752. if (mSizeConstraintRect != constraintRect)
  2753. {
  2754. mSizeConstraintRect = constraintRect;
  2755. if (mParentLayout)
  2756. mParentLayout->sizeConstraintsChanged();
  2757. }
  2758. }
  2759. /*!
  2760. Sets the margin \a group of the specified margin \a sides.
  2761. Margin groups allow synchronizing specified margins across layout elements, see the documentation
  2762. of \ref QCPMarginGroup.
  2763. To unset the margin group of \a sides, set \a group to \c nullptr.
  2764. Note that margin groups only work for margin sides that are set to automatic (\ref
  2765. setAutoMargins).
  2766. \see QCP::MarginSide
  2767. */
  2768. void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group)
  2769. {
  2770. QVector<QCP::MarginSide> sideVector;
  2771. if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft);
  2772. if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight);
  2773. if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop);
  2774. if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom);
  2775. foreach (QCP::MarginSide side, sideVector)
  2776. {
  2777. if (marginGroup(side) != group)
  2778. {
  2779. QCPMarginGroup *oldGroup = marginGroup(side);
  2780. if (oldGroup) // unregister at old group
  2781. oldGroup->removeChild(side, this);
  2782. if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there
  2783. {
  2784. mMarginGroups.remove(side);
  2785. } else // setting to a new group
  2786. {
  2787. mMarginGroups[side] = group;
  2788. group->addChild(side, this);
  2789. }
  2790. }
  2791. }
  2792. }
  2793. /*!
  2794. Updates the layout element and sub-elements. This function is automatically called before every
  2795. replot by the parent layout element. It is called multiple times, once for every \ref
  2796. UpdatePhase. The phases are run through in the order of the enum values. For details about what
  2797. happens at the different phases, see the documentation of \ref UpdatePhase.
  2798. Layout elements that have child elements should call the \ref update method of their child
  2799. elements, and pass the current \a phase unchanged.
  2800. The default implementation executes the automatic margin mechanism in the \ref upMargins phase.
  2801. Subclasses should make sure to call the base class implementation.
  2802. */
  2803. void QCPLayoutElement::update(UpdatePhase phase)
  2804. {
  2805. if (phase == upMargins)
  2806. {
  2807. if (mAutoMargins != QCP::msNone)
  2808. {
  2809. // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group:
  2810. QMargins newMargins = mMargins;
  2811. const QList<QCP::MarginSide> allMarginSides = QList<QCP::MarginSide>() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom;
  2812. foreach (QCP::MarginSide side, allMarginSides)
  2813. {
  2814. if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically
  2815. {
  2816. if (mMarginGroups.contains(side))
  2817. QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group
  2818. else
  2819. QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly
  2820. // apply minimum margin restrictions:
  2821. if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side))
  2822. QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side));
  2823. }
  2824. }
  2825. setMargins(newMargins);
  2826. }
  2827. }
  2828. }
  2829. /*!
  2830. Returns the suggested minimum size this layout element (the \ref outerRect) may be compressed to,
  2831. if no manual minimum size is set.
  2832. if a minimum size (\ref setMinimumSize) was not set manually, parent layouts use the returned size
  2833. (usually indirectly through \ref QCPLayout::getFinalMinimumOuterSize) to determine the minimum
  2834. allowed size of this layout element.
  2835. A manual minimum size is considered set if it is non-zero.
  2836. The default implementation simply returns the sum of the horizontal margins for the width and the
  2837. sum of the vertical margins for the height. Reimplementations may use their detailed knowledge
  2838. about the layout element's content to provide size hints.
  2839. */
  2840. QSize QCPLayoutElement::minimumOuterSizeHint() const
  2841. {
  2842. return {mMargins.left()+mMargins.right(), mMargins.top()+mMargins.bottom()};
  2843. }
  2844. /*!
  2845. Returns the suggested maximum size this layout element (the \ref outerRect) may be expanded to,
  2846. if no manual maximum size is set.
  2847. if a maximum size (\ref setMaximumSize) was not set manually, parent layouts use the returned
  2848. size (usually indirectly through \ref QCPLayout::getFinalMaximumOuterSize) to determine the
  2849. maximum allowed size of this layout element.
  2850. A manual maximum size is considered set if it is smaller than Qt's \c QWIDGETSIZE_MAX.
  2851. The default implementation simply returns \c QWIDGETSIZE_MAX for both width and height, implying
  2852. no suggested maximum size. Reimplementations may use their detailed knowledge about the layout
  2853. element's content to provide size hints.
  2854. */
  2855. QSize QCPLayoutElement::maximumOuterSizeHint() const
  2856. {
  2857. return {QWIDGETSIZE_MAX, QWIDGETSIZE_MAX};
  2858. }
  2859. /*!
  2860. Returns a list of all child elements in this layout element. If \a recursive is true, all
  2861. sub-child elements are included in the list, too.
  2862. \warning There may be \c nullptr entries in the returned list. For example, QCPLayoutGrid may
  2863. have empty cells which yield \c nullptr at the respective index.
  2864. */
  2865. QList<QCPLayoutElement*> QCPLayoutElement::elements(bool recursive) const
  2866. {
  2867. Q_UNUSED(recursive)
  2868. return QList<QCPLayoutElement*>();
  2869. }
  2870. /*!
  2871. Layout elements are sensitive to events inside their outer rect. If \a pos is within the outer
  2872. rect, this method returns a value corresponding to 0.99 times the parent plot's selection
  2873. tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is
  2874. true, -1.0 is returned.
  2875. See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
  2876. QCPLayoutElement subclasses may reimplement this method to provide more specific selection test
  2877. behaviour.
  2878. */
  2879. double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  2880. {
  2881. Q_UNUSED(details)
  2882. if (onlySelectable)
  2883. return -1;
  2884. if (QRectF(mOuterRect).contains(pos))
  2885. {
  2886. if (mParentPlot)
  2887. return mParentPlot->selectionTolerance()*0.99;
  2888. else
  2889. {
  2890. qDebug() << Q_FUNC_INFO << "parent plot not defined";
  2891. return -1;
  2892. }
  2893. } else
  2894. return -1;
  2895. }
  2896. /*! \internal
  2897. propagates the parent plot initialization to all child elements, by calling \ref
  2898. QCPLayerable::initializeParentPlot on them.
  2899. */
  2900. void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot)
  2901. {
  2902. foreach (QCPLayoutElement *el, elements(false))
  2903. {
  2904. if (!el->parentPlot())
  2905. el->initializeParentPlot(parentPlot);
  2906. }
  2907. }
  2908. /*! \internal
  2909. Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a
  2910. side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the
  2911. returned value will not be smaller than the specified minimum margin.
  2912. The default implementation just returns the respective manual margin (\ref setMargins) or the
  2913. minimum margin, whichever is larger.
  2914. */
  2915. int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side)
  2916. {
  2917. return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side));
  2918. }
  2919. /*! \internal
  2920. This virtual method is called when this layout element was moved to a different QCPLayout, or
  2921. when this layout element has changed its logical position (e.g. row and/or column) within the
  2922. same QCPLayout. Subclasses may use this to react accordingly.
  2923. Since this method is called after the completion of the move, you can access the new parent
  2924. layout via \ref layout().
  2925. The default implementation does nothing.
  2926. */
  2927. void QCPLayoutElement::layoutChanged()
  2928. {
  2929. }
  2930. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2931. //////////////////// QCPLayout
  2932. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2933. /*! \class QCPLayout
  2934. \brief The abstract base class for layouts
  2935. This is an abstract base class for layout elements whose main purpose is to define the position
  2936. and size of other child layout elements. In most cases, layouts don't draw anything themselves
  2937. (but there are exceptions to this, e.g. QCPLegend).
  2938. QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts.
  2939. QCPLayout introduces a common interface for accessing and manipulating the child elements. Those
  2940. functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref
  2941. simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions
  2942. to this interface which are more specialized to the form of the layout. For example, \ref
  2943. QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid
  2944. more conveniently.
  2945. Since this is an abstract base class, you can't instantiate it directly. Rather use one of its
  2946. subclasses like QCPLayoutGrid or QCPLayoutInset.
  2947. For a general introduction to the layout system, see the dedicated documentation page \ref
  2948. thelayoutsystem "The Layout System".
  2949. */
  2950. /* start documentation of pure virtual functions */
  2951. /*! \fn virtual int QCPLayout::elementCount() const = 0
  2952. Returns the number of elements/cells in the layout.
  2953. \see elements, elementAt
  2954. */
  2955. /*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0
  2956. Returns the element in the cell with the given \a index. If \a index is invalid, returns \c
  2957. nullptr.
  2958. Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g.
  2959. QCPLayoutGrid), so this function may return \c nullptr in those cases. You may use this function
  2960. to check whether a cell is empty or not.
  2961. \see elements, elementCount, takeAt
  2962. */
  2963. /*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0
  2964. Removes the element with the given \a index from the layout and returns it.
  2965. If the \a index is invalid or the cell with that index is empty, returns \c nullptr.
  2966. Note that some layouts don't remove the respective cell right away but leave an empty cell after
  2967. successful removal of the layout element. To collapse empty cells, use \ref simplify.
  2968. \see elementAt, take
  2969. */
  2970. /*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0
  2971. Removes the specified \a element from the layout and returns true on success.
  2972. If the \a element isn't in this layout, returns false.
  2973. Note that some layouts don't remove the respective cell right away but leave an empty cell after
  2974. successful removal of the layout element. To collapse empty cells, use \ref simplify.
  2975. \see takeAt
  2976. */
  2977. /* end documentation of pure virtual functions */
  2978. /*!
  2979. Creates an instance of QCPLayout and sets default values. Note that since QCPLayout
  2980. is an abstract base class, it can't be instantiated directly.
  2981. */
  2982. QCPLayout::QCPLayout()
  2983. {
  2984. }
  2985. /*!
  2986. If \a phase is \ref upLayout, calls \ref updateLayout, which subclasses may reimplement to
  2987. reposition and resize their cells.
  2988. Finally, the call is propagated down to all child \ref QCPLayoutElement "QCPLayoutElements".
  2989. For details about this method and the update phases, see the documentation of \ref
  2990. QCPLayoutElement::update.
  2991. */
  2992. void QCPLayout::update(UpdatePhase phase)
  2993. {
  2994. QCPLayoutElement::update(phase);
  2995. // set child element rects according to layout:
  2996. if (phase == upLayout)
  2997. updateLayout();
  2998. // propagate update call to child elements:
  2999. const int elCount = elementCount();
  3000. for (int i=0; i<elCount; ++i)
  3001. {
  3002. if (QCPLayoutElement *el = elementAt(i))
  3003. el->update(phase);
  3004. }
  3005. }
  3006. /* inherits documentation from base class */
  3007. QList<QCPLayoutElement*> QCPLayout::elements(bool recursive) const
  3008. {
  3009. const int c = elementCount();
  3010. QList<QCPLayoutElement*> result;
  3011. #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
  3012. result.reserve(c);
  3013. #endif
  3014. for (int i=0; i<c; ++i)
  3015. result.append(elementAt(i));
  3016. if (recursive)
  3017. {
  3018. for (int i=0; i<c; ++i)
  3019. {
  3020. if (result.at(i))
  3021. result << result.at(i)->elements(recursive);
  3022. }
  3023. }
  3024. return result;
  3025. }
  3026. /*!
  3027. Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the
  3028. default implementation does nothing.
  3029. Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit
  3030. simplification while QCPLayoutGrid does.
  3031. */
  3032. void QCPLayout::simplify()
  3033. {
  3034. }
  3035. /*!
  3036. Removes and deletes the element at the provided \a index. Returns true on success. If \a index is
  3037. invalid or points to an empty cell, returns false.
  3038. This function internally uses \ref takeAt to remove the element from the layout and then deletes
  3039. the returned element. Note that some layouts don't remove the respective cell right away but leave an
  3040. empty cell after successful removal of the layout element. To collapse empty cells, use \ref
  3041. simplify.
  3042. \see remove, takeAt
  3043. */
  3044. bool QCPLayout::removeAt(int index)
  3045. {
  3046. if (QCPLayoutElement *el = takeAt(index))
  3047. {
  3048. delete el;
  3049. return true;
  3050. } else
  3051. return false;
  3052. }
  3053. /*!
  3054. Removes and deletes the provided \a element. Returns true on success. If \a element is not in the
  3055. layout, returns false.
  3056. This function internally uses \ref takeAt to remove the element from the layout and then deletes
  3057. the element. Note that some layouts don't remove the respective cell right away but leave an
  3058. empty cell after successful removal of the layout element. To collapse empty cells, use \ref
  3059. simplify.
  3060. \see removeAt, take
  3061. */
  3062. bool QCPLayout::remove(QCPLayoutElement *element)
  3063. {
  3064. if (take(element))
  3065. {
  3066. delete element;
  3067. return true;
  3068. } else
  3069. return false;
  3070. }
  3071. /*!
  3072. Removes and deletes all layout elements in this layout. Finally calls \ref simplify to make sure
  3073. all empty cells are collapsed.
  3074. \see remove, removeAt
  3075. */
  3076. void QCPLayout::clear()
  3077. {
  3078. for (int i=elementCount()-1; i>=0; --i)
  3079. {
  3080. if (elementAt(i))
  3081. removeAt(i);
  3082. }
  3083. simplify();
  3084. }
  3085. /*!
  3086. Subclasses call this method to report changed (minimum/maximum) size constraints.
  3087. If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref
  3088. sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of
  3089. QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout,
  3090. it may update itself and resize cells accordingly.
  3091. */
  3092. void QCPLayout::sizeConstraintsChanged() const
  3093. {
  3094. if (QWidget *w = qobject_cast<QWidget*>(parent()))
  3095. w->updateGeometry();
  3096. else if (QCPLayout *l = qobject_cast<QCPLayout*>(parent()))
  3097. l->sizeConstraintsChanged();
  3098. }
  3099. /*! \internal
  3100. Subclasses reimplement this method to update the position and sizes of the child elements/cells
  3101. via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing.
  3102. The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay
  3103. within that rect.
  3104. \ref getSectionSizes may help with the reimplementation of this function.
  3105. \see update
  3106. */
  3107. void QCPLayout::updateLayout()
  3108. {
  3109. }
  3110. /*! \internal
  3111. Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the
  3112. \ref QCPLayerable::parentLayerable and the QObject parent to this layout.
  3113. Further, if \a el didn't previously have a parent plot, calls \ref
  3114. QCPLayerable::initializeParentPlot on \a el to set the paret plot.
  3115. This method is used by subclass specific methods that add elements to the layout. Note that this
  3116. method only changes properties in \a el. The removal from the old layout and the insertion into
  3117. the new layout must be done additionally.
  3118. */
  3119. void QCPLayout::adoptElement(QCPLayoutElement *el)
  3120. {
  3121. if (el)
  3122. {
  3123. el->mParentLayout = this;
  3124. el->setParentLayerable(this);
  3125. el->setParent(this);
  3126. if (!el->parentPlot())
  3127. el->initializeParentPlot(mParentPlot);
  3128. el->layoutChanged();
  3129. } else
  3130. qDebug() << Q_FUNC_INFO << "Null element passed";
  3131. }
  3132. /*! \internal
  3133. Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout
  3134. and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent
  3135. QCustomPlot.
  3136. This method is used by subclass specific methods that remove elements from the layout (e.g. \ref
  3137. take or \ref takeAt). Note that this method only changes properties in \a el. The removal from
  3138. the old layout must be done additionally.
  3139. */
  3140. void QCPLayout::releaseElement(QCPLayoutElement *el)
  3141. {
  3142. if (el)
  3143. {
  3144. el->mParentLayout = nullptr;
  3145. el->setParentLayerable(nullptr);
  3146. el->setParent(mParentPlot);
  3147. // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot
  3148. } else
  3149. qDebug() << Q_FUNC_INFO << "Null element passed";
  3150. }
  3151. /*! \internal
  3152. This is a helper function for the implementation of \ref updateLayout in subclasses.
  3153. It calculates the sizes of one-dimensional sections with provided constraints on maximum section
  3154. sizes, minimum section sizes, relative stretch factors and the final total size of all sections.
  3155. The QVector entries refer to the sections. Thus all QVectors must have the same size.
  3156. \a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size
  3157. imposed, set all vector values to Qt's QWIDGETSIZE_MAX.
  3158. \a minSizes gives the minimum allowed size of each section. If there shall be no minimum size
  3159. imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than
  3160. \a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words,
  3161. not exceeding the allowed total size is taken to be more important than not going below minimum
  3162. section sizes.)
  3163. \a stretchFactors give the relative proportions of the sections to each other. If all sections
  3164. shall be scaled equally, set all values equal. If the first section shall be double the size of
  3165. each individual other section, set the first number of \a stretchFactors to double the value of
  3166. the other individual values (e.g. {2, 1, 1, 1}).
  3167. \a totalSize is the value that the final section sizes will add up to. Due to rounding, the
  3168. actual sum may differ slightly. If you want the section sizes to sum up to exactly that value,
  3169. you could distribute the remaining difference on the sections.
  3170. The return value is a QVector containing the section sizes.
  3171. */
  3172. QVector<int> QCPLayout::getSectionSizes(QVector<int> maxSizes, QVector<int> minSizes, QVector<double> stretchFactors, int totalSize) const
  3173. {
  3174. if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size())
  3175. {
  3176. qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors;
  3177. return QVector<int>();
  3178. }
  3179. if (stretchFactors.isEmpty())
  3180. return QVector<int>();
  3181. int sectionCount = stretchFactors.size();
  3182. QVector<double> sectionSizes(sectionCount);
  3183. // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections):
  3184. int minSizeSum = 0;
  3185. for (int i=0; i<sectionCount; ++i)
  3186. minSizeSum += minSizes.at(i);
  3187. if (totalSize < minSizeSum)
  3188. {
  3189. // new stretch factors are minimum sizes and minimum sizes are set to zero:
  3190. for (int i=0; i<sectionCount; ++i)
  3191. {
  3192. stretchFactors[i] = minSizes.at(i);
  3193. minSizes[i] = 0;
  3194. }
  3195. }
  3196. QList<int> minimumLockedSections;
  3197. QList<int> unfinishedSections;
  3198. for (int i=0; i<sectionCount; ++i)
  3199. unfinishedSections.append(i);
  3200. double freeSize = totalSize;
  3201. int outerIterations = 0;
  3202. while (!unfinishedSections.isEmpty() && outerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
  3203. {
  3204. ++outerIterations;
  3205. int innerIterations = 0;
  3206. while (!unfinishedSections.isEmpty() && innerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
  3207. {
  3208. ++innerIterations;
  3209. // find section that hits its maximum next:
  3210. int nextId = -1;
  3211. double nextMax = 1e12;
  3212. foreach (int secId, unfinishedSections)
  3213. {
  3214. double hitsMaxAt = (maxSizes.at(secId)-sectionSizes.at(secId))/stretchFactors.at(secId);
  3215. if (hitsMaxAt < nextMax)
  3216. {
  3217. nextMax = hitsMaxAt;
  3218. nextId = secId;
  3219. }
  3220. }
  3221. // check if that maximum is actually within the bounds of the total size (i.e. can we stretch all remaining sections so far that the found section
  3222. // actually hits its maximum, without exceeding the total size when we add up all sections)
  3223. double stretchFactorSum = 0;
  3224. foreach (int secId, unfinishedSections)
  3225. stretchFactorSum += stretchFactors.at(secId);
  3226. double nextMaxLimit = freeSize/stretchFactorSum;
  3227. if (nextMax < nextMaxLimit) // next maximum is actually hit, move forward to that point and fix the size of that section
  3228. {
  3229. foreach (int secId, unfinishedSections)
  3230. {
  3231. sectionSizes[secId] += nextMax*stretchFactors.at(secId); // increment all sections
  3232. freeSize -= nextMax*stretchFactors.at(secId);
  3233. }
  3234. unfinishedSections.removeOne(nextId); // exclude the section that is now at maximum from further changes
  3235. } else // next maximum isn't hit, just distribute rest of free space on remaining sections
  3236. {
  3237. foreach (int secId, unfinishedSections)
  3238. sectionSizes[secId] += nextMaxLimit*stretchFactors.at(secId); // increment all sections
  3239. unfinishedSections.clear();
  3240. }
  3241. }
  3242. if (innerIterations == sectionCount*2)
  3243. qDebug() << Q_FUNC_INFO << "Exceeded maximum expected inner iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
  3244. // now check whether the resulting section sizes violate minimum restrictions:
  3245. bool foundMinimumViolation = false;
  3246. for (int i=0; i<sectionSizes.size(); ++i)
  3247. {
  3248. if (minimumLockedSections.contains(i))
  3249. continue;
  3250. if (sectionSizes.at(i) < minSizes.at(i)) // section violates minimum
  3251. {
  3252. sectionSizes[i] = minSizes.at(i); // set it to minimum
  3253. foundMinimumViolation = true; // make sure we repeat the whole optimization process
  3254. minimumLockedSections.append(i);
  3255. }
  3256. }
  3257. if (foundMinimumViolation)
  3258. {
  3259. freeSize = totalSize;
  3260. for (int i=0; i<sectionCount; ++i)
  3261. {
  3262. if (!minimumLockedSections.contains(i)) // only put sections that haven't hit their minimum back into the pool
  3263. unfinishedSections.append(i);
  3264. else
  3265. freeSize -= sectionSizes.at(i); // remove size of minimum locked sections from available space in next round
  3266. }
  3267. // reset all section sizes to zero that are in unfinished sections (all others have been set to their minimum):
  3268. foreach (int secId, unfinishedSections)
  3269. sectionSizes[secId] = 0;
  3270. }
  3271. }
  3272. if (outerIterations == sectionCount*2)
  3273. qDebug() << Q_FUNC_INFO << "Exceeded maximum expected outer iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
  3274. QVector<int> result(sectionCount);
  3275. for (int i=0; i<sectionCount; ++i)
  3276. result[i] = qRound(sectionSizes.at(i));
  3277. return result;
  3278. }
  3279. /*! \internal
  3280. This is a helper function for the implementation of subclasses.
  3281. It returns the minimum size that should finally be used for the outer rect of the passed layout
  3282. element \a el.
  3283. It takes into account whether a manual minimum size is set (\ref
  3284. QCPLayoutElement::setMinimumSize), which size constraint is set (\ref
  3285. QCPLayoutElement::setSizeConstraintRect), as well as the minimum size hint, if no manual minimum
  3286. size was set (\ref QCPLayoutElement::minimumOuterSizeHint).
  3287. */
  3288. QSize QCPLayout::getFinalMinimumOuterSize(const QCPLayoutElement *el)
  3289. {
  3290. QSize minOuterHint = el->minimumOuterSizeHint();
  3291. QSize minOuter = el->minimumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset minimum of 0)
  3292. if (minOuter.width() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
  3293. minOuter.rwidth() += el->margins().left() + el->margins().right();
  3294. if (minOuter.height() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
  3295. minOuter.rheight() += el->margins().top() + el->margins().bottom();
  3296. return {minOuter.width() > 0 ? minOuter.width() : minOuterHint.width(),
  3297. minOuter.height() > 0 ? minOuter.height() : minOuterHint.height()};
  3298. }
  3299. /*! \internal
  3300. This is a helper function for the implementation of subclasses.
  3301. It returns the maximum size that should finally be used for the outer rect of the passed layout
  3302. element \a el.
  3303. It takes into account whether a manual maximum size is set (\ref
  3304. QCPLayoutElement::setMaximumSize), which size constraint is set (\ref
  3305. QCPLayoutElement::setSizeConstraintRect), as well as the maximum size hint, if no manual maximum
  3306. size was set (\ref QCPLayoutElement::maximumOuterSizeHint).
  3307. */
  3308. QSize QCPLayout::getFinalMaximumOuterSize(const QCPLayoutElement *el)
  3309. {
  3310. QSize maxOuterHint = el->maximumOuterSizeHint();
  3311. QSize maxOuter = el->maximumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset maximum of QWIDGETSIZE_MAX)
  3312. if (maxOuter.width() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
  3313. maxOuter.rwidth() += el->margins().left() + el->margins().right();
  3314. if (maxOuter.height() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
  3315. maxOuter.rheight() += el->margins().top() + el->margins().bottom();
  3316. return {maxOuter.width() < QWIDGETSIZE_MAX ? maxOuter.width() : maxOuterHint.width(),
  3317. maxOuter.height() < QWIDGETSIZE_MAX ? maxOuter.height() : maxOuterHint.height()};
  3318. }
  3319. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3320. //////////////////// QCPLayoutGrid
  3321. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3322. /*! \class QCPLayoutGrid
  3323. \brief A layout that arranges child elements in a grid
  3324. Elements are laid out in a grid with configurable stretch factors (\ref setColumnStretchFactor,
  3325. \ref setRowStretchFactor) and spacing (\ref setColumnSpacing, \ref setRowSpacing).
  3326. Elements can be added to cells via \ref addElement. The grid is expanded if the specified row or
  3327. column doesn't exist yet. Whether a cell contains a valid layout element can be checked with \ref
  3328. hasElement, that element can be retrieved with \ref element. If rows and columns that only have
  3329. empty cells shall be removed, call \ref simplify. Removal of elements is either done by just
  3330. adding the element to a different layout or by using the QCPLayout interface \ref take or \ref
  3331. remove.
  3332. If you use \ref addElement(QCPLayoutElement*) without explicit parameters for \a row and \a
  3333. column, the grid layout will choose the position according to the current \ref setFillOrder and
  3334. the wrapping (\ref setWrap).
  3335. Row and column insertion can be performed with \ref insertRow and \ref insertColumn.
  3336. */
  3337. /* start documentation of inline functions */
  3338. /*! \fn int QCPLayoutGrid::rowCount() const
  3339. Returns the number of rows in the layout.
  3340. \see columnCount
  3341. */
  3342. /*! \fn int QCPLayoutGrid::columnCount() const
  3343. Returns the number of columns in the layout.
  3344. \see rowCount
  3345. */
  3346. /* end documentation of inline functions */
  3347. /*!
  3348. Creates an instance of QCPLayoutGrid and sets default values.
  3349. */
  3350. QCPLayoutGrid::QCPLayoutGrid() :
  3351. mColumnSpacing(5),
  3352. mRowSpacing(5),
  3353. mWrap(0),
  3354. mFillOrder(foColumnsFirst)
  3355. {
  3356. }
  3357. QCPLayoutGrid::~QCPLayoutGrid()
  3358. {
  3359. // clear all child layout elements. This is important because only the specific layouts know how
  3360. // to handle removing elements (clear calls virtual removeAt method to do that).
  3361. clear();
  3362. }
  3363. /*!
  3364. Returns the element in the cell in \a row and \a column.
  3365. Returns \c nullptr if either the row/column is invalid or if the cell is empty. In those cases, a
  3366. qDebug message is printed. To check whether a cell exists and isn't empty, use \ref hasElement.
  3367. \see addElement, hasElement
  3368. */
  3369. QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const
  3370. {
  3371. if (row >= 0 && row < mElements.size())
  3372. {
  3373. if (column >= 0 && column < mElements.first().size())
  3374. {
  3375. if (QCPLayoutElement *result = mElements.at(row).at(column))
  3376. return result;
  3377. else
  3378. qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column;
  3379. } else
  3380. qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column;
  3381. } else
  3382. qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column;
  3383. return nullptr;
  3384. }
  3385. /*! \overload
  3386. Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it
  3387. is first removed from there. If \a row or \a column don't exist yet, the layout is expanded
  3388. accordingly.
  3389. Returns true if the element was added successfully, i.e. if the cell at \a row and \a column
  3390. didn't already have an element.
  3391. Use the overload of this method without explicit row/column index to place the element according
  3392. to the configured fill order and wrapping settings.
  3393. \see element, hasElement, take, remove
  3394. */
  3395. bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element)
  3396. {
  3397. if (!hasElement(row, column))
  3398. {
  3399. if (element && element->layout()) // remove from old layout first
  3400. element->layout()->take(element);
  3401. expandTo(row+1, column+1);
  3402. mElements[row][column] = element;
  3403. if (element)
  3404. adoptElement(element);
  3405. return true;
  3406. } else
  3407. qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column;
  3408. return false;
  3409. }
  3410. /*! \overload
  3411. Adds the \a element to the next empty cell according to the current fill order (\ref
  3412. setFillOrder) and wrapping (\ref setWrap). If \a element is already in a layout, it is first
  3413. removed from there. If necessary, the layout is expanded to hold the new element.
  3414. Returns true if the element was added successfully.
  3415. \see setFillOrder, setWrap, element, hasElement, take, remove
  3416. */
  3417. bool QCPLayoutGrid::addElement(QCPLayoutElement *element)
  3418. {
  3419. int rowIndex = 0;
  3420. int colIndex = 0;
  3421. if (mFillOrder == foColumnsFirst)
  3422. {
  3423. while (hasElement(rowIndex, colIndex))
  3424. {
  3425. ++colIndex;
  3426. if (colIndex >= mWrap && mWrap > 0)
  3427. {
  3428. colIndex = 0;
  3429. ++rowIndex;
  3430. }
  3431. }
  3432. } else
  3433. {
  3434. while (hasElement(rowIndex, colIndex))
  3435. {
  3436. ++rowIndex;
  3437. if (rowIndex >= mWrap && mWrap > 0)
  3438. {
  3439. rowIndex = 0;
  3440. ++colIndex;
  3441. }
  3442. }
  3443. }
  3444. return addElement(rowIndex, colIndex, element);
  3445. }
  3446. /*!
  3447. Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't
  3448. empty.
  3449. \see element
  3450. */
  3451. bool QCPLayoutGrid::hasElement(int row, int column)
  3452. {
  3453. if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount())
  3454. return mElements.at(row).at(column);
  3455. else
  3456. return false;
  3457. }
  3458. /*!
  3459. Sets the stretch \a factor of \a column.
  3460. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  3461. their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
  3462. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
  3463. QCPLayoutElement::setSizeConstraintRect.)
  3464. The default stretch factor of newly created rows/columns is 1.
  3465. \see setColumnStretchFactors, setRowStretchFactor
  3466. */
  3467. void QCPLayoutGrid::setColumnStretchFactor(int column, double factor)
  3468. {
  3469. if (column >= 0 && column < columnCount())
  3470. {
  3471. if (factor > 0)
  3472. mColumnStretchFactors[column] = factor;
  3473. else
  3474. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
  3475. } else
  3476. qDebug() << Q_FUNC_INFO << "Invalid column:" << column;
  3477. }
  3478. /*!
  3479. Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount.
  3480. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  3481. their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
  3482. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
  3483. QCPLayoutElement::setSizeConstraintRect.)
  3484. The default stretch factor of newly created rows/columns is 1.
  3485. \see setColumnStretchFactor, setRowStretchFactors
  3486. */
  3487. void QCPLayoutGrid::setColumnStretchFactors(const QList<double> &factors)
  3488. {
  3489. if (factors.size() == mColumnStretchFactors.size())
  3490. {
  3491. mColumnStretchFactors = factors;
  3492. for (int i=0; i<mColumnStretchFactors.size(); ++i)
  3493. {
  3494. if (mColumnStretchFactors.at(i) <= 0)
  3495. {
  3496. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mColumnStretchFactors.at(i);
  3497. mColumnStretchFactors[i] = 1;
  3498. }
  3499. }
  3500. } else
  3501. qDebug() << Q_FUNC_INFO << "Column count not equal to passed stretch factor count:" << factors;
  3502. }
  3503. /*!
  3504. Sets the stretch \a factor of \a row.
  3505. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  3506. their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
  3507. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
  3508. QCPLayoutElement::setSizeConstraintRect.)
  3509. The default stretch factor of newly created rows/columns is 1.
  3510. \see setColumnStretchFactors, setRowStretchFactor
  3511. */
  3512. void QCPLayoutGrid::setRowStretchFactor(int row, double factor)
  3513. {
  3514. if (row >= 0 && row < rowCount())
  3515. {
  3516. if (factor > 0)
  3517. mRowStretchFactors[row] = factor;
  3518. else
  3519. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
  3520. } else
  3521. qDebug() << Q_FUNC_INFO << "Invalid row:" << row;
  3522. }
  3523. /*!
  3524. Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount.
  3525. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  3526. their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
  3527. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
  3528. QCPLayoutElement::setSizeConstraintRect.)
  3529. The default stretch factor of newly created rows/columns is 1.
  3530. \see setRowStretchFactor, setColumnStretchFactors
  3531. */
  3532. void QCPLayoutGrid::setRowStretchFactors(const QList<double> &factors)
  3533. {
  3534. if (factors.size() == mRowStretchFactors.size())
  3535. {
  3536. mRowStretchFactors = factors;
  3537. for (int i=0; i<mRowStretchFactors.size(); ++i)
  3538. {
  3539. if (mRowStretchFactors.at(i) <= 0)
  3540. {
  3541. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mRowStretchFactors.at(i);
  3542. mRowStretchFactors[i] = 1;
  3543. }
  3544. }
  3545. } else
  3546. qDebug() << Q_FUNC_INFO << "Row count not equal to passed stretch factor count:" << factors;
  3547. }
  3548. /*!
  3549. Sets the gap that is left blank between columns to \a pixels.
  3550. \see setRowSpacing
  3551. */
  3552. void QCPLayoutGrid::setColumnSpacing(int pixels)
  3553. {
  3554. mColumnSpacing = pixels;
  3555. }
  3556. /*!
  3557. Sets the gap that is left blank between rows to \a pixels.
  3558. \see setColumnSpacing
  3559. */
  3560. void QCPLayoutGrid::setRowSpacing(int pixels)
  3561. {
  3562. mRowSpacing = pixels;
  3563. }
  3564. /*!
  3565. Sets the maximum number of columns or rows that are used, before new elements added with \ref
  3566. addElement(QCPLayoutElement*) will start to fill the next row or column, respectively. It depends
  3567. on \ref setFillOrder, whether rows or columns are wrapped.
  3568. If \a count is set to zero, no wrapping will ever occur.
  3569. If you wish to re-wrap the elements currently in the layout, call \ref setFillOrder with \a
  3570. rearrange set to true (the actual fill order doesn't need to be changed for the rearranging to be
  3571. done).
  3572. Note that the method \ref addElement(int row, int column, QCPLayoutElement *element) with
  3573. explicitly stated row and column is not subject to wrapping and can place elements even beyond
  3574. the specified wrapping point.
  3575. \see setFillOrder
  3576. */
  3577. void QCPLayoutGrid::setWrap(int count)
  3578. {
  3579. mWrap = qMax(0, count);
  3580. }
  3581. /*!
  3582. Sets the filling order and wrapping behaviour that is used when adding new elements with the
  3583. method \ref addElement(QCPLayoutElement*).
  3584. The specified \a order defines whether rows or columns are filled first. Using \ref setWrap, you
  3585. can control at which row/column count wrapping into the next column/row will occur. If you set it
  3586. to zero, no wrapping will ever occur. Changing the fill order also changes the meaning of the
  3587. linear index used e.g. in \ref elementAt and \ref takeAt. The default fill order for \ref
  3588. QCPLayoutGrid is \ref foColumnsFirst.
  3589. If you want to have all current elements arranged in the new order, set \a rearrange to true. The
  3590. elements will be rearranged in a way that tries to preserve their linear index. However, empty
  3591. cells are skipped during build-up of the new cell order, which shifts the succeeding element's
  3592. index. The rearranging is performed even if the specified \a order is already the current fill
  3593. order. Thus this method can be used to re-wrap the current elements.
  3594. If \a rearrange is false, the current element arrangement is not changed, which means the
  3595. linear indexes change (because the linear index is dependent on the fill order).
  3596. Note that the method \ref addElement(int row, int column, QCPLayoutElement *element) with
  3597. explicitly stated row and column is not subject to wrapping and can place elements even beyond
  3598. the specified wrapping point.
  3599. \see setWrap, addElement(QCPLayoutElement*)
  3600. */
  3601. void QCPLayoutGrid::setFillOrder(FillOrder order, bool rearrange)
  3602. {
  3603. // if rearranging, take all elements via linear index of old fill order:
  3604. const int elCount = elementCount();
  3605. QVector<QCPLayoutElement*> tempElements;
  3606. if (rearrange)
  3607. {
  3608. tempElements.reserve(elCount);
  3609. for (int i=0; i<elCount; ++i)
  3610. {
  3611. if (elementAt(i))
  3612. tempElements.append(takeAt(i));
  3613. }
  3614. simplify();
  3615. }
  3616. // change fill order as requested:
  3617. mFillOrder = order;
  3618. // if rearranging, re-insert via linear index according to new fill order:
  3619. if (rearrange)
  3620. {
  3621. foreach (QCPLayoutElement *tempElement, tempElements)
  3622. addElement(tempElement);
  3623. }
  3624. }
  3625. /*!
  3626. Expands the layout to have \a newRowCount rows and \a newColumnCount columns. So the last valid
  3627. row index will be \a newRowCount-1, the last valid column index will be \a newColumnCount-1.
  3628. If the current column/row count is already larger or equal to \a newColumnCount/\a newRowCount,
  3629. this function does nothing in that dimension.
  3630. Newly created cells are empty, new rows and columns have the stretch factor 1.
  3631. Note that upon a call to \ref addElement, the layout is expanded automatically to contain the
  3632. specified row and column, using this function.
  3633. \see simplify
  3634. */
  3635. void QCPLayoutGrid::expandTo(int newRowCount, int newColumnCount)
  3636. {
  3637. // add rows as necessary:
  3638. while (rowCount() < newRowCount)
  3639. {
  3640. mElements.append(QList<QCPLayoutElement*>());
  3641. mRowStretchFactors.append(1);
  3642. }
  3643. // go through rows and expand columns as necessary:
  3644. int newColCount = qMax(columnCount(), newColumnCount);
  3645. for (int i=0; i<rowCount(); ++i)
  3646. {
  3647. while (mElements.at(i).size() < newColCount)
  3648. mElements[i].append(nullptr);
  3649. }
  3650. while (mColumnStretchFactors.size() < newColCount)
  3651. mColumnStretchFactors.append(1);
  3652. }
  3653. /*!
  3654. Inserts a new row with empty cells at the row index \a newIndex. Valid values for \a newIndex
  3655. range from 0 (inserts a row at the top) to \a rowCount (appends a row at the bottom).
  3656. \see insertColumn
  3657. */
  3658. void QCPLayoutGrid::insertRow(int newIndex)
  3659. {
  3660. if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
  3661. {
  3662. expandTo(1, 1);
  3663. return;
  3664. }
  3665. if (newIndex < 0)
  3666. newIndex = 0;
  3667. if (newIndex > rowCount())
  3668. newIndex = rowCount();
  3669. mRowStretchFactors.insert(newIndex, 1);
  3670. QList<QCPLayoutElement*> newRow;
  3671. for (int col=0; col<columnCount(); ++col)
  3672. newRow.append(nullptr);
  3673. mElements.insert(newIndex, newRow);
  3674. }
  3675. /*!
  3676. Inserts a new column with empty cells at the column index \a newIndex. Valid values for \a
  3677. newIndex range from 0 (inserts a column at the left) to \a columnCount (appends a column at the
  3678. right).
  3679. \see insertRow
  3680. */
  3681. void QCPLayoutGrid::insertColumn(int newIndex)
  3682. {
  3683. if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
  3684. {
  3685. expandTo(1, 1);
  3686. return;
  3687. }
  3688. if (newIndex < 0)
  3689. newIndex = 0;
  3690. if (newIndex > columnCount())
  3691. newIndex = columnCount();
  3692. mColumnStretchFactors.insert(newIndex, 1);
  3693. for (int row=0; row<rowCount(); ++row)
  3694. mElements[row].insert(newIndex, nullptr);
  3695. }
  3696. /*!
  3697. Converts the given \a row and \a column to the linear index used by some methods of \ref
  3698. QCPLayoutGrid and \ref QCPLayout.
  3699. The way the cells are indexed depends on \ref setFillOrder. If it is \ref foRowsFirst, the
  3700. indices increase left to right and then top to bottom. If it is \ref foColumnsFirst, the indices
  3701. increase top to bottom and then left to right.
  3702. For the returned index to be valid, \a row and \a column must be valid indices themselves, i.e.
  3703. greater or equal to zero and smaller than the current \ref rowCount/\ref columnCount.
  3704. \see indexToRowCol
  3705. */
  3706. int QCPLayoutGrid::rowColToIndex(int row, int column) const
  3707. {
  3708. if (row >= 0 && row < rowCount())
  3709. {
  3710. if (column >= 0 && column < columnCount())
  3711. {
  3712. switch (mFillOrder)
  3713. {
  3714. case foRowsFirst: return column*rowCount() + row;
  3715. case foColumnsFirst: return row*columnCount() + column;
  3716. }
  3717. } else
  3718. qDebug() << Q_FUNC_INFO << "row index out of bounds:" << row;
  3719. } else
  3720. qDebug() << Q_FUNC_INFO << "column index out of bounds:" << column;
  3721. return 0;
  3722. }
  3723. /*!
  3724. Converts the linear index to row and column indices and writes the result to \a row and \a
  3725. column.
  3726. The way the cells are indexed depends on \ref setFillOrder. If it is \ref foRowsFirst, the
  3727. indices increase left to right and then top to bottom. If it is \ref foColumnsFirst, the indices
  3728. increase top to bottom and then left to right.
  3729. If there are no cells (i.e. column or row count is zero), sets \a row and \a column to -1.
  3730. For the retrieved \a row and \a column to be valid, the passed \a index must be valid itself,
  3731. i.e. greater or equal to zero and smaller than the current \ref elementCount.
  3732. \see rowColToIndex
  3733. */
  3734. void QCPLayoutGrid::indexToRowCol(int index, int &row, int &column) const
  3735. {
  3736. row = -1;
  3737. column = -1;
  3738. const int nCols = columnCount();
  3739. const int nRows = rowCount();
  3740. if (nCols == 0 || nRows == 0)
  3741. return;
  3742. if (index < 0 || index >= elementCount())
  3743. {
  3744. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  3745. return;
  3746. }
  3747. switch (mFillOrder)
  3748. {
  3749. case foRowsFirst:
  3750. {
  3751. column = index / nRows;
  3752. row = index % nRows;
  3753. break;
  3754. }
  3755. case foColumnsFirst:
  3756. {
  3757. row = index / nCols;
  3758. column = index % nCols;
  3759. break;
  3760. }
  3761. }
  3762. }
  3763. /* inherits documentation from base class */
  3764. void QCPLayoutGrid::updateLayout()
  3765. {
  3766. QVector<int> minColWidths, minRowHeights, maxColWidths, maxRowHeights;
  3767. getMinimumRowColSizes(&minColWidths, &minRowHeights);
  3768. getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
  3769. int totalRowSpacing = (rowCount()-1) * mRowSpacing;
  3770. int totalColSpacing = (columnCount()-1) * mColumnSpacing;
  3771. QVector<int> colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing);
  3772. QVector<int> rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing);
  3773. // go through cells and set rects accordingly:
  3774. int yOffset = mRect.top();
  3775. for (int row=0; row<rowCount(); ++row)
  3776. {
  3777. if (row > 0)
  3778. yOffset += rowHeights.at(row-1)+mRowSpacing;
  3779. int xOffset = mRect.left();
  3780. for (int col=0; col<columnCount(); ++col)
  3781. {
  3782. if (col > 0)
  3783. xOffset += colWidths.at(col-1)+mColumnSpacing;
  3784. if (mElements.at(row).at(col))
  3785. mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row)));
  3786. }
  3787. }
  3788. }
  3789. /*!
  3790. \seebaseclassmethod
  3791. Note that the association of the linear \a index to the row/column based cells depends on the
  3792. current setting of \ref setFillOrder.
  3793. \see rowColToIndex
  3794. */
  3795. QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const
  3796. {
  3797. if (index >= 0 && index < elementCount())
  3798. {
  3799. int row, col;
  3800. indexToRowCol(index, row, col);
  3801. return mElements.at(row).at(col);
  3802. } else
  3803. return nullptr;
  3804. }
  3805. /*!
  3806. \seebaseclassmethod
  3807. Note that the association of the linear \a index to the row/column based cells depends on the
  3808. current setting of \ref setFillOrder.
  3809. \see rowColToIndex
  3810. */
  3811. QCPLayoutElement *QCPLayoutGrid::takeAt(int index)
  3812. {
  3813. if (QCPLayoutElement *el = elementAt(index))
  3814. {
  3815. releaseElement(el);
  3816. int row, col;
  3817. indexToRowCol(index, row, col);
  3818. mElements[row][col] = nullptr;
  3819. return el;
  3820. } else
  3821. {
  3822. qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
  3823. return nullptr;
  3824. }
  3825. }
  3826. /* inherits documentation from base class */
  3827. bool QCPLayoutGrid::take(QCPLayoutElement *element)
  3828. {
  3829. if (element)
  3830. {
  3831. for (int i=0; i<elementCount(); ++i)
  3832. {
  3833. if (elementAt(i) == element)
  3834. {
  3835. takeAt(i);
  3836. return true;
  3837. }
  3838. }
  3839. qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
  3840. } else
  3841. qDebug() << Q_FUNC_INFO << "Can't take nullptr element";
  3842. return false;
  3843. }
  3844. /* inherits documentation from base class */
  3845. QList<QCPLayoutElement*> QCPLayoutGrid::elements(bool recursive) const
  3846. {
  3847. QList<QCPLayoutElement*> result;
  3848. const int elCount = elementCount();
  3849. #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
  3850. result.reserve(elCount);
  3851. #endif
  3852. for (int i=0; i<elCount; ++i)
  3853. result.append(elementAt(i));
  3854. if (recursive)
  3855. {
  3856. for (int i=0; i<elCount; ++i)
  3857. {
  3858. if (result.at(i))
  3859. result << result.at(i)->elements(recursive);
  3860. }
  3861. }
  3862. return result;
  3863. }
  3864. /*!
  3865. Simplifies the layout by collapsing rows and columns which only contain empty cells.
  3866. */
  3867. void QCPLayoutGrid::simplify()
  3868. {
  3869. // remove rows with only empty cells:
  3870. for (int row=rowCount()-1; row>=0; --row)
  3871. {
  3872. bool hasElements = false;
  3873. for (int col=0; col<columnCount(); ++col)
  3874. {
  3875. if (mElements.at(row).at(col))
  3876. {
  3877. hasElements = true;
  3878. break;
  3879. }
  3880. }
  3881. if (!hasElements)
  3882. {
  3883. mRowStretchFactors.removeAt(row);
  3884. mElements.removeAt(row);
  3885. if (mElements.isEmpty()) // removed last element, also remove stretch factor (wouldn't happen below because also columnCount changed to 0 now)
  3886. mColumnStretchFactors.clear();
  3887. }
  3888. }
  3889. // remove columns with only empty cells:
  3890. for (int col=columnCount()-1; col>=0; --col)
  3891. {
  3892. bool hasElements = false;
  3893. for (int row=0; row<rowCount(); ++row)
  3894. {
  3895. if (mElements.at(row).at(col))
  3896. {
  3897. hasElements = true;
  3898. break;
  3899. }
  3900. }
  3901. if (!hasElements)
  3902. {
  3903. mColumnStretchFactors.removeAt(col);
  3904. for (int row=0; row<rowCount(); ++row)
  3905. mElements[row].removeAt(col);
  3906. }
  3907. }
  3908. }
  3909. /* inherits documentation from base class */
  3910. QSize QCPLayoutGrid::minimumOuterSizeHint() const
  3911. {
  3912. QVector<int> minColWidths, minRowHeights;
  3913. getMinimumRowColSizes(&minColWidths, &minRowHeights);
  3914. QSize result(0, 0);
  3915. foreach (int w, minColWidths)
  3916. result.rwidth() += w;
  3917. foreach (int h, minRowHeights)
  3918. result.rheight() += h;
  3919. result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing;
  3920. result.rheight() += qMax(0, rowCount()-1) * mRowSpacing;
  3921. result.rwidth() += mMargins.left()+mMargins.right();
  3922. result.rheight() += mMargins.top()+mMargins.bottom();
  3923. return result;
  3924. }
  3925. /* inherits documentation from base class */
  3926. QSize QCPLayoutGrid::maximumOuterSizeHint() const
  3927. {
  3928. QVector<int> maxColWidths, maxRowHeights;
  3929. getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
  3930. QSize result(0, 0);
  3931. foreach (int w, maxColWidths)
  3932. result.setWidth(qMin(result.width()+w, QWIDGETSIZE_MAX));
  3933. foreach (int h, maxRowHeights)
  3934. result.setHeight(qMin(result.height()+h, QWIDGETSIZE_MAX));
  3935. result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing;
  3936. result.rheight() += qMax(0, rowCount()-1) * mRowSpacing;
  3937. result.rwidth() += mMargins.left()+mMargins.right();
  3938. result.rheight() += mMargins.top()+mMargins.bottom();
  3939. if (result.height() > QWIDGETSIZE_MAX)
  3940. result.setHeight(QWIDGETSIZE_MAX);
  3941. if (result.width() > QWIDGETSIZE_MAX)
  3942. result.setWidth(QWIDGETSIZE_MAX);
  3943. return result;
  3944. }
  3945. /*! \internal
  3946. Places the minimum column widths and row heights into \a minColWidths and \a minRowHeights
  3947. respectively.
  3948. The minimum height of a row is the largest minimum height of any element's outer rect in that
  3949. row. The minimum width of a column is the largest minimum width of any element's outer rect in
  3950. that column.
  3951. This is a helper function for \ref updateLayout.
  3952. \see getMaximumRowColSizes
  3953. */
  3954. void QCPLayoutGrid::getMinimumRowColSizes(QVector<int> *minColWidths, QVector<int> *minRowHeights) const
  3955. {
  3956. *minColWidths = QVector<int>(columnCount(), 0);
  3957. *minRowHeights = QVector<int>(rowCount(), 0);
  3958. for (int row=0; row<rowCount(); ++row)
  3959. {
  3960. for (int col=0; col<columnCount(); ++col)
  3961. {
  3962. if (QCPLayoutElement *el = mElements.at(row).at(col))
  3963. {
  3964. QSize minSize = getFinalMinimumOuterSize(el);
  3965. if (minColWidths->at(col) < minSize.width())
  3966. (*minColWidths)[col] = minSize.width();
  3967. if (minRowHeights->at(row) < minSize.height())
  3968. (*minRowHeights)[row] = minSize.height();
  3969. }
  3970. }
  3971. }
  3972. }
  3973. /*! \internal
  3974. Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights
  3975. respectively.
  3976. The maximum height of a row is the smallest maximum height of any element's outer rect in that
  3977. row. The maximum width of a column is the smallest maximum width of any element's outer rect in
  3978. that column.
  3979. This is a helper function for \ref updateLayout.
  3980. \see getMinimumRowColSizes
  3981. */
  3982. void QCPLayoutGrid::getMaximumRowColSizes(QVector<int> *maxColWidths, QVector<int> *maxRowHeights) const
  3983. {
  3984. *maxColWidths = QVector<int>(columnCount(), QWIDGETSIZE_MAX);
  3985. *maxRowHeights = QVector<int>(rowCount(), QWIDGETSIZE_MAX);
  3986. for (int row=0; row<rowCount(); ++row)
  3987. {
  3988. for (int col=0; col<columnCount(); ++col)
  3989. {
  3990. if (QCPLayoutElement *el = mElements.at(row).at(col))
  3991. {
  3992. QSize maxSize = getFinalMaximumOuterSize(el);
  3993. if (maxColWidths->at(col) > maxSize.width())
  3994. (*maxColWidths)[col] = maxSize.width();
  3995. if (maxRowHeights->at(row) > maxSize.height())
  3996. (*maxRowHeights)[row] = maxSize.height();
  3997. }
  3998. }
  3999. }
  4000. }
  4001. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4002. //////////////////// QCPLayoutInset
  4003. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4004. /*! \class QCPLayoutInset
  4005. \brief A layout that places child elements aligned to the border or arbitrarily positioned
  4006. Elements are placed either aligned to the border or at arbitrary position in the area of the
  4007. layout. Which placement applies is controlled with the \ref InsetPlacement (\ref
  4008. setInsetPlacement).
  4009. Elements are added via \ref addElement(QCPLayoutElement *element, Qt::Alignment alignment) or
  4010. addElement(QCPLayoutElement *element, const QRectF &rect). If the first method is used, the inset
  4011. placement will default to \ref ipBorderAligned and the element will be aligned according to the
  4012. \a alignment parameter. The second method defaults to \ref ipFree and allows placing elements at
  4013. arbitrary position and size, defined by \a rect.
  4014. The alignment or rect can be set via \ref setInsetAlignment or \ref setInsetRect, respectively.
  4015. This is the layout that every QCPAxisRect has as \ref QCPAxisRect::insetLayout.
  4016. */
  4017. /* start documentation of inline functions */
  4018. /*! \fn virtual void QCPLayoutInset::simplify()
  4019. The QCPInsetLayout does not need simplification since it can never have empty cells due to its
  4020. linear index structure. This method does nothing.
  4021. */
  4022. /* end documentation of inline functions */
  4023. /*!
  4024. Creates an instance of QCPLayoutInset and sets default values.
  4025. */
  4026. QCPLayoutInset::QCPLayoutInset()
  4027. {
  4028. }
  4029. QCPLayoutInset::~QCPLayoutInset()
  4030. {
  4031. // clear all child layout elements. This is important because only the specific layouts know how
  4032. // to handle removing elements (clear calls virtual removeAt method to do that).
  4033. clear();
  4034. }
  4035. /*!
  4036. Returns the placement type of the element with the specified \a index.
  4037. */
  4038. QCPLayoutInset::InsetPlacement QCPLayoutInset::insetPlacement(int index) const
  4039. {
  4040. if (elementAt(index))
  4041. return mInsetPlacement.at(index);
  4042. else
  4043. {
  4044. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4045. return ipFree;
  4046. }
  4047. }
  4048. /*!
  4049. Returns the alignment of the element with the specified \a index. The alignment only has a
  4050. meaning, if the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned.
  4051. */
  4052. Qt::Alignment QCPLayoutInset::insetAlignment(int index) const
  4053. {
  4054. if (elementAt(index))
  4055. return mInsetAlignment.at(index);
  4056. else
  4057. {
  4058. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4059. #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0)
  4060. return nullptr;
  4061. #else
  4062. return {};
  4063. #endif
  4064. }
  4065. }
  4066. /*!
  4067. Returns the rect of the element with the specified \a index. The rect only has a
  4068. meaning, if the inset placement (\ref setInsetPlacement) is \ref ipFree.
  4069. */
  4070. QRectF QCPLayoutInset::insetRect(int index) const
  4071. {
  4072. if (elementAt(index))
  4073. return mInsetRect.at(index);
  4074. else
  4075. {
  4076. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4077. return {};
  4078. }
  4079. }
  4080. /*!
  4081. Sets the inset placement type of the element with the specified \a index to \a placement.
  4082. \see InsetPlacement
  4083. */
  4084. void QCPLayoutInset::setInsetPlacement(int index, QCPLayoutInset::InsetPlacement placement)
  4085. {
  4086. if (elementAt(index))
  4087. mInsetPlacement[index] = placement;
  4088. else
  4089. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4090. }
  4091. /*!
  4092. If the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned, this function
  4093. is used to set the alignment of the element with the specified \a index to \a alignment.
  4094. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
  4095. Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
  4096. alignment flags will be ignored.
  4097. */
  4098. void QCPLayoutInset::setInsetAlignment(int index, Qt::Alignment alignment)
  4099. {
  4100. if (elementAt(index))
  4101. mInsetAlignment[index] = alignment;
  4102. else
  4103. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4104. }
  4105. /*!
  4106. If the inset placement (\ref setInsetPlacement) is \ref ipFree, this function is used to set the
  4107. position and size of the element with the specified \a index to \a rect.
  4108. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
  4109. will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
  4110. corner of the layout, with 35% width and height of the parent layout.
  4111. Note that the minimum and maximum sizes of the embedded element (\ref
  4112. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize) are enforced.
  4113. */
  4114. void QCPLayoutInset::setInsetRect(int index, const QRectF &rect)
  4115. {
  4116. if (elementAt(index))
  4117. mInsetRect[index] = rect;
  4118. else
  4119. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4120. }
  4121. /* inherits documentation from base class */
  4122. void QCPLayoutInset::updateLayout()
  4123. {
  4124. for (int i=0; i<mElements.size(); ++i)
  4125. {
  4126. QCPLayoutElement *el = mElements.at(i);
  4127. QRect insetRect;
  4128. QSize finalMinSize = getFinalMinimumOuterSize(el);
  4129. QSize finalMaxSize = getFinalMaximumOuterSize(el);
  4130. if (mInsetPlacement.at(i) == ipFree)
  4131. {
  4132. insetRect = QRect(int( rect().x()+rect().width()*mInsetRect.at(i).x() ),
  4133. int( rect().y()+rect().height()*mInsetRect.at(i).y() ),
  4134. int( rect().width()*mInsetRect.at(i).width() ),
  4135. int( rect().height()*mInsetRect.at(i).height() ));
  4136. if (insetRect.size().width() < finalMinSize.width())
  4137. insetRect.setWidth(finalMinSize.width());
  4138. if (insetRect.size().height() < finalMinSize.height())
  4139. insetRect.setHeight(finalMinSize.height());
  4140. if (insetRect.size().width() > finalMaxSize.width())
  4141. insetRect.setWidth(finalMaxSize.width());
  4142. if (insetRect.size().height() > finalMaxSize.height())
  4143. insetRect.setHeight(finalMaxSize.height());
  4144. } else if (mInsetPlacement.at(i) == ipBorderAligned)
  4145. {
  4146. insetRect.setSize(finalMinSize);
  4147. Qt::Alignment al = mInsetAlignment.at(i);
  4148. if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x());
  4149. else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width());
  4150. else insetRect.moveLeft(int( rect().x()+rect().width()*0.5-finalMinSize.width()*0.5 )); // default to Qt::AlignHCenter
  4151. if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y());
  4152. else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height());
  4153. else insetRect.moveTop(int( rect().y()+rect().height()*0.5-finalMinSize.height()*0.5 )); // default to Qt::AlignVCenter
  4154. }
  4155. mElements.at(i)->setOuterRect(insetRect);
  4156. }
  4157. }
  4158. /* inherits documentation from base class */
  4159. int QCPLayoutInset::elementCount() const
  4160. {
  4161. return mElements.size();
  4162. }
  4163. /* inherits documentation from base class */
  4164. QCPLayoutElement *QCPLayoutInset::elementAt(int index) const
  4165. {
  4166. if (index >= 0 && index < mElements.size())
  4167. return mElements.at(index);
  4168. else
  4169. return nullptr;
  4170. }
  4171. /* inherits documentation from base class */
  4172. QCPLayoutElement *QCPLayoutInset::takeAt(int index)
  4173. {
  4174. if (QCPLayoutElement *el = elementAt(index))
  4175. {
  4176. releaseElement(el);
  4177. mElements.removeAt(index);
  4178. mInsetPlacement.removeAt(index);
  4179. mInsetAlignment.removeAt(index);
  4180. mInsetRect.removeAt(index);
  4181. return el;
  4182. } else
  4183. {
  4184. qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
  4185. return nullptr;
  4186. }
  4187. }
  4188. /* inherits documentation from base class */
  4189. bool QCPLayoutInset::take(QCPLayoutElement *element)
  4190. {
  4191. if (element)
  4192. {
  4193. for (int i=0; i<elementCount(); ++i)
  4194. {
  4195. if (elementAt(i) == element)
  4196. {
  4197. takeAt(i);
  4198. return true;
  4199. }
  4200. }
  4201. qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
  4202. } else
  4203. qDebug() << Q_FUNC_INFO << "Can't take nullptr element";
  4204. return false;
  4205. }
  4206. /*!
  4207. The inset layout is sensitive to events only at areas where its (visible) child elements are
  4208. sensitive. If the selectTest method of any of the child elements returns a positive number for \a
  4209. pos, this method returns a value corresponding to 0.99 times the parent plot's selection
  4210. tolerance. The inset layout is not selectable itself by default. So if \a onlySelectable is true,
  4211. -1.0 is returned.
  4212. See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
  4213. */
  4214. double QCPLayoutInset::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  4215. {
  4216. Q_UNUSED(details)
  4217. if (onlySelectable)
  4218. return -1;
  4219. foreach (QCPLayoutElement *el, mElements)
  4220. {
  4221. // inset layout shall only return positive selectTest, if actually an inset object is at pos
  4222. // else it would block the entire underlying QCPAxisRect with its surface.
  4223. if (el->realVisibility() && el->selectTest(pos, onlySelectable) >= 0)
  4224. return mParentPlot->selectionTolerance()*0.99;
  4225. }
  4226. return -1;
  4227. }
  4228. /*!
  4229. Adds the specified \a element to the layout as an inset aligned at the border (\ref
  4230. setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a
  4231. alignment.
  4232. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
  4233. Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
  4234. alignment flags will be ignored.
  4235. \see addElement(QCPLayoutElement *element, const QRectF &rect)
  4236. */
  4237. void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment)
  4238. {
  4239. if (element)
  4240. {
  4241. if (element->layout()) // remove from old layout first
  4242. element->layout()->take(element);
  4243. mElements.append(element);
  4244. mInsetPlacement.append(ipBorderAligned);
  4245. mInsetAlignment.append(alignment);
  4246. mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4));
  4247. adoptElement(element);
  4248. } else
  4249. qDebug() << Q_FUNC_INFO << "Can't add nullptr element";
  4250. }
  4251. /*!
  4252. Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref
  4253. setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a
  4254. rect.
  4255. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
  4256. will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
  4257. corner of the layout, with 35% width and height of the parent layout.
  4258. \see addElement(QCPLayoutElement *element, Qt::Alignment alignment)
  4259. */
  4260. void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect)
  4261. {
  4262. if (element)
  4263. {
  4264. if (element->layout()) // remove from old layout first
  4265. element->layout()->take(element);
  4266. mElements.append(element);
  4267. mInsetPlacement.append(ipFree);
  4268. mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop);
  4269. mInsetRect.append(rect);
  4270. adoptElement(element);
  4271. } else
  4272. qDebug() << Q_FUNC_INFO << "Can't add nullptr element";
  4273. }
  4274. /* end of 'src/layout.cpp' */
  4275. /* including file 'src/lineending.cpp' */
  4276. /* modified 2022-11-06T12:45:56, size 11189 */
  4277. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4278. //////////////////// QCPLineEnding
  4279. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4280. /*! \class QCPLineEnding
  4281. \brief Handles the different ending decorations for line-like items
  4282. \image html QCPLineEnding.png "The various ending styles currently supported"
  4283. For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine
  4284. has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail.
  4285. The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can
  4286. be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of
  4287. the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item.
  4288. For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite
  4289. directions, e.g. "outward". This can be changed by \ref setInverted, which would make the
  4290. respective arrow point inward.
  4291. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a
  4292. QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g.
  4293. \snippet documentation/doc-code-snippets/mainwindow.cpp qcplineending-sethead
  4294. */
  4295. /*!
  4296. Creates a QCPLineEnding instance with default values (style \ref esNone).
  4297. */
  4298. QCPLineEnding::QCPLineEnding() :
  4299. mStyle(esNone),
  4300. mWidth(8),
  4301. mLength(10),
  4302. mInverted(false)
  4303. {
  4304. }
  4305. /*!
  4306. Creates a QCPLineEnding instance with the specified values.
  4307. */
  4308. QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) :
  4309. mStyle(style),
  4310. mWidth(width),
  4311. mLength(length),
  4312. mInverted(inverted)
  4313. {
  4314. }
  4315. /*!
  4316. Sets the style of the ending decoration.
  4317. */
  4318. void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style)
  4319. {
  4320. mStyle = style;
  4321. }
  4322. /*!
  4323. Sets the width of the ending decoration, if the style supports it. On arrows, for example, the
  4324. width defines the size perpendicular to the arrow's pointing direction.
  4325. \see setLength
  4326. */
  4327. void QCPLineEnding::setWidth(double width)
  4328. {
  4329. mWidth = width;
  4330. }
  4331. /*!
  4332. Sets the length of the ending decoration, if the style supports it. On arrows, for example, the
  4333. length defines the size in pointing direction.
  4334. \see setWidth
  4335. */
  4336. void QCPLineEnding::setLength(double length)
  4337. {
  4338. mLength = length;
  4339. }
  4340. /*!
  4341. Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point
  4342. inward when \a inverted is set to true.
  4343. Note that also the \a width direction is inverted. For symmetrical ending styles like arrows or
  4344. discs, this doesn't make a difference. However, asymmetric styles like \ref esHalfBar are
  4345. affected by it, which can be used to control to which side the half bar points to.
  4346. */
  4347. void QCPLineEnding::setInverted(bool inverted)
  4348. {
  4349. mInverted = inverted;
  4350. }
  4351. /*! \internal
  4352. Returns the maximum pixel radius the ending decoration might cover, starting from the position
  4353. the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item).
  4354. This is relevant for clipping. Only omit painting of the decoration when the position where the
  4355. decoration is supposed to be drawn is farther away from the clipping rect than the returned
  4356. distance.
  4357. */
  4358. double QCPLineEnding::boundingDistance() const
  4359. {
  4360. switch (mStyle)
  4361. {
  4362. case esNone:
  4363. return 0;
  4364. case esFlatArrow:
  4365. case esSpikeArrow:
  4366. case esLineArrow:
  4367. case esSkewedBar:
  4368. return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length
  4369. case esDisc:
  4370. case esSquare:
  4371. case esDiamond:
  4372. case esBar:
  4373. case esHalfBar:
  4374. return mWidth*1.42; // items that only have a width -> width*sqrt(2)
  4375. }
  4376. return 0;
  4377. }
  4378. /*!
  4379. Starting from the origin of this line ending (which is style specific), returns the length
  4380. covered by the line ending symbol, in backward direction.
  4381. For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if
  4382. both have the same \ref setLength value, because the spike arrow has an inward curved back, which
  4383. reduces the length along its center axis (the drawing origin for arrows is at the tip).
  4384. This function is used for precise, style specific placement of line endings, for example in
  4385. QCPAxes.
  4386. */
  4387. double QCPLineEnding::realLength() const
  4388. {
  4389. switch (mStyle)
  4390. {
  4391. case esNone:
  4392. case esLineArrow:
  4393. case esSkewedBar:
  4394. case esBar:
  4395. case esHalfBar:
  4396. return 0;
  4397. case esFlatArrow:
  4398. return mLength;
  4399. case esDisc:
  4400. case esSquare:
  4401. case esDiamond:
  4402. return mWidth*0.5;
  4403. case esSpikeArrow:
  4404. return mLength*0.8;
  4405. }
  4406. return 0;
  4407. }
  4408. /*! \internal
  4409. Draws the line ending with the specified \a painter at the position \a pos. The direction of the
  4410. line ending is controlled with \a dir.
  4411. */
  4412. void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, const QCPVector2D &dir) const
  4413. {
  4414. if (mStyle == esNone)
  4415. return;
  4416. QCPVector2D lengthVec = dir.normalized() * mLength*(mInverted ? -1 : 1);
  4417. if (lengthVec.isNull())
  4418. lengthVec = QCPVector2D(1, 0);
  4419. QCPVector2D widthVec = dir.normalized().perpendicular() * mWidth*0.5*(mInverted ? -1 : 1);
  4420. QPen penBackup = painter->pen();
  4421. QBrush brushBackup = painter->brush();
  4422. QPen miterPen = penBackup;
  4423. miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey
  4424. QBrush brush(painter->pen().color(), Qt::SolidPattern);
  4425. switch (mStyle)
  4426. {
  4427. case esNone: break;
  4428. case esFlatArrow:
  4429. {
  4430. QPointF points[3] = {pos.toPointF(),
  4431. (pos-lengthVec+widthVec).toPointF(),
  4432. (pos-lengthVec-widthVec).toPointF()
  4433. };
  4434. painter->setPen(miterPen);
  4435. painter->setBrush(brush);
  4436. painter->drawConvexPolygon(points, 3);
  4437. painter->setBrush(brushBackup);
  4438. painter->setPen(penBackup);
  4439. break;
  4440. }
  4441. case esSpikeArrow:
  4442. {
  4443. QPointF points[4] = {pos.toPointF(),
  4444. (pos-lengthVec+widthVec).toPointF(),
  4445. (pos-lengthVec*0.8).toPointF(),
  4446. (pos-lengthVec-widthVec).toPointF()
  4447. };
  4448. painter->setPen(miterPen);
  4449. painter->setBrush(brush);
  4450. painter->drawConvexPolygon(points, 4);
  4451. painter->setBrush(brushBackup);
  4452. painter->setPen(penBackup);
  4453. break;
  4454. }
  4455. case esLineArrow:
  4456. {
  4457. QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(),
  4458. pos.toPointF(),
  4459. (pos-lengthVec-widthVec).toPointF()
  4460. };
  4461. painter->setPen(miterPen);
  4462. painter->drawPolyline(points, 3);
  4463. painter->setPen(penBackup);
  4464. break;
  4465. }
  4466. case esDisc:
  4467. {
  4468. painter->setBrush(brush);
  4469. painter->drawEllipse(pos.toPointF(), mWidth*0.5, mWidth*0.5);
  4470. painter->setBrush(brushBackup);
  4471. break;
  4472. }
  4473. case esSquare:
  4474. {
  4475. QCPVector2D widthVecPerp = widthVec.perpendicular();
  4476. QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(),
  4477. (pos-widthVecPerp-widthVec).toPointF(),
  4478. (pos+widthVecPerp-widthVec).toPointF(),
  4479. (pos+widthVecPerp+widthVec).toPointF()
  4480. };
  4481. painter->setPen(miterPen);
  4482. painter->setBrush(brush);
  4483. painter->drawConvexPolygon(points, 4);
  4484. painter->setBrush(brushBackup);
  4485. painter->setPen(penBackup);
  4486. break;
  4487. }
  4488. case esDiamond:
  4489. {
  4490. QCPVector2D widthVecPerp = widthVec.perpendicular();
  4491. QPointF points[4] = {(pos-widthVecPerp).toPointF(),
  4492. (pos-widthVec).toPointF(),
  4493. (pos+widthVecPerp).toPointF(),
  4494. (pos+widthVec).toPointF()
  4495. };
  4496. painter->setPen(miterPen);
  4497. painter->setBrush(brush);
  4498. painter->drawConvexPolygon(points, 4);
  4499. painter->setBrush(brushBackup);
  4500. painter->setPen(penBackup);
  4501. break;
  4502. }
  4503. case esBar:
  4504. {
  4505. painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF());
  4506. break;
  4507. }
  4508. case esHalfBar:
  4509. {
  4510. painter->drawLine((pos+widthVec).toPointF(), pos.toPointF());
  4511. break;
  4512. }
  4513. case esSkewedBar:
  4514. {
  4515. QCPVector2D shift;
  4516. if (!qFuzzyIsNull(painter->pen().widthF()) || painter->modes().testFlag(QCPPainter::pmNonCosmetic))
  4517. shift = dir.normalized()*qMax(qreal(1.0), painter->pen().widthF())*qreal(0.5);
  4518. // if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly
  4519. painter->drawLine((pos+widthVec+lengthVec*0.2*(mInverted?-1:1)+shift).toPointF(),
  4520. (pos-widthVec-lengthVec*0.2*(mInverted?-1:1)+shift).toPointF());
  4521. break;
  4522. }
  4523. }
  4524. }
  4525. /*! \internal
  4526. \overload
  4527. Draws the line ending. The direction is controlled with the \a angle parameter in radians.
  4528. */
  4529. void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, double angle) const
  4530. {
  4531. draw(painter, pos, QCPVector2D(qCos(angle), qSin(angle)));
  4532. }
  4533. /* end of 'src/lineending.cpp' */
  4534. /* including file 'src/axis/labelpainter.cpp' */
  4535. /* modified 2022-11-06T12:45:56, size 27519 */
  4536. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4537. //////////////////// QCPLabelPainterPrivate
  4538. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4539. /*! \class QCPLabelPainterPrivate
  4540. \internal
  4541. \brief (Private)
  4542. This is a private class and not part of the public QCustomPlot interface.
  4543. */
  4544. const QChar QCPLabelPainterPrivate::SymbolDot(183);
  4545. const QChar QCPLabelPainterPrivate::SymbolCross(215);
  4546. /*!
  4547. Constructs a QCPLabelPainterPrivate instance. Make sure to not create a new
  4548. instance on every redraw, to utilize the caching mechanisms.
  4549. the \a parentPlot does not take ownership of the label painter. Make sure
  4550. to delete it appropriately.
  4551. */
  4552. QCPLabelPainterPrivate::QCPLabelPainterPrivate(QCustomPlot *parentPlot) :
  4553. mAnchorMode(amRectangular),
  4554. mAnchorSide(asLeft),
  4555. mAnchorReferenceType(artNormal),
  4556. mColor(Qt::black),
  4557. mPadding(0),
  4558. mRotation(0),
  4559. mSubstituteExponent(true),
  4560. mMultiplicationSymbol(QChar(215)),
  4561. mAbbreviateDecimalPowers(false),
  4562. mParentPlot(parentPlot),
  4563. mLabelCache(16)
  4564. {
  4565. analyzeFontMetrics();
  4566. }
  4567. QCPLabelPainterPrivate::~QCPLabelPainterPrivate()
  4568. {
  4569. }
  4570. void QCPLabelPainterPrivate::setAnchorSide(AnchorSide side)
  4571. {
  4572. mAnchorSide = side;
  4573. }
  4574. void QCPLabelPainterPrivate::setAnchorMode(AnchorMode mode)
  4575. {
  4576. mAnchorMode = mode;
  4577. }
  4578. void QCPLabelPainterPrivate::setAnchorReference(const QPointF &pixelPoint)
  4579. {
  4580. mAnchorReference = pixelPoint;
  4581. }
  4582. void QCPLabelPainterPrivate::setAnchorReferenceType(AnchorReferenceType type)
  4583. {
  4584. mAnchorReferenceType = type;
  4585. }
  4586. void QCPLabelPainterPrivate::setFont(const QFont &font)
  4587. {
  4588. if (mFont != font)
  4589. {
  4590. mFont = font;
  4591. analyzeFontMetrics();
  4592. }
  4593. }
  4594. void QCPLabelPainterPrivate::setColor(const QColor &color)
  4595. {
  4596. mColor = color;
  4597. }
  4598. void QCPLabelPainterPrivate::setPadding(int padding)
  4599. {
  4600. mPadding = padding;
  4601. }
  4602. void QCPLabelPainterPrivate::setRotation(double rotation)
  4603. {
  4604. mRotation = qBound(-90.0, rotation, 90.0);
  4605. }
  4606. void QCPLabelPainterPrivate::setSubstituteExponent(bool enabled)
  4607. {
  4608. mSubstituteExponent = enabled;
  4609. }
  4610. void QCPLabelPainterPrivate::setMultiplicationSymbol(QChar symbol)
  4611. {
  4612. mMultiplicationSymbol = symbol;
  4613. }
  4614. void QCPLabelPainterPrivate::setAbbreviateDecimalPowers(bool enabled)
  4615. {
  4616. mAbbreviateDecimalPowers = enabled;
  4617. }
  4618. void QCPLabelPainterPrivate::setCacheSize(int labelCount)
  4619. {
  4620. mLabelCache.setMaxCost(labelCount);
  4621. }
  4622. int QCPLabelPainterPrivate::cacheSize() const
  4623. {
  4624. return mLabelCache.maxCost();
  4625. }
  4626. void QCPLabelPainterPrivate::drawTickLabel(QCPPainter *painter, const QPointF &tickPos, const QString &text)
  4627. {
  4628. double realRotation = mRotation;
  4629. AnchorSide realSide = mAnchorSide;
  4630. // for circular axes, the anchor side is determined depending on the quadrant of tickPos with respect to mCircularReference
  4631. if (mAnchorMode == amSkewedUpright)
  4632. {
  4633. realSide = skewedAnchorSide(tickPos, 0.2, 0.3);
  4634. } else if (mAnchorMode == amSkewedRotated) // in this mode every label is individually rotated to match circle tangent
  4635. {
  4636. realSide = skewedAnchorSide(tickPos, 0, 0);
  4637. realRotation += QCPVector2D(tickPos-mAnchorReference).angle()/M_PI*180.0;
  4638. if (realRotation > 90) realRotation -= 180;
  4639. else if (realRotation < -90) realRotation += 180;
  4640. }
  4641. realSide = rotationCorrectedSide(realSide, realRotation); // rotation angles may change the true anchor side of the label
  4642. drawLabelMaybeCached(painter, mFont, mColor, getAnchorPos(tickPos), realSide, realRotation, text);
  4643. }
  4644. /*! \internal
  4645. Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone
  4646. direction) needed to fit the axis.
  4647. */
  4648. /* TODO: needed?
  4649. int QCPLabelPainterPrivate::size() const
  4650. {
  4651. int result = 0;
  4652. // get length of tick marks pointing outwards:
  4653. if (!tickPositions.isEmpty())
  4654. result += qMax(0, qMax(tickLengthOut, subTickLengthOut));
  4655. // calculate size of tick labels:
  4656. if (tickLabelSide == QCPAxis::lsOutside)
  4657. {
  4658. QSize tickLabelsSize(0, 0);
  4659. if (!tickLabels.isEmpty())
  4660. {
  4661. for (int i=0; i<tickLabels.size(); ++i)
  4662. getMaxTickLabelSize(tickLabelFont, tickLabels.at(i), &tickLabelsSize);
  4663. result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width();
  4664. result += tickLabelPadding;
  4665. }
  4666. }
  4667. // calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees):
  4668. if (!label.isEmpty())
  4669. {
  4670. QFontMetrics fontMetrics(labelFont);
  4671. QRect bounds;
  4672. bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label);
  4673. result += bounds.height() + labelPadding;
  4674. }
  4675. return result;
  4676. }
  4677. */
  4678. /*! \internal
  4679. Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This
  4680. method is called automatically if any parameters have changed that invalidate the cached labels,
  4681. such as font, color, etc. Usually you won't need to call this method manually.
  4682. */
  4683. void QCPLabelPainterPrivate::clearCache()
  4684. {
  4685. mLabelCache.clear();
  4686. }
  4687. /*! \internal
  4688. Returns a hash that allows uniquely identifying whether the label parameters have changed such
  4689. that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the
  4690. return value of this method hasn't changed since the last redraw, the respective label parameters
  4691. haven't changed and cached labels may be used.
  4692. */
  4693. QByteArray QCPLabelPainterPrivate::generateLabelParameterHash() const
  4694. {
  4695. QByteArray result;
  4696. result.append(QByteArray::number(mParentPlot->bufferDevicePixelRatio()));
  4697. result.append(QByteArray::number(mRotation));
  4698. //result.append(QByteArray::number(int(tickLabelSide))); TODO: check whether this is really a cache-invalidating property
  4699. result.append(QByteArray::number(int(mSubstituteExponent)));
  4700. result.append(QString(mMultiplicationSymbol).toUtf8());
  4701. result.append(mColor.name().toLatin1()+QByteArray::number(mColor.alpha(), 16));
  4702. result.append(mFont.toString().toLatin1());
  4703. return result;
  4704. }
  4705. /*! \internal
  4706. Draws a single tick label with the provided \a painter, utilizing the internal label cache to
  4707. significantly speed up drawing of labels that were drawn in previous calls. The tick label is
  4708. always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in
  4709. pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence
  4710. for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate),
  4711. at which the label should be drawn.
  4712. In order to later draw the axis label in a place that doesn't overlap with the tick labels, the
  4713. largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref
  4714. drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a
  4715. tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently
  4716. holds.
  4717. The label is drawn with the font and pen that are currently set on the \a painter. To draw
  4718. superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref
  4719. getTickLabelData).
  4720. */
  4721. void QCPLabelPainterPrivate::drawLabelMaybeCached(QCPPainter *painter, const QFont &font, const QColor &color, const QPointF &pos, AnchorSide side, double rotation, const QString &text)
  4722. {
  4723. // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly!
  4724. if (text.isEmpty()) return;
  4725. QSize finalSize;
  4726. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled
  4727. {
  4728. QByteArray key = cacheKey(text, color, rotation, side);
  4729. CachedLabel *cachedLabel = mLabelCache.take(QString::fromUtf8(key)); // attempt to take label from cache (don't use object() because we want ownership/prevent deletion during our operations, we re-insert it afterwards)
  4730. if (!cachedLabel) // no cached label existed, create it
  4731. {
  4732. LabelData labelData = getTickLabelData(font, color, rotation, side, text);
  4733. cachedLabel = createCachedLabel(labelData);
  4734. }
  4735. // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
  4736. bool labelClippedByBorder = false;
  4737. /*
  4738. if (tickLabelSide == QCPAxis::lsOutside)
  4739. {
  4740. if (QCPAxis::orientation(type) == Qt::Horizontal)
  4741. labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width()/mParentPlot->bufferDevicePixelRatio() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left();
  4742. else
  4743. labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height()/mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top();
  4744. }
  4745. */
  4746. if (!labelClippedByBorder)
  4747. {
  4748. painter->drawPixmap(pos+cachedLabel->offset, cachedLabel->pixmap);
  4749. finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio(); // TODO: collect this in a member rect list?
  4750. }
  4751. mLabelCache.insert(QString::fromUtf8(key), cachedLabel);
  4752. } else // label caching disabled, draw text directly on surface:
  4753. {
  4754. LabelData labelData = getTickLabelData(font, color, rotation, side, text);
  4755. // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
  4756. bool labelClippedByBorder = false;
  4757. /*
  4758. if (tickLabelSide == QCPAxis::lsOutside)
  4759. {
  4760. if (QCPAxis::orientation(type) == Qt::Horizontal)
  4761. labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left();
  4762. else
  4763. labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top();
  4764. }
  4765. */
  4766. if (!labelClippedByBorder)
  4767. {
  4768. drawText(painter, pos, labelData);
  4769. finalSize = labelData.rotatedTotalBounds.size();
  4770. }
  4771. }
  4772. /*
  4773. // expand passed tickLabelsSize if current tick label is larger:
  4774. if (finalSize.width() > tickLabelsSize->width())
  4775. tickLabelsSize->setWidth(finalSize.width());
  4776. if (finalSize.height() > tickLabelsSize->height())
  4777. tickLabelsSize->setHeight(finalSize.height());
  4778. */
  4779. }
  4780. QPointF QCPLabelPainterPrivate::getAnchorPos(const QPointF &tickPos)
  4781. {
  4782. switch (mAnchorMode)
  4783. {
  4784. case amRectangular:
  4785. {
  4786. switch (mAnchorSide)
  4787. {
  4788. case asLeft: return tickPos+QPointF(mPadding, 0);
  4789. case asRight: return tickPos+QPointF(-mPadding, 0);
  4790. case asTop: return tickPos+QPointF(0, mPadding);
  4791. case asBottom: return tickPos+QPointF(0, -mPadding);
  4792. case asTopLeft: return tickPos+QPointF(mPadding*M_SQRT1_2, mPadding*M_SQRT1_2);
  4793. case asTopRight: return tickPos+QPointF(-mPadding*M_SQRT1_2, mPadding*M_SQRT1_2);
  4794. case asBottomRight: return tickPos+QPointF(-mPadding*M_SQRT1_2, -mPadding*M_SQRT1_2);
  4795. case asBottomLeft: return tickPos+QPointF(mPadding*M_SQRT1_2, -mPadding*M_SQRT1_2);
  4796. default: qDebug() << Q_FUNC_INFO << "invalid mode for anchor side: " << mAnchorSide; break;
  4797. }
  4798. break;
  4799. }
  4800. case amSkewedUpright:
  4801. // fall through
  4802. case amSkewedRotated:
  4803. {
  4804. QCPVector2D anchorNormal(tickPos-mAnchorReference);
  4805. if (mAnchorReferenceType == artTangent)
  4806. anchorNormal = anchorNormal.perpendicular();
  4807. anchorNormal.normalize();
  4808. return tickPos+(anchorNormal*mPadding).toPointF();
  4809. }
  4810. default: qDebug() << Q_FUNC_INFO << "invalid mode for anchor mode: " << mAnchorMode; break;
  4811. }
  4812. return tickPos;
  4813. }
  4814. /*! \internal
  4815. This is a \ref placeTickLabel helper function.
  4816. Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a
  4817. y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to
  4818. directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when
  4819. QCP::phCacheLabels plotting hint is not set.
  4820. */
  4821. void QCPLabelPainterPrivate::drawText(QCPPainter *painter, const QPointF &pos, const LabelData &labelData) const
  4822. {
  4823. // backup painter settings that we're about to change:
  4824. QTransform oldTransform = painter->transform();
  4825. QFont oldFont = painter->font();
  4826. QPen oldPen = painter->pen();
  4827. // transform painter to position/rotation:
  4828. painter->translate(pos);
  4829. painter->setTransform(labelData.transform, true);
  4830. // draw text:
  4831. painter->setFont(labelData.baseFont);
  4832. painter->setPen(QPen(labelData.color));
  4833. if (!labelData.expPart.isEmpty()) // use superscripted exponent typesetting
  4834. {
  4835. painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart);
  4836. if (!labelData.suffixPart.isEmpty())
  4837. painter->drawText(labelData.baseBounds.width()+1+labelData.expBounds.width(), 0, 0, 0, Qt::TextDontClip, labelData.suffixPart);
  4838. painter->setFont(labelData.expFont);
  4839. painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart);
  4840. } else
  4841. {
  4842. painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart);
  4843. }
  4844. /* Debug code to draw label bounding boxes, baseline, and capheight
  4845. painter->save();
  4846. painter->setPen(QPen(QColor(0, 0, 0, 150)));
  4847. painter->drawRect(labelData.totalBounds);
  4848. const int baseline = labelData.totalBounds.height()-mLetterDescent;
  4849. painter->setPen(QPen(QColor(255, 0, 0, 150)));
  4850. painter->drawLine(QLineF(0, baseline, labelData.totalBounds.width(), baseline));
  4851. painter->setPen(QPen(QColor(0, 0, 255, 150)));
  4852. painter->drawLine(QLineF(0, baseline-mLetterCapHeight, labelData.totalBounds.width(), baseline-mLetterCapHeight));
  4853. painter->restore();
  4854. */
  4855. // reset painter settings to what it was before:
  4856. painter->setTransform(oldTransform);
  4857. painter->setFont(oldFont);
  4858. painter->setPen(oldPen);
  4859. }
  4860. /*! \internal
  4861. This is a \ref placeTickLabel helper function.
  4862. Transforms the passed \a text and \a font to a tickLabelData structure that can then be further
  4863. processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and
  4864. exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes.
  4865. */
  4866. QCPLabelPainterPrivate::LabelData QCPLabelPainterPrivate::getTickLabelData(const QFont &font, const QColor &color, double rotation, AnchorSide side, const QString &text) const
  4867. {
  4868. LabelData result;
  4869. result.rotation = rotation;
  4870. result.side = side;
  4871. result.color = color;
  4872. // determine whether beautiful decimal powers should be used
  4873. bool useBeautifulPowers = false;
  4874. int ePos = -1; // first index of exponent part, text before that will be basePart, text until eLast will be expPart
  4875. int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart
  4876. if (mSubstituteExponent)
  4877. {
  4878. ePos = text.indexOf(QLatin1Char('e'));
  4879. if (ePos > 0 && text.at(ePos-1).isDigit())
  4880. {
  4881. eLast = ePos;
  4882. while (eLast+1 < text.size() && (text.at(eLast+1) == QLatin1Char('+') || text.at(eLast+1) == QLatin1Char('-') || text.at(eLast+1).isDigit()))
  4883. ++eLast;
  4884. if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as beautifiable power
  4885. useBeautifulPowers = true;
  4886. }
  4887. }
  4888. // calculate text bounding rects and do string preparation for beautiful decimal powers:
  4889. result.baseFont = font;
  4890. if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line
  4891. 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
  4892. QFontMetrics baseFontMetrics(result.baseFont);
  4893. if (useBeautifulPowers)
  4894. {
  4895. // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent:
  4896. result.basePart = text.left(ePos);
  4897. result.suffixPart = text.mid(eLast+1); // also drawn normally but after exponent
  4898. // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base:
  4899. if (mAbbreviateDecimalPowers && result.basePart == QLatin1String("1"))
  4900. result.basePart = QLatin1String("10");
  4901. else
  4902. result.basePart += QString(mMultiplicationSymbol) + QLatin1String("10");
  4903. result.expPart = text.mid(ePos+1, eLast-ePos);
  4904. // clip "+" and leading zeros off expPart:
  4905. while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e'
  4906. result.expPart.remove(1, 1);
  4907. if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+'))
  4908. result.expPart.remove(0, 1);
  4909. // prepare smaller font for exponent:
  4910. result.expFont = font;
  4911. if (result.expFont.pointSize() > 0)
  4912. result.expFont.setPointSize(result.expFont.pointSize()*0.75);
  4913. else
  4914. result.expFont.setPixelSize(result.expFont.pixelSize()*0.75);
  4915. // calculate bounding rects of base part(s), exponent part and total one:
  4916. result.baseBounds = baseFontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart);
  4917. result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart);
  4918. if (!result.suffixPart.isEmpty())
  4919. result.suffixBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.suffixPart);
  4920. 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
  4921. } else // useBeautifulPowers == false
  4922. {
  4923. result.basePart = text;
  4924. result.totalBounds = baseFontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart);
  4925. }
  4926. result.totalBounds.moveTopLeft(QPoint(0, 0));
  4927. applyAnchorTransform(result);
  4928. result.rotatedTotalBounds = result.transform.mapRect(result.totalBounds);
  4929. return result;
  4930. }
  4931. void QCPLabelPainterPrivate::applyAnchorTransform(LabelData &labelData) const
  4932. {
  4933. if (!qFuzzyIsNull(labelData.rotation))
  4934. labelData.transform.rotate(labelData.rotation); // rotates effectively clockwise (due to flipped y axis of painter vs widget coordinate system)
  4935. // from now on we translate in rotated label-local coordinate system.
  4936. // shift origin of coordinate system to appropriate point on label:
  4937. labelData.transform.translate(0, -labelData.totalBounds.height()+mLetterDescent+mLetterCapHeight); // shifts origin to true top of capital (or number) characters
  4938. if (labelData.side == asLeft || labelData.side == asRight) // anchor is centered vertically
  4939. labelData.transform.translate(0, -mLetterCapHeight/2.0);
  4940. else if (labelData.side == asTop || labelData.side == asBottom) // anchor is centered horizontally
  4941. labelData.transform.translate(-labelData.totalBounds.width()/2.0, 0);
  4942. if (labelData.side == asTopRight || labelData.side == asRight || labelData.side == asBottomRight) // anchor is at right
  4943. labelData.transform.translate(-labelData.totalBounds.width(), 0);
  4944. if (labelData.side == asBottomLeft || labelData.side == asBottom || labelData.side == asBottomRight) // anchor is at bottom (no elseif!)
  4945. labelData.transform.translate(0, -mLetterCapHeight);
  4946. }
  4947. /*! \internal
  4948. Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label
  4949. to be drawn, depending on number format etc. Since only the largest tick label is wanted for the
  4950. margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a
  4951. smaller width/height.
  4952. */
  4953. /*
  4954. void QCPLabelPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const
  4955. {
  4956. // note: this function must return the same tick label sizes as the placeTickLabel function.
  4957. QSize finalSize;
  4958. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label
  4959. {
  4960. const CachedLabel *cachedLabel = mLabelCache.object(text);
  4961. finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
  4962. } else // label caching disabled or no label with this text cached:
  4963. {
  4964. // TODO: LabelData labelData = getTickLabelData(font, text);
  4965. // TODO: finalSize = labelData.rotatedTotalBounds.size();
  4966. }
  4967. // expand passed tickLabelsSize if current tick label is larger:
  4968. if (finalSize.width() > tickLabelsSize->width())
  4969. tickLabelsSize->setWidth(finalSize.width());
  4970. if (finalSize.height() > tickLabelsSize->height())
  4971. tickLabelsSize->setHeight(finalSize.height());
  4972. }
  4973. */
  4974. QCPLabelPainterPrivate::CachedLabel *QCPLabelPainterPrivate::createCachedLabel(const LabelData &labelData) const
  4975. {
  4976. CachedLabel *result = new CachedLabel;
  4977. // allocate pixmap with the correct size and pixel ratio:
  4978. if (!qFuzzyCompare(1.0, mParentPlot->bufferDevicePixelRatio()))
  4979. {
  4980. result->pixmap = QPixmap(labelData.rotatedTotalBounds.size()*mParentPlot->bufferDevicePixelRatio());
  4981. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  4982. # ifdef QCP_DEVICEPIXELRATIO_FLOAT
  4983. result->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF());
  4984. # else
  4985. result->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio());
  4986. # endif
  4987. #endif
  4988. } else
  4989. result->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
  4990. result->pixmap.fill(Qt::transparent);
  4991. // draw the label into the pixmap
  4992. // 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.
  4993. // We use rotatedTotalBounds.topLeft() because rotatedTotalBounds is in a coordinate system where the label anchor is at (0, 0)
  4994. result->offset = labelData.rotatedTotalBounds.topLeft();
  4995. QCPPainter cachePainter(&result->pixmap);
  4996. drawText(&cachePainter, -result->offset, labelData);
  4997. return result;
  4998. }
  4999. QByteArray QCPLabelPainterPrivate::cacheKey(const QString &text, const QColor &color, double rotation, AnchorSide side) const
  5000. {
  5001. return text.toUtf8()+
  5002. QByteArray::number(color.red()+256*color.green()+65536*color.blue(), 36)+
  5003. QByteArray::number(color.alpha()+256*int(side), 36)+
  5004. QByteArray::number(int(rotation*100), 36);
  5005. }
  5006. QCPLabelPainterPrivate::AnchorSide QCPLabelPainterPrivate::skewedAnchorSide(const QPointF &tickPos, double sideExpandHorz, double sideExpandVert) const
  5007. {
  5008. QCPVector2D anchorNormal = QCPVector2D(tickPos-mAnchorReference);
  5009. if (mAnchorReferenceType == artTangent)
  5010. anchorNormal = anchorNormal.perpendicular();
  5011. const double radius = anchorNormal.length();
  5012. const double sideHorz = sideExpandHorz*radius;
  5013. const double sideVert = sideExpandVert*radius;
  5014. if (anchorNormal.x() > sideHorz)
  5015. {
  5016. if (anchorNormal.y() > sideVert) return asTopLeft;
  5017. else if (anchorNormal.y() < -sideVert) return asBottomLeft;
  5018. else return asLeft;
  5019. } else if (anchorNormal.x() < -sideHorz)
  5020. {
  5021. if (anchorNormal.y() > sideVert) return asTopRight;
  5022. else if (anchorNormal.y() < -sideVert) return asBottomRight;
  5023. else return asRight;
  5024. } else
  5025. {
  5026. if (anchorNormal.y() > 0) return asTop;
  5027. else return asBottom;
  5028. }
  5029. return asBottom; // should never be reached
  5030. }
  5031. QCPLabelPainterPrivate::AnchorSide QCPLabelPainterPrivate::rotationCorrectedSide(AnchorSide side, double rotation) const
  5032. {
  5033. AnchorSide result = side;
  5034. const bool rotateClockwise = rotation > 0;
  5035. if (!qFuzzyIsNull(rotation))
  5036. {
  5037. if (!qFuzzyCompare(qAbs(rotation), 90)) // avoid graphical collision with anchor tangent (e.g. axis line) when rotating, so change anchor side appropriately:
  5038. {
  5039. if (side == asTop) result = rotateClockwise ? asLeft : asRight;
  5040. else if (side == asBottom) result = rotateClockwise ? asRight : asLeft;
  5041. else if (side == asTopLeft) result = rotateClockwise ? asLeft : asTop;
  5042. else if (side == asTopRight) result = rotateClockwise ? asTop : asRight;
  5043. else if (side == asBottomLeft) result = rotateClockwise ? asBottom : asLeft;
  5044. else if (side == asBottomRight) result = rotateClockwise ? asRight : asBottom;
  5045. } else // for full rotation by +/-90 degrees, other sides are more appropriate for centering on anchor:
  5046. {
  5047. if (side == asLeft) result = rotateClockwise ? asBottom : asTop;
  5048. else if (side == asRight) result = rotateClockwise ? asTop : asBottom;
  5049. else if (side == asTop) result = rotateClockwise ? asLeft : asRight;
  5050. else if (side == asBottom) result = rotateClockwise ? asRight : asLeft;
  5051. else if (side == asTopLeft) result = rotateClockwise ? asBottomLeft : asTopRight;
  5052. else if (side == asTopRight) result = rotateClockwise ? asTopLeft : asBottomRight;
  5053. else if (side == asBottomLeft) result = rotateClockwise ? asBottomRight : asTopLeft;
  5054. else if (side == asBottomRight) result = rotateClockwise ? asTopRight : asBottomLeft;
  5055. }
  5056. }
  5057. return result;
  5058. }
  5059. void QCPLabelPainterPrivate::analyzeFontMetrics()
  5060. {
  5061. const QFontMetrics fm(mFont);
  5062. mLetterCapHeight = fm.tightBoundingRect(QLatin1String("8")).height(); // this method is slow, that's why we query it only upon font change
  5063. mLetterDescent = fm.descent();
  5064. }
  5065. /* end of 'src/axis/labelpainter.cpp' */
  5066. /* including file 'src/axis/axisticker.cpp' */
  5067. /* modified 2022-11-06T12:45:56, size 18693 */
  5068. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5069. //////////////////// QCPAxisTicker
  5070. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5071. /*! \class QCPAxisTicker
  5072. \brief The base class tick generator used by QCPAxis to create tick positions and tick labels
  5073. Each QCPAxis has an internal QCPAxisTicker (or a subclass) in order to generate tick positions
  5074. and tick labels for the current axis range. The ticker of an axis can be set via \ref
  5075. QCPAxis::setTicker. Since that method takes a <tt>QSharedPointer<QCPAxisTicker></tt>, multiple
  5076. axes can share the same ticker instance.
  5077. This base class generates normal tick coordinates and numeric labels for linear axes. It picks a
  5078. reasonable tick step (the separation between ticks) which results in readable tick labels. The
  5079. number of ticks that should be approximately generated can be set via \ref setTickCount.
  5080. Depending on the current tick step strategy (\ref setTickStepStrategy), the algorithm either
  5081. sacrifices readability to better match the specified tick count (\ref
  5082. QCPAxisTicker::tssMeetTickCount) or relaxes the tick count in favor of better tick steps (\ref
  5083. QCPAxisTicker::tssReadability), which is the default.
  5084. The following more specialized axis ticker subclasses are available, see details in the
  5085. respective class documentation:
  5086. <center>
  5087. <table>
  5088. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerFixed</td><td>\image html axisticker-fixed.png</td></tr>
  5089. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerLog</td><td>\image html axisticker-log.png</td></tr>
  5090. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerPi</td><td>\image html axisticker-pi.png</td></tr>
  5091. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerText</td><td>\image html axisticker-text.png</td></tr>
  5092. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerDateTime</td><td>\image html axisticker-datetime.png</td></tr>
  5093. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerTime</td><td>\image html axisticker-time.png
  5094. \image html axisticker-time2.png</td></tr>
  5095. </table>
  5096. </center>
  5097. \section axisticker-subclassing Creating own axis tickers
  5098. Creating own axis tickers can be achieved very easily by sublassing QCPAxisTicker and
  5099. reimplementing some or all of the available virtual methods.
  5100. In the simplest case you might wish to just generate different tick steps than the other tickers,
  5101. so you only reimplement the method \ref getTickStep. If you additionally want control over the
  5102. string that will be shown as tick label, reimplement \ref getTickLabel.
  5103. If you wish to have complete control, you can generate the tick vectors and tick label vectors
  5104. yourself by reimplementing \ref createTickVector and \ref createLabelVector. The default
  5105. implementations use the previously mentioned virtual methods \ref getTickStep and \ref
  5106. getTickLabel, but your reimplementations don't necessarily need to do so. For example in the case
  5107. of unequal tick steps, the method \ref getTickStep loses its usefulness and can be ignored.
  5108. The sub tick count between major ticks can be controlled with \ref getSubTickCount. Full sub tick
  5109. placement control is obtained by reimplementing \ref createSubTickVector.
  5110. See the documentation of all these virtual methods in QCPAxisTicker for detailed information
  5111. about the parameters and expected return values.
  5112. */
  5113. /*!
  5114. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  5115. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  5116. */
  5117. QCPAxisTicker::QCPAxisTicker() :
  5118. mTickStepStrategy(tssReadability),
  5119. mTickCount(5),
  5120. mTickOrigin(0)
  5121. {
  5122. }
  5123. QCPAxisTicker::~QCPAxisTicker()
  5124. {
  5125. }
  5126. /*!
  5127. Sets which strategy the axis ticker follows when choosing the size of the tick step. For the
  5128. available strategies, see \ref TickStepStrategy.
  5129. */
  5130. void QCPAxisTicker::setTickStepStrategy(QCPAxisTicker::TickStepStrategy strategy)
  5131. {
  5132. mTickStepStrategy = strategy;
  5133. }
  5134. /*!
  5135. Sets how many ticks this ticker shall aim to generate across the axis range. Note that \a count
  5136. is not guaranteed to be matched exactly, as generating readable tick intervals may conflict with
  5137. the requested number of ticks.
  5138. Whether the readability has priority over meeting the requested \a count can be specified with
  5139. \ref setTickStepStrategy.
  5140. */
  5141. void QCPAxisTicker::setTickCount(int count)
  5142. {
  5143. if (count > 0)
  5144. mTickCount = count;
  5145. else
  5146. qDebug() << Q_FUNC_INFO << "tick count must be greater than zero:" << count;
  5147. }
  5148. /*!
  5149. Sets the mathematical coordinate (or "offset") of the zeroth tick. This tick coordinate is just a
  5150. concept and doesn't need to be inside the currently visible axis range.
  5151. By default \a origin is zero, which for example yields ticks {-5, 0, 5, 10, 15,...} when the tick
  5152. step is five. If \a origin is now set to 1 instead, the correspondingly generated ticks would be
  5153. {-4, 1, 6, 11, 16,...}.
  5154. */
  5155. void QCPAxisTicker::setTickOrigin(double origin)
  5156. {
  5157. mTickOrigin = origin;
  5158. }
  5159. /*!
  5160. This is the method called by QCPAxis in order to actually generate tick coordinates (\a ticks),
  5161. tick label strings (\a tickLabels) and sub tick coordinates (\a subTicks).
  5162. The ticks are generated for the specified \a range. The generated labels typically follow the
  5163. specified \a locale, \a formatChar and number \a precision, however this might be different (or
  5164. even irrelevant) for certain QCPAxisTicker subclasses.
  5165. The output parameter \a ticks is filled with the generated tick positions in axis coordinates.
  5166. The output parameters \a subTicks and \a tickLabels are optional (set them to \c nullptr if not
  5167. needed) and are respectively filled with sub tick coordinates, and tick label strings belonging
  5168. to \a ticks by index.
  5169. */
  5170. void QCPAxisTicker::generate(const QCPRange &range, const QLocale &locale, QChar formatChar, int precision, QVector<double> &ticks, QVector<double> *subTicks, QVector<QString> *tickLabels)
  5171. {
  5172. // generate (major) ticks:
  5173. double tickStep = getTickStep(range);
  5174. ticks = createTickVector(tickStep, range);
  5175. trimTicks(range, ticks, true); // trim ticks to visible range plus one outer tick on each side (incase a subclass createTickVector creates more)
  5176. // generate sub ticks between major ticks:
  5177. if (subTicks)
  5178. {
  5179. if (!ticks.isEmpty())
  5180. {
  5181. *subTicks = createSubTickVector(getSubTickCount(tickStep), ticks);
  5182. trimTicks(range, *subTicks, false);
  5183. } else
  5184. *subTicks = QVector<double>();
  5185. }
  5186. // finally trim also outliers (no further clipping happens in axis drawing):
  5187. trimTicks(range, ticks, false);
  5188. // generate labels for visible ticks if requested:
  5189. if (tickLabels)
  5190. *tickLabels = createLabelVector(ticks, locale, formatChar, precision);
  5191. }
  5192. /*! \internal
  5193. Takes the entire currently visible axis range and returns a sensible tick step in
  5194. order to provide readable tick labels as well as a reasonable number of tick counts (see \ref
  5195. setTickCount, \ref setTickStepStrategy).
  5196. If a QCPAxisTicker subclass only wants a different tick step behaviour than the default
  5197. implementation, it should reimplement this method. See \ref cleanMantissa for a possible helper
  5198. function.
  5199. */
  5200. double QCPAxisTicker::getTickStep(const QCPRange &range)
  5201. {
  5202. double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  5203. return cleanMantissa(exactStep);
  5204. }
  5205. /*! \internal
  5206. Takes the \a tickStep, i.e. the distance between two consecutive ticks, and returns
  5207. an appropriate number of sub ticks for that specific tick step.
  5208. Note that a returned sub tick count of e.g. 4 will split each tick interval into 5 sections.
  5209. */
  5210. int QCPAxisTicker::getSubTickCount(double tickStep)
  5211. {
  5212. int result = 1; // default to 1, if no proper value can be found
  5213. // separate integer and fractional part of mantissa:
  5214. double epsilon = 0.01;
  5215. double intPartf;
  5216. int intPart;
  5217. double fracPart = modf(getMantissa(tickStep), &intPartf);
  5218. intPart = int(intPartf);
  5219. // handle cases with (almost) integer mantissa:
  5220. if (fracPart < epsilon || 1.0-fracPart < epsilon)
  5221. {
  5222. if (1.0-fracPart < epsilon)
  5223. ++intPart;
  5224. switch (intPart)
  5225. {
  5226. case 1: result = 4; break; // 1.0 -> 0.2 substep
  5227. case 2: result = 3; break; // 2.0 -> 0.5 substep
  5228. case 3: result = 2; break; // 3.0 -> 1.0 substep
  5229. case 4: result = 3; break; // 4.0 -> 1.0 substep
  5230. case 5: result = 4; break; // 5.0 -> 1.0 substep
  5231. case 6: result = 2; break; // 6.0 -> 2.0 substep
  5232. case 7: result = 6; break; // 7.0 -> 1.0 substep
  5233. case 8: result = 3; break; // 8.0 -> 2.0 substep
  5234. case 9: result = 2; break; // 9.0 -> 3.0 substep
  5235. }
  5236. } else
  5237. {
  5238. // handle cases with significantly fractional mantissa:
  5239. if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa
  5240. {
  5241. switch (intPart)
  5242. {
  5243. case 1: result = 2; break; // 1.5 -> 0.5 substep
  5244. case 2: result = 4; break; // 2.5 -> 0.5 substep
  5245. case 3: result = 4; break; // 3.5 -> 0.7 substep
  5246. case 4: result = 2; break; // 4.5 -> 1.5 substep
  5247. case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with default getTickStep from here on)
  5248. case 6: result = 4; break; // 6.5 -> 1.3 substep
  5249. case 7: result = 2; break; // 7.5 -> 2.5 substep
  5250. case 8: result = 4; break; // 8.5 -> 1.7 substep
  5251. case 9: result = 4; break; // 9.5 -> 1.9 substep
  5252. }
  5253. }
  5254. // if mantissa fraction isn't 0.0 or 0.5, don't bother finding good sub tick marks, leave default
  5255. }
  5256. return result;
  5257. }
  5258. /*! \internal
  5259. This method returns the tick label string as it should be printed under the \a tick coordinate.
  5260. If a textual number is returned, it should respect the provided \a locale, \a formatChar and \a
  5261. precision.
  5262. If the returned value contains exponentials of the form "2e5" and beautifully typeset powers is
  5263. enabled in the QCPAxis number format (\ref QCPAxis::setNumberFormat), the exponential part will
  5264. be formatted accordingly using multiplication symbol and superscript during rendering of the
  5265. label automatically.
  5266. */
  5267. QString QCPAxisTicker::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  5268. {
  5269. return locale.toString(tick, formatChar.toLatin1(), precision);
  5270. }
  5271. /*! \internal
  5272. Returns a vector containing all coordinates of sub ticks that should be drawn. It generates \a
  5273. subTickCount sub ticks between each tick pair given in \a ticks.
  5274. If a QCPAxisTicker subclass needs maximal control over the generated sub ticks, it should
  5275. reimplement this method. Depending on the purpose of the subclass it doesn't necessarily need to
  5276. base its result on \a subTickCount or \a ticks.
  5277. */
  5278. QVector<double> QCPAxisTicker::createSubTickVector(int subTickCount, const QVector<double> &ticks)
  5279. {
  5280. QVector<double> result;
  5281. if (subTickCount <= 0 || ticks.size() < 2)
  5282. return result;
  5283. result.reserve((ticks.size()-1)*subTickCount);
  5284. for (int i=1; i<ticks.size(); ++i)
  5285. {
  5286. double subTickStep = (ticks.at(i)-ticks.at(i-1))/double(subTickCount+1);
  5287. for (int k=1; k<=subTickCount; ++k)
  5288. result.append(ticks.at(i-1) + k*subTickStep);
  5289. }
  5290. return result;
  5291. }
  5292. /*! \internal
  5293. Returns a vector containing all coordinates of ticks that should be drawn. The default
  5294. implementation generates ticks with a spacing of \a tickStep (mathematically starting at the tick
  5295. step origin, see \ref setTickOrigin) distributed over the passed \a range.
  5296. In order for the axis ticker to generate proper sub ticks, it is necessary that the first and
  5297. last tick coordinates returned by this method are just below/above the provided \a range.
  5298. Otherwise the outer intervals won't contain any sub ticks.
  5299. If a QCPAxisTicker subclass needs maximal control over the generated ticks, it should reimplement
  5300. this method. Depending on the purpose of the subclass it doesn't necessarily need to base its
  5301. result on \a tickStep, e.g. when the ticks are spaced unequally like in the case of
  5302. QCPAxisTickerLog.
  5303. */
  5304. QVector<double> QCPAxisTicker::createTickVector(double tickStep, const QCPRange &range)
  5305. {
  5306. QVector<double> result;
  5307. // Generate tick positions according to tickStep:
  5308. qint64 firstStep = qint64(floor((range.lower-mTickOrigin)/tickStep)); // do not use qFloor here, or we'll lose 64 bit precision
  5309. qint64 lastStep = qint64(ceil((range.upper-mTickOrigin)/tickStep)); // do not use qCeil here, or we'll lose 64 bit precision
  5310. int tickcount = int(lastStep-firstStep+1);
  5311. if (tickcount < 0) tickcount = 0;
  5312. result.resize(tickcount);
  5313. for (int i=0; i<tickcount; ++i)
  5314. result[i] = mTickOrigin + (firstStep+i)*tickStep;
  5315. return result;
  5316. }
  5317. /*! \internal
  5318. Returns a vector containing all tick label strings corresponding to the tick coordinates provided
  5319. in \a ticks. The default implementation calls \ref getTickLabel to generate the respective
  5320. strings.
  5321. It is possible but uncommon for QCPAxisTicker subclasses to reimplement this method, as
  5322. reimplementing \ref getTickLabel often achieves the intended result easier.
  5323. */
  5324. QVector<QString> QCPAxisTicker::createLabelVector(const QVector<double> &ticks, const QLocale &locale, QChar formatChar, int precision)
  5325. {
  5326. QVector<QString> result;
  5327. result.reserve(ticks.size());
  5328. foreach (double tickCoord, ticks)
  5329. result.append(getTickLabel(tickCoord, locale, formatChar, precision));
  5330. return result;
  5331. }
  5332. /*! \internal
  5333. Removes tick coordinates from \a ticks which lie outside the specified \a range. If \a
  5334. keepOneOutlier is true, it preserves one tick just outside the range on both sides, if present.
  5335. The passed \a ticks must be sorted in ascending order.
  5336. */
  5337. void QCPAxisTicker::trimTicks(const QCPRange &range, QVector<double> &ticks, bool keepOneOutlier) const
  5338. {
  5339. bool lowFound = false;
  5340. bool highFound = false;
  5341. int lowIndex = 0;
  5342. int highIndex = -1;
  5343. for (int i=0; i < ticks.size(); ++i)
  5344. {
  5345. if (ticks.at(i) >= range.lower)
  5346. {
  5347. lowFound = true;
  5348. lowIndex = i;
  5349. break;
  5350. }
  5351. }
  5352. for (int i=ticks.size()-1; i >= 0; --i)
  5353. {
  5354. if (ticks.at(i) <= range.upper)
  5355. {
  5356. highFound = true;
  5357. highIndex = i;
  5358. break;
  5359. }
  5360. }
  5361. if (highFound && lowFound)
  5362. {
  5363. int trimFront = qMax(0, lowIndex-(keepOneOutlier ? 1 : 0));
  5364. int trimBack = qMax(0, ticks.size()-(keepOneOutlier ? 2 : 1)-highIndex);
  5365. if (trimFront > 0 || trimBack > 0)
  5366. ticks = ticks.mid(trimFront, ticks.size()-trimFront-trimBack);
  5367. } else // all ticks are either all below or all above the range
  5368. ticks.clear();
  5369. }
  5370. /*! \internal
  5371. Returns the coordinate contained in \a candidates which is closest to the provided \a target.
  5372. This method assumes \a candidates is not empty and sorted in ascending order.
  5373. */
  5374. double QCPAxisTicker::pickClosest(double target, const QVector<double> &candidates) const
  5375. {
  5376. if (candidates.size() == 1)
  5377. return candidates.first();
  5378. QVector<double>::const_iterator it = std::lower_bound(candidates.constBegin(), candidates.constEnd(), target);
  5379. if (it == candidates.constEnd())
  5380. return *(it-1);
  5381. else if (it == candidates.constBegin())
  5382. return *it;
  5383. else
  5384. return target-*(it-1) < *it-target ? *(it-1) : *it;
  5385. }
  5386. /*! \internal
  5387. Returns the decimal mantissa of \a input. Optionally, if \a magnitude is not set to zero, it also
  5388. returns the magnitude of \a input as a power of 10.
  5389. For example, an input of 142.6 will return a mantissa of 1.426 and a magnitude of 100.
  5390. */
  5391. double QCPAxisTicker::getMantissa(double input, double *magnitude) const
  5392. {
  5393. const double mag = std::pow(10.0, std::floor(std::log10(input)));
  5394. if (magnitude) *magnitude = mag;
  5395. return input/mag;
  5396. }
  5397. /*! \internal
  5398. Returns a number that is close to \a input but has a clean, easier human readable mantissa. How
  5399. strongly the mantissa is altered, and thus how strong the result deviates from the original \a
  5400. input, depends on the current tick step strategy (see \ref setTickStepStrategy).
  5401. */
  5402. double QCPAxisTicker::cleanMantissa(double input) const
  5403. {
  5404. double magnitude;
  5405. const double mantissa = getMantissa(input, &magnitude);
  5406. switch (mTickStepStrategy)
  5407. {
  5408. case tssReadability:
  5409. {
  5410. return pickClosest(mantissa, QVector<double>() << 1.0 << 2.0 << 2.5 << 5.0 << 10.0)*magnitude;
  5411. }
  5412. case tssMeetTickCount:
  5413. {
  5414. // 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
  5415. if (mantissa <= 5.0)
  5416. return int(mantissa*2)/2.0*magnitude; // round digit after decimal point to 0.5
  5417. else
  5418. return int(mantissa/2.0)*2.0*magnitude; // round to first digit in multiples of 2
  5419. }
  5420. }
  5421. return input;
  5422. }
  5423. /* end of 'src/axis/axisticker.cpp' */
  5424. /* including file 'src/axis/axistickerdatetime.cpp' */
  5425. /* modified 2022-11-06T12:45:56, size 18829 */
  5426. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5427. //////////////////// QCPAxisTickerDateTime
  5428. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5429. /*! \class QCPAxisTickerDateTime
  5430. \brief Specialized axis ticker for calendar dates and times as axis ticks
  5431. \image html axisticker-datetime.png
  5432. This QCPAxisTicker subclass generates ticks that correspond to real calendar dates and times. The
  5433. plot axis coordinate is interpreted as Unix Time, so seconds since Epoch (January 1, 1970, 00:00
  5434. UTC). This is also used for example by QDateTime in the <tt>toTime_t()/setTime_t()</tt> methods
  5435. with a precision of one second. Since Qt 4.7, millisecond accuracy can be obtained from QDateTime
  5436. by using <tt>QDateTime::fromMSecsSinceEpoch()/1000.0</tt>. The static methods \ref dateTimeToKey
  5437. and \ref keyToDateTime conveniently perform this conversion achieving a precision of one
  5438. millisecond on all Qt versions.
  5439. The format of the date/time display in the tick labels is controlled with \ref setDateTimeFormat.
  5440. If a different time spec or time zone shall be used for the tick label appearance, see \ref
  5441. setDateTimeSpec or \ref setTimeZone, respectively.
  5442. This ticker produces unequal tick spacing in order to provide intuitive date and time-of-day
  5443. ticks. For example, if the axis range spans a few years such that there is one tick per year,
  5444. ticks will be positioned on 1. January of every year. This is intuitive but, due to leap years,
  5445. will result in slightly unequal tick intervals (visually unnoticeable). The same can be seen in
  5446. the image above: even though the number of days varies month by month, this ticker generates
  5447. ticks on the same day of each month.
  5448. If you would like to change the date/time that is used as a (mathematical) starting date for the
  5449. ticks, use the \ref setTickOrigin(const QDateTime &origin) method overload, which takes a
  5450. QDateTime. If you pass 15. July, 9:45 to this method, the yearly ticks will end up on 15. July at
  5451. 9:45 of every year.
  5452. The ticker can be created and assigned to an axis like this:
  5453. \snippet documentation/doc-image-generator/mainwindow.cpp axistickerdatetime-creation
  5454. \note If you rather wish to display relative times in terms of days, hours, minutes, seconds and
  5455. milliseconds, and are not interested in the intricacies of real calendar dates with months and
  5456. (leap) years, have a look at QCPAxisTickerTime instead.
  5457. */
  5458. /*!
  5459. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  5460. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  5461. */
  5462. QCPAxisTickerDateTime::QCPAxisTickerDateTime() :
  5463. mDateTimeFormat(QLatin1String("hh:mm:ss\ndd.MM.yy")),
  5464. mDateTimeSpec(Qt::LocalTime),
  5465. mDateStrategy(dsNone)
  5466. {
  5467. setTickCount(4);
  5468. }
  5469. /*!
  5470. Sets the format in which dates and times are displayed as tick labels. For details about the \a
  5471. format string, see the documentation of QDateTime::toString().
  5472. Typical expressions are
  5473. <table>
  5474. <tr><td>\c d</td><td>The day as a number without a leading zero (1 to 31)</td></tr>
  5475. <tr><td>\c dd</td><td>The day as a number with a leading zero (01 to 31)</td></tr>
  5476. <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>
  5477. <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>
  5478. <tr><td>\c M</td><td>The month as a number without a leading zero (1 to 12)</td></tr>
  5479. <tr><td>\c MM</td><td>The month as a number with a leading zero (01 to 12)</td></tr>
  5480. <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>
  5481. <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>
  5482. <tr><td>\c yy</td><td>The year as a two digit number (00 to 99)</td></tr>
  5483. <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>
  5484. <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>
  5485. <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>
  5486. <tr><td>\c H</td><td>The hour without a leading zero (0 to 23, even with AM/PM display)</td></tr>
  5487. <tr><td>\c HH</td><td>The hour with a leading zero (00 to 23, even with AM/PM display)</td></tr>
  5488. <tr><td>\c m</td><td>The minute without a leading zero (0 to 59)</td></tr>
  5489. <tr><td>\c mm</td><td>The minute with a leading zero (00 to 59)</td></tr>
  5490. <tr><td>\c s</td><td>The whole second, without any leading zero (0 to 59)</td></tr>
  5491. <tr><td>\c ss</td><td>The whole second, with a leading zero where applicable (00 to 59)</td></tr>
  5492. <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>
  5493. <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>
  5494. <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>
  5495. <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>
  5496. <tr><td>\c t</td><td>The timezone (for example "CEST")</td></tr>
  5497. </table>
  5498. Newlines can be inserted with \c "\n", literal strings (even when containing above expressions)
  5499. by encapsulating them using single-quotes. A literal single quote can be generated by using two
  5500. consecutive single quotes in the format.
  5501. \see setDateTimeSpec, setTimeZone
  5502. */
  5503. void QCPAxisTickerDateTime::setDateTimeFormat(const QString &format)
  5504. {
  5505. mDateTimeFormat = format;
  5506. }
  5507. /*!
  5508. Sets the time spec that is used for creating the tick labels from corresponding dates/times.
  5509. The default value of QDateTime objects (and also QCPAxisTickerDateTime) is
  5510. <tt>Qt::LocalTime</tt>. However, if the displayed tick labels shall be given in UTC, set \a spec
  5511. to <tt>Qt::UTC</tt>.
  5512. Tick labels corresponding to other time zones can be achieved with \ref setTimeZone (which sets
  5513. \a spec to \c Qt::TimeZone internally). Note that if \a spec is afterwards set to not be \c
  5514. Qt::TimeZone again, the \ref setTimeZone setting will be ignored accordingly.
  5515. \see setDateTimeFormat, setTimeZone
  5516. */
  5517. void QCPAxisTickerDateTime::setDateTimeSpec(Qt::TimeSpec spec)
  5518. {
  5519. mDateTimeSpec = spec;
  5520. }
  5521. # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)
  5522. /*!
  5523. Sets the time zone that is used for creating the tick labels from corresponding dates/times. The
  5524. time spec (\ref setDateTimeSpec) is set to \c Qt::TimeZone.
  5525. \see setDateTimeFormat, setTimeZone
  5526. */
  5527. void QCPAxisTickerDateTime::setTimeZone(const QTimeZone &zone)
  5528. {
  5529. mTimeZone = zone;
  5530. mDateTimeSpec = Qt::TimeZone;
  5531. }
  5532. #endif
  5533. /*!
  5534. Sets the tick origin (see \ref QCPAxisTicker::setTickOrigin) in seconds since Epoch (1. Jan 1970,
  5535. 00:00 UTC). For the date time ticker it might be more intuitive to use the overload which
  5536. directly takes a QDateTime, see \ref setTickOrigin(const QDateTime &origin).
  5537. This is useful to define the month/day/time recurring at greater tick interval steps. For
  5538. example, If you pass 15. July, 9:45 to this method and the tick interval happens to be one tick
  5539. per year, the ticks will end up on 15. July at 9:45 of every year.
  5540. */
  5541. void QCPAxisTickerDateTime::setTickOrigin(double origin)
  5542. {
  5543. QCPAxisTicker::setTickOrigin(origin);
  5544. }
  5545. /*!
  5546. Sets the tick origin (see \ref QCPAxisTicker::setTickOrigin) as a QDateTime \a origin.
  5547. This is useful to define the month/day/time recurring at greater tick interval steps. For
  5548. example, If you pass 15. July, 9:45 to this method and the tick interval happens to be one tick
  5549. per year, the ticks will end up on 15. July at 9:45 of every year.
  5550. */
  5551. void QCPAxisTickerDateTime::setTickOrigin(const QDateTime &origin)
  5552. {
  5553. setTickOrigin(dateTimeToKey(origin));
  5554. }
  5555. /*! \internal
  5556. Returns a sensible tick step with intervals appropriate for a date-time-display, such as weekly,
  5557. monthly, bi-monthly, etc.
  5558. Note that this tick step isn't used exactly when generating the tick vector in \ref
  5559. createTickVector, but only as a guiding value requiring some correction for each individual tick
  5560. interval. Otherwise this would lead to unintuitive date displays, e.g. jumping between first day
  5561. in the month to the last day in the previous month from tick to tick, due to the non-uniform
  5562. length of months. The same problem arises with leap years.
  5563. \seebaseclassmethod
  5564. */
  5565. double QCPAxisTickerDateTime::getTickStep(const QCPRange &range)
  5566. {
  5567. double result = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  5568. mDateStrategy = dsNone; // leaving it at dsNone means tick coordinates will not be tuned in any special way in createTickVector
  5569. if (result < 1) // ideal tick step is below 1 second -> use normal clean mantissa algorithm in units of seconds
  5570. {
  5571. result = cleanMantissa(result);
  5572. } else if (result < 86400*30.4375*12) // below a year
  5573. {
  5574. result = pickClosest(result, QVector<double>()
  5575. << 1 << 2.5 << 5 << 10 << 15 << 30 << 60 << 2.5*60 << 5*60 << 10*60 << 15*60 << 30*60 << 60*60 // second, minute, hour range
  5576. << 3600*2 << 3600*3 << 3600*6 << 3600*12 << 3600*24 // hour to day range
  5577. << 86400*2 << 86400*5 << 86400*7 << 86400*14 << 86400*30.4375 << 86400*30.4375*2 << 86400*30.4375*3 << 86400*30.4375*6 << 86400*30.4375*12); // day, week, month range (avg. days per month includes leap years)
  5578. if (result > 86400*30.4375-1) // month tick intervals or larger
  5579. mDateStrategy = dsUniformDayInMonth;
  5580. else if (result > 3600*24-1) // day tick intervals or larger
  5581. mDateStrategy = dsUniformTimeInDay;
  5582. } else // more than a year, go back to normal clean mantissa algorithm but in units of years
  5583. {
  5584. const double secondsPerYear = 86400*30.4375*12; // average including leap years
  5585. result = cleanMantissa(result/secondsPerYear)*secondsPerYear;
  5586. mDateStrategy = dsUniformDayInMonth;
  5587. }
  5588. return result;
  5589. }
  5590. /*! \internal
  5591. Returns a sensible sub tick count with intervals appropriate for a date-time-display, such as weekly,
  5592. monthly, bi-monthly, etc.
  5593. \seebaseclassmethod
  5594. */
  5595. int QCPAxisTickerDateTime::getSubTickCount(double tickStep)
  5596. {
  5597. int result = QCPAxisTicker::getSubTickCount(tickStep);
  5598. switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day/week/month range (as specified in getTickStep)
  5599. {
  5600. case 5*60: result = 4; break;
  5601. case 10*60: result = 1; break;
  5602. case 15*60: result = 2; break;
  5603. case 30*60: result = 1; break;
  5604. case 60*60: result = 3; break;
  5605. case 3600*2: result = 3; break;
  5606. case 3600*3: result = 2; break;
  5607. case 3600*6: result = 1; break;
  5608. case 3600*12: result = 3; break;
  5609. case 3600*24: result = 3; break;
  5610. case 86400*2: result = 1; break;
  5611. case 86400*5: result = 4; break;
  5612. case 86400*7: result = 6; break;
  5613. case 86400*14: result = 1; break;
  5614. case int(86400*30.4375+0.5): result = 3; break;
  5615. case int(86400*30.4375*2+0.5): result = 1; break;
  5616. case int(86400*30.4375*3+0.5): result = 2; break;
  5617. case int(86400*30.4375*6+0.5): result = 5; break;
  5618. case int(86400*30.4375*12+0.5): result = 3; break;
  5619. }
  5620. return result;
  5621. }
  5622. /*! \internal
  5623. Generates a date/time tick label for tick coordinate \a tick, based on the currently set format
  5624. (\ref setDateTimeFormat), time spec (\ref setDateTimeSpec), and possibly time zone (\ref
  5625. setTimeZone).
  5626. \seebaseclassmethod
  5627. */
  5628. QString QCPAxisTickerDateTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  5629. {
  5630. Q_UNUSED(precision)
  5631. Q_UNUSED(formatChar)
  5632. # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)
  5633. if (mDateTimeSpec == Qt::TimeZone)
  5634. return locale.toString(keyToDateTime(tick).toTimeZone(mTimeZone), mDateTimeFormat);
  5635. else
  5636. return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
  5637. # else
  5638. return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
  5639. # endif
  5640. }
  5641. /*! \internal
  5642. Uses the passed \a tickStep as a guiding value and applies corrections in order to obtain
  5643. non-uniform tick intervals but intuitive tick labels, e.g. falling on the same day of each month.
  5644. \seebaseclassmethod
  5645. */
  5646. QVector<double> QCPAxisTickerDateTime::createTickVector(double tickStep, const QCPRange &range)
  5647. {
  5648. QVector<double> result = QCPAxisTicker::createTickVector(tickStep, range);
  5649. if (!result.isEmpty())
  5650. {
  5651. if (mDateStrategy == dsUniformTimeInDay)
  5652. {
  5653. QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // the time of this datetime will be set for all other ticks, if possible
  5654. QDateTime tickDateTime;
  5655. for (int i=0; i<result.size(); ++i)
  5656. {
  5657. tickDateTime = keyToDateTime(result.at(i));
  5658. tickDateTime.setTime(uniformDateTime.time());
  5659. result[i] = dateTimeToKey(tickDateTime);
  5660. }
  5661. } else if (mDateStrategy == dsUniformDayInMonth)
  5662. {
  5663. QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // this day (in month) and time will be set for all other ticks, if possible
  5664. QDateTime tickDateTime;
  5665. for (int i=0; i<result.size(); ++i)
  5666. {
  5667. tickDateTime = keyToDateTime(result.at(i));
  5668. tickDateTime.setTime(uniformDateTime.time());
  5669. 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)
  5670. 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. 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
  5673. tickDateTime = tickDateTime.addMonths(-1);
  5674. tickDateTime.setDate(QDate(tickDateTime.date().year(), tickDateTime.date().month(), thisUniformDay));
  5675. result[i] = dateTimeToKey(tickDateTime);
  5676. }
  5677. }
  5678. }
  5679. return result;
  5680. }
  5681. /*!
  5682. A convenience method which turns \a key (in seconds since Epoch 1. Jan 1970, 00:00 UTC) into a
  5683. QDateTime object. This can be used to turn axis coordinates to actual QDateTimes.
  5684. The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it
  5685. works around the lack of a QDateTime::fromMSecsSinceEpoch in Qt 4.6)
  5686. \see dateTimeToKey
  5687. */
  5688. QDateTime QCPAxisTickerDateTime::keyToDateTime(double key)
  5689. {
  5690. # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
  5691. return QDateTime::fromTime_t(key).addMSecs((key-(qint64)key)*1000);
  5692. # else
  5693. return QDateTime::fromMSecsSinceEpoch(qint64(key*1000.0));
  5694. # endif
  5695. }
  5696. /*! \overload
  5697. A convenience method which turns a QDateTime object into a double value that corresponds to
  5698. seconds since Epoch (1. Jan 1970, 00:00 UTC). This is the format used as axis coordinates by
  5699. QCPAxisTickerDateTime.
  5700. The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it
  5701. works around the lack of a QDateTime::toMSecsSinceEpoch in Qt 4.6)
  5702. \see keyToDateTime
  5703. */
  5704. double QCPAxisTickerDateTime::dateTimeToKey(const QDateTime &dateTime)
  5705. {
  5706. # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
  5707. return dateTime.toTime_t()+dateTime.time().msec()/1000.0;
  5708. # else
  5709. return dateTime.toMSecsSinceEpoch()/1000.0;
  5710. # endif
  5711. }
  5712. /*! \overload
  5713. A convenience method which turns a QDate object into a double value that corresponds to seconds
  5714. since Epoch (1. Jan 1970, 00:00 UTC). This is the format used
  5715. as axis coordinates by QCPAxisTickerDateTime.
  5716. The returned value will be the start of the passed day of \a date, interpreted in the given \a
  5717. timeSpec.
  5718. \see keyToDateTime
  5719. */
  5720. double QCPAxisTickerDateTime::dateTimeToKey(const QDate &date, Qt::TimeSpec timeSpec)
  5721. {
  5722. # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
  5723. return QDateTime(date, QTime(0, 0), timeSpec).toTime_t();
  5724. # elif QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  5725. return QDateTime(date, QTime(0, 0), timeSpec).toMSecsSinceEpoch()/1000.0;
  5726. # else
  5727. return date.startOfDay(timeSpec).toMSecsSinceEpoch()/1000.0;
  5728. # endif
  5729. }
  5730. /* end of 'src/axis/axistickerdatetime.cpp' */
  5731. /* including file 'src/axis/axistickertime.cpp' */
  5732. /* modified 2022-11-06T12:45:56, size 11745 */
  5733. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5734. //////////////////// QCPAxisTickerTime
  5735. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5736. /*! \class QCPAxisTickerTime
  5737. \brief Specialized axis ticker for time spans in units of milliseconds to days
  5738. \image html axisticker-time.png
  5739. This QCPAxisTicker subclass generates ticks that corresponds to time intervals.
  5740. The format of the time display in the tick labels is controlled with \ref setTimeFormat and \ref
  5741. setFieldWidth. The time coordinate is in the unit of seconds with respect to the time coordinate
  5742. zero. Unlike with QCPAxisTickerDateTime, the ticks don't correspond to a specific calendar date
  5743. and time.
  5744. The time can be displayed in milliseconds, seconds, minutes, hours and days. Depending on the
  5745. largest available unit in the format specified with \ref setTimeFormat, any time spans above will
  5746. be carried in that largest unit. So for example if the format string is "%m:%s" and a tick at
  5747. coordinate value 7815 (being 2 hours, 10 minutes and 15 seconds) is created, the resulting tick
  5748. label will show "130:15" (130 minutes, 15 seconds). If the format string is "%h:%m:%s", the hour
  5749. unit will be used and the label will thus be "02:10:15". Negative times with respect to the axis
  5750. zero will carry a leading minus sign.
  5751. The ticker can be created and assigned to an axis like this:
  5752. \snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation
  5753. Here is an example of a time axis providing time information in days, hours and minutes. Due to
  5754. the axis range spanning a few days and the wanted tick count (\ref setTickCount), the ticker
  5755. decided to use tick steps of 12 hours:
  5756. \image html axisticker-time2.png
  5757. The format string for this example is
  5758. \snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation-2
  5759. \note If you rather wish to display calendar dates and times, have a look at QCPAxisTickerDateTime
  5760. instead.
  5761. */
  5762. /*!
  5763. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  5764. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  5765. */
  5766. QCPAxisTickerTime::QCPAxisTickerTime() :
  5767. mTimeFormat(QLatin1String("%h:%m:%s")),
  5768. mSmallestUnit(tuSeconds),
  5769. mBiggestUnit(tuHours)
  5770. {
  5771. setTickCount(4);
  5772. mFieldWidth[tuMilliseconds] = 3;
  5773. mFieldWidth[tuSeconds] = 2;
  5774. mFieldWidth[tuMinutes] = 2;
  5775. mFieldWidth[tuHours] = 2;
  5776. mFieldWidth[tuDays] = 1;
  5777. mFormatPattern[tuMilliseconds] = QLatin1String("%z");
  5778. mFormatPattern[tuSeconds] = QLatin1String("%s");
  5779. mFormatPattern[tuMinutes] = QLatin1String("%m");
  5780. mFormatPattern[tuHours] = QLatin1String("%h");
  5781. mFormatPattern[tuDays] = QLatin1String("%d");
  5782. }
  5783. /*!
  5784. Sets the format that will be used to display time in the tick labels.
  5785. The available patterns are:
  5786. - %%z for milliseconds
  5787. - %%s for seconds
  5788. - %%m for minutes
  5789. - %%h for hours
  5790. - %%d for days
  5791. The field width (zero padding) can be controlled for each unit with \ref setFieldWidth.
  5792. The largest unit that appears in \a format will carry all the remaining time of a certain tick
  5793. coordinate, even if it overflows the natural limit of the unit. For example, if %%m is the
  5794. largest unit it might become larger than 59 in order to consume larger time values. If on the
  5795. other hand %%h is available, the minutes will wrap around to zero after 59 and the time will
  5796. carry to the hour digit.
  5797. */
  5798. void QCPAxisTickerTime::setTimeFormat(const QString &format)
  5799. {
  5800. mTimeFormat = format;
  5801. // determine smallest and biggest unit in format, to optimize unit replacement and allow biggest
  5802. // unit to consume remaining time of a tick value and grow beyond its modulo (e.g. min > 59)
  5803. mSmallestUnit = tuMilliseconds;
  5804. mBiggestUnit = tuMilliseconds;
  5805. bool hasSmallest = false;
  5806. for (int i = tuMilliseconds; i <= tuDays; ++i)
  5807. {
  5808. TimeUnit unit = static_cast<TimeUnit>(i);
  5809. if (mTimeFormat.contains(mFormatPattern.value(unit)))
  5810. {
  5811. if (!hasSmallest)
  5812. {
  5813. mSmallestUnit = unit;
  5814. hasSmallest = true;
  5815. }
  5816. mBiggestUnit = unit;
  5817. }
  5818. }
  5819. }
  5820. /*!
  5821. Sets the field widh of the specified \a unit to be \a width digits, when displayed in the tick
  5822. label. If the number for the specific unit is shorter than \a width, it will be padded with an
  5823. according number of zeros to the left in order to reach the field width.
  5824. \see setTimeFormat
  5825. */
  5826. void QCPAxisTickerTime::setFieldWidth(QCPAxisTickerTime::TimeUnit unit, int width)
  5827. {
  5828. mFieldWidth[unit] = qMax(width, 1);
  5829. }
  5830. /*! \internal
  5831. Returns the tick step appropriate for time displays, depending on the provided \a range and the
  5832. smallest available time unit in the current format (\ref setTimeFormat). For example if the unit
  5833. of seconds isn't available in the format, this method will not generate steps (like 2.5 minutes)
  5834. that require sub-minute precision to be displayed correctly.
  5835. \seebaseclassmethod
  5836. */
  5837. double QCPAxisTickerTime::getTickStep(const QCPRange &range)
  5838. {
  5839. double result = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  5840. if (result < 1) // ideal tick step is below 1 second -> use normal clean mantissa algorithm in units of seconds
  5841. {
  5842. if (mSmallestUnit == tuMilliseconds)
  5843. result = qMax(cleanMantissa(result), 0.001); // smallest tick step is 1 millisecond
  5844. else // have no milliseconds available in format, so stick with 1 second tickstep
  5845. result = 1.0;
  5846. } else if (result < 3600*24) // below a day
  5847. {
  5848. // the filling of availableSteps seems a bit contorted but it fills in a sorted fashion and thus saves a post-fill sorting run
  5849. QVector<double> availableSteps;
  5850. // seconds range:
  5851. if (mSmallestUnit <= tuSeconds)
  5852. availableSteps << 1;
  5853. if (mSmallestUnit == tuMilliseconds)
  5854. availableSteps << 2.5; // only allow half second steps if milliseconds are there to display it
  5855. else if (mSmallestUnit == tuSeconds)
  5856. availableSteps << 2;
  5857. if (mSmallestUnit <= tuSeconds)
  5858. availableSteps << 5 << 10 << 15 << 30;
  5859. // minutes range:
  5860. if (mSmallestUnit <= tuMinutes)
  5861. availableSteps << 1*60;
  5862. if (mSmallestUnit <= tuSeconds)
  5863. availableSteps << 2.5*60; // only allow half minute steps if seconds are there to display it
  5864. else if (mSmallestUnit == tuMinutes)
  5865. availableSteps << 2*60;
  5866. if (mSmallestUnit <= tuMinutes)
  5867. availableSteps << 5*60 << 10*60 << 15*60 << 30*60;
  5868. // hours range:
  5869. if (mSmallestUnit <= tuHours)
  5870. availableSteps << 1*3600 << 2*3600 << 3*3600 << 6*3600 << 12*3600 << 24*3600;
  5871. // pick available step that is most appropriate to approximate ideal step:
  5872. result = pickClosest(result, availableSteps);
  5873. } else // more than a day, go back to normal clean mantissa algorithm but in units of days
  5874. {
  5875. const double secondsPerDay = 3600*24;
  5876. result = cleanMantissa(result/secondsPerDay)*secondsPerDay;
  5877. }
  5878. return result;
  5879. }
  5880. /*! \internal
  5881. Returns the sub tick count appropriate for the provided \a tickStep and time displays.
  5882. \seebaseclassmethod
  5883. */
  5884. int QCPAxisTickerTime::getSubTickCount(double tickStep)
  5885. {
  5886. int result = QCPAxisTicker::getSubTickCount(tickStep);
  5887. switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day range (as specified in getTickStep)
  5888. {
  5889. case 5*60: result = 4; break;
  5890. case 10*60: result = 1; break;
  5891. case 15*60: result = 2; break;
  5892. case 30*60: result = 1; break;
  5893. case 60*60: result = 3; break;
  5894. case 3600*2: result = 3; break;
  5895. case 3600*3: result = 2; break;
  5896. case 3600*6: result = 1; break;
  5897. case 3600*12: result = 3; break;
  5898. case 3600*24: result = 3; break;
  5899. }
  5900. return result;
  5901. }
  5902. /*! \internal
  5903. Returns the tick label corresponding to the provided \a tick and the configured format and field
  5904. widths (\ref setTimeFormat, \ref setFieldWidth).
  5905. \seebaseclassmethod
  5906. */
  5907. QString QCPAxisTickerTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  5908. {
  5909. Q_UNUSED(precision)
  5910. Q_UNUSED(formatChar)
  5911. Q_UNUSED(locale)
  5912. bool negative = tick < 0;
  5913. if (negative) tick *= -1;
  5914. double values[tuDays+1]; // contains the msec/sec/min/... value with its respective modulo (e.g. minute 0..59)
  5915. double restValues[tuDays+1]; // contains the msec/sec/min/... value as if it's the largest available unit and thus consumes the remaining time
  5916. restValues[tuMilliseconds] = tick*1000;
  5917. values[tuMilliseconds] = modf(restValues[tuMilliseconds]/1000, &restValues[tuSeconds])*1000;
  5918. values[tuSeconds] = modf(restValues[tuSeconds]/60, &restValues[tuMinutes])*60;
  5919. values[tuMinutes] = modf(restValues[tuMinutes]/60, &restValues[tuHours])*60;
  5920. values[tuHours] = modf(restValues[tuHours]/24, &restValues[tuDays])*24;
  5921. // no need to set values[tuDays] because days are always a rest value (there is no higher unit so it consumes all remaining time)
  5922. QString result = mTimeFormat;
  5923. for (int i = mSmallestUnit; i <= mBiggestUnit; ++i)
  5924. {
  5925. TimeUnit iUnit = static_cast<TimeUnit>(i);
  5926. replaceUnit(result, iUnit, qRound(iUnit == mBiggestUnit ? restValues[iUnit] : values[iUnit]));
  5927. }
  5928. if (negative)
  5929. result.prepend(QLatin1Char('-'));
  5930. return result;
  5931. }
  5932. /*! \internal
  5933. Replaces all occurrences of the format pattern belonging to \a unit in \a text with the specified
  5934. \a value, using the field width as specified with \ref setFieldWidth for the \a unit.
  5935. */
  5936. void QCPAxisTickerTime::replaceUnit(QString &text, QCPAxisTickerTime::TimeUnit unit, int value) const
  5937. {
  5938. QString valueStr = QString::number(value);
  5939. while (valueStr.size() < mFieldWidth.value(unit))
  5940. valueStr.prepend(QLatin1Char('0'));
  5941. text.replace(mFormatPattern.value(unit), valueStr);
  5942. }
  5943. /* end of 'src/axis/axistickertime.cpp' */
  5944. /* including file 'src/axis/axistickerfixed.cpp' */
  5945. /* modified 2022-11-06T12:45:56, size 5575 */
  5946. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5947. //////////////////// QCPAxisTickerFixed
  5948. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5949. /*! \class QCPAxisTickerFixed
  5950. \brief Specialized axis ticker with a fixed tick step
  5951. \image html axisticker-fixed.png
  5952. This QCPAxisTicker subclass generates ticks with a fixed tick step set with \ref setTickStep. It
  5953. is also possible to allow integer multiples and integer powers of the specified tick step with
  5954. \ref setScaleStrategy.
  5955. A typical application of this ticker is to make an axis only display integers, by setting the
  5956. tick step of the ticker to 1.0 and the scale strategy to \ref ssMultiples.
  5957. Another case is when a certain number has a special meaning and axis ticks should only appear at
  5958. multiples of that value. In this case you might also want to consider \ref QCPAxisTickerPi
  5959. because despite the name it is not limited to only pi symbols/values.
  5960. The ticker can be created and assigned to an axis like this:
  5961. \snippet documentation/doc-image-generator/mainwindow.cpp axistickerfixed-creation
  5962. */
  5963. /*!
  5964. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  5965. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  5966. */
  5967. QCPAxisTickerFixed::QCPAxisTickerFixed() :
  5968. mTickStep(1.0),
  5969. mScaleStrategy(ssNone)
  5970. {
  5971. }
  5972. /*!
  5973. Sets the fixed tick interval to \a step.
  5974. The axis ticker will only use this tick step when generating axis ticks. This might cause a very
  5975. high tick density and overlapping labels if the axis range is zoomed out. Using \ref
  5976. setScaleStrategy it is possible to relax the fixed step and also allow multiples or powers of \a
  5977. step. This will enable the ticker to reduce the number of ticks to a reasonable amount (see \ref
  5978. setTickCount).
  5979. */
  5980. void QCPAxisTickerFixed::setTickStep(double step)
  5981. {
  5982. if (step > 0)
  5983. mTickStep = step;
  5984. else
  5985. qDebug() << Q_FUNC_INFO << "tick step must be greater than zero:" << step;
  5986. }
  5987. /*!
  5988. Sets whether the specified tick step (\ref setTickStep) is absolutely fixed or whether
  5989. modifications may be applied to it before calculating the finally used tick step, such as
  5990. permitting multiples or powers. See \ref ScaleStrategy for details.
  5991. The default strategy is \ref ssNone, which means the tick step is absolutely fixed.
  5992. */
  5993. void QCPAxisTickerFixed::setScaleStrategy(QCPAxisTickerFixed::ScaleStrategy strategy)
  5994. {
  5995. mScaleStrategy = strategy;
  5996. }
  5997. /*! \internal
  5998. Determines the actually used tick step from the specified tick step and scale strategy (\ref
  5999. setTickStep, \ref setScaleStrategy).
  6000. This method either returns the specified tick step exactly, or, if the scale strategy is not \ref
  6001. ssNone, a modification of it to allow varying the number of ticks in the current axis range.
  6002. \seebaseclassmethod
  6003. */
  6004. double QCPAxisTickerFixed::getTickStep(const QCPRange &range)
  6005. {
  6006. switch (mScaleStrategy)
  6007. {
  6008. case ssNone:
  6009. {
  6010. return mTickStep;
  6011. }
  6012. case ssMultiples:
  6013. {
  6014. double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  6015. if (exactStep < mTickStep)
  6016. return mTickStep;
  6017. else
  6018. return qint64(cleanMantissa(exactStep/mTickStep)+0.5)*mTickStep;
  6019. }
  6020. case ssPowers:
  6021. {
  6022. double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  6023. return qPow(mTickStep, int(qLn(exactStep)/qLn(mTickStep)+0.5));
  6024. }
  6025. }
  6026. return mTickStep;
  6027. }
  6028. /* end of 'src/axis/axistickerfixed.cpp' */
  6029. /* including file 'src/axis/axistickertext.cpp' */
  6030. /* modified 2022-11-06T12:45:56, size 8742 */
  6031. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6032. //////////////////// QCPAxisTickerText
  6033. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6034. /*! \class QCPAxisTickerText
  6035. \brief Specialized axis ticker which allows arbitrary labels at specified coordinates
  6036. \image html axisticker-text.png
  6037. This QCPAxisTicker subclass generates ticks which can be directly specified by the user as
  6038. coordinates and associated strings. They can be passed as a whole with \ref setTicks or one at a
  6039. time with \ref addTick. Alternatively you can directly access the internal storage via \ref ticks
  6040. and modify the tick/label data there.
  6041. This is useful for cases where the axis represents categories rather than numerical values.
  6042. If you are updating the ticks of this ticker regularly and in a dynamic fasion (e.g. dependent on
  6043. the axis range), it is a sign that you should probably create an own ticker by subclassing
  6044. QCPAxisTicker, instead of using this one.
  6045. The ticker can be created and assigned to an axis like this:
  6046. \snippet documentation/doc-image-generator/mainwindow.cpp axistickertext-creation
  6047. */
  6048. /* start of documentation of inline functions */
  6049. /*! \fn QMap<double, QString> &QCPAxisTickerText::ticks()
  6050. Returns a non-const reference to the internal map which stores the tick coordinates and their
  6051. labels.
  6052. You can access the map directly in order to add, remove or manipulate ticks, as an alternative to
  6053. using the methods provided by QCPAxisTickerText, such as \ref setTicks and \ref addTick.
  6054. */
  6055. /* end of documentation of inline functions */
  6056. /*!
  6057. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  6058. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  6059. */
  6060. QCPAxisTickerText::QCPAxisTickerText() :
  6061. mSubTickCount(0)
  6062. {
  6063. }
  6064. /*! \overload
  6065. Sets the ticks that shall appear on the axis. The map key of \a ticks corresponds to the axis
  6066. coordinate, and the map value is the string that will appear as tick label.
  6067. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  6068. getter.
  6069. \see addTicks, addTick, clear
  6070. */
  6071. void QCPAxisTickerText::setTicks(const QMap<double, QString> &ticks)
  6072. {
  6073. mTicks = ticks;
  6074. }
  6075. /*! \overload
  6076. Sets the ticks that shall appear on the axis. The entries of \a positions correspond to the axis
  6077. coordinates, and the entries of \a labels are the respective strings that will appear as tick
  6078. labels.
  6079. \see addTicks, addTick, clear
  6080. */
  6081. void QCPAxisTickerText::setTicks(const QVector<double> &positions, const QVector<QString> &labels)
  6082. {
  6083. clear();
  6084. addTicks(positions, labels);
  6085. }
  6086. /*!
  6087. Sets the number of sub ticks that shall appear between ticks. For QCPAxisTickerText, there is no
  6088. automatic sub tick count calculation. So if sub ticks are needed, they must be configured with this
  6089. method.
  6090. */
  6091. void QCPAxisTickerText::setSubTickCount(int subTicks)
  6092. {
  6093. if (subTicks >= 0)
  6094. mSubTickCount = subTicks;
  6095. else
  6096. qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks;
  6097. }
  6098. /*!
  6099. Clears all ticks.
  6100. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  6101. getter.
  6102. \see setTicks, addTicks, addTick
  6103. */
  6104. void QCPAxisTickerText::clear()
  6105. {
  6106. mTicks.clear();
  6107. }
  6108. /*!
  6109. Adds a single tick to the axis at the given axis coordinate \a position, with the provided tick \a
  6110. label.
  6111. \see addTicks, setTicks, clear
  6112. */
  6113. void QCPAxisTickerText::addTick(double position, const QString &label)
  6114. {
  6115. mTicks.insert(position, label);
  6116. }
  6117. /*! \overload
  6118. Adds the provided \a ticks to the ones already existing. The map key of \a ticks corresponds to
  6119. the axis coordinate, and the map value is the string that will appear as tick label.
  6120. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  6121. getter.
  6122. \see addTick, setTicks, clear
  6123. */
  6124. void QCPAxisTickerText::addTicks(const QMap<double, QString> &ticks)
  6125. {
  6126. #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
  6127. mTicks.unite(ticks);
  6128. #else
  6129. mTicks.insert(ticks);
  6130. #endif
  6131. }
  6132. /*! \overload
  6133. Adds the provided ticks to the ones already existing. The entries of \a positions correspond to
  6134. the axis coordinates, and the entries of \a labels are the respective strings that will appear as
  6135. tick labels.
  6136. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  6137. getter.
  6138. \see addTick, setTicks, clear
  6139. */
  6140. void QCPAxisTickerText::addTicks(const QVector<double> &positions, const QVector<QString> &labels)
  6141. {
  6142. if (positions.size() != labels.size())
  6143. qDebug() << Q_FUNC_INFO << "passed unequal length vectors for positions and labels:" << positions.size() << labels.size();
  6144. int n = qMin(positions.size(), labels.size());
  6145. for (int i=0; i<n; ++i)
  6146. mTicks.insert(positions.at(i), labels.at(i));
  6147. }
  6148. /*!
  6149. Since the tick coordinates are provided externally, this method implementation does nothing.
  6150. \seebaseclassmethod
  6151. */
  6152. double QCPAxisTickerText::getTickStep(const QCPRange &range)
  6153. {
  6154. // text axis ticker has manual tick positions, so doesn't need this method
  6155. Q_UNUSED(range)
  6156. return 1.0;
  6157. }
  6158. /*!
  6159. Returns the sub tick count that was configured with \ref setSubTickCount.
  6160. \seebaseclassmethod
  6161. */
  6162. int QCPAxisTickerText::getSubTickCount(double tickStep)
  6163. {
  6164. Q_UNUSED(tickStep)
  6165. return mSubTickCount;
  6166. }
  6167. /*!
  6168. Returns the tick label which corresponds to the key \a tick in the internal tick storage. Since
  6169. the labels are provided externally, \a locale, \a formatChar, and \a precision are ignored.
  6170. \seebaseclassmethod
  6171. */
  6172. QString QCPAxisTickerText::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  6173. {
  6174. Q_UNUSED(locale)
  6175. Q_UNUSED(formatChar)
  6176. Q_UNUSED(precision)
  6177. return mTicks.value(tick);
  6178. }
  6179. /*!
  6180. Returns the externally provided tick coordinates which are in the specified \a range. If
  6181. available, one tick above and below the range is provided in addition, to allow possible sub tick
  6182. calculation. The parameter \a tickStep is ignored.
  6183. \seebaseclassmethod
  6184. */
  6185. QVector<double> QCPAxisTickerText::createTickVector(double tickStep, const QCPRange &range)
  6186. {
  6187. Q_UNUSED(tickStep)
  6188. QVector<double> result;
  6189. if (mTicks.isEmpty())
  6190. return result;
  6191. QMap<double, QString>::const_iterator start = mTicks.lowerBound(range.lower);
  6192. QMap<double, QString>::const_iterator end = mTicks.upperBound(range.upper);
  6193. // this method should try to give one tick outside of range so proper subticks can be generated:
  6194. if (start != mTicks.constBegin()) --start;
  6195. if (end != mTicks.constEnd()) ++end;
  6196. for (QMap<double, QString>::const_iterator it = start; it != end; ++it)
  6197. result.append(it.key());
  6198. return result;
  6199. }
  6200. /* end of 'src/axis/axistickertext.cpp' */
  6201. /* including file 'src/axis/axistickerpi.cpp' */
  6202. /* modified 2022-11-06T12:45:56, size 11177 */
  6203. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6204. //////////////////// QCPAxisTickerPi
  6205. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6206. /*! \class QCPAxisTickerPi
  6207. \brief Specialized axis ticker to display ticks in units of an arbitrary constant, for example pi
  6208. \image html axisticker-pi.png
  6209. This QCPAxisTicker subclass generates ticks that are expressed with respect to a given symbolic
  6210. constant with a numerical value specified with \ref setPiValue and an appearance in the tick
  6211. labels specified with \ref setPiSymbol.
  6212. Ticks may be generated at fractions of the symbolic constant. How these fractions appear in the
  6213. tick label can be configured with \ref setFractionStyle.
  6214. The ticker can be created and assigned to an axis like this:
  6215. \snippet documentation/doc-image-generator/mainwindow.cpp axistickerpi-creation
  6216. */
  6217. /*!
  6218. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  6219. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  6220. */
  6221. QCPAxisTickerPi::QCPAxisTickerPi() :
  6222. mPiSymbol(QLatin1String(" ")+QChar(0x03C0)),
  6223. mPiValue(M_PI),
  6224. mPeriodicity(0),
  6225. mFractionStyle(fsUnicodeFractions),
  6226. mPiTickStep(0)
  6227. {
  6228. setTickCount(4);
  6229. }
  6230. /*!
  6231. Sets how the symbol part (which is always a suffix to the number) shall appear in the axis tick
  6232. label.
  6233. If a space shall appear between the number and the symbol, make sure the space is contained in \a
  6234. symbol.
  6235. */
  6236. void QCPAxisTickerPi::setPiSymbol(QString symbol)
  6237. {
  6238. mPiSymbol = symbol;
  6239. }
  6240. /*!
  6241. Sets the numerical value that the symbolic constant has.
  6242. This will be used to place the appropriate fractions of the symbol at the respective axis
  6243. coordinates.
  6244. */
  6245. void QCPAxisTickerPi::setPiValue(double pi)
  6246. {
  6247. mPiValue = pi;
  6248. }
  6249. /*!
  6250. Sets whether the axis labels shall appear periodicly and if so, at which multiplicity of the
  6251. symbolic constant.
  6252. To disable periodicity, set \a multiplesOfPi to zero.
  6253. For example, an axis that identifies 0 with 2pi would set \a multiplesOfPi to two.
  6254. */
  6255. void QCPAxisTickerPi::setPeriodicity(int multiplesOfPi)
  6256. {
  6257. mPeriodicity = qAbs(multiplesOfPi);
  6258. }
  6259. /*!
  6260. Sets how the numerical/fractional part preceding the symbolic constant is displayed in tick
  6261. labels. See \ref FractionStyle for the various options.
  6262. */
  6263. void QCPAxisTickerPi::setFractionStyle(QCPAxisTickerPi::FractionStyle style)
  6264. {
  6265. mFractionStyle = style;
  6266. }
  6267. /*! \internal
  6268. Returns the tick step, using the constant's value (\ref setPiValue) as base unit. In consequence
  6269. the numerical/fractional part preceding the symbolic constant is made to have a readable
  6270. mantissa.
  6271. \seebaseclassmethod
  6272. */
  6273. double QCPAxisTickerPi::getTickStep(const QCPRange &range)
  6274. {
  6275. mPiTickStep = range.size()/mPiValue/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  6276. mPiTickStep = cleanMantissa(mPiTickStep);
  6277. return mPiTickStep*mPiValue;
  6278. }
  6279. /*! \internal
  6280. Returns the sub tick count, using the constant's value (\ref setPiValue) as base unit. In
  6281. consequence the sub ticks divide the numerical/fractional part preceding the symbolic constant
  6282. reasonably, and not the total tick coordinate.
  6283. \seebaseclassmethod
  6284. */
  6285. int QCPAxisTickerPi::getSubTickCount(double tickStep)
  6286. {
  6287. return QCPAxisTicker::getSubTickCount(tickStep/mPiValue);
  6288. }
  6289. /*! \internal
  6290. Returns the tick label as a fractional/numerical part and a symbolic string as suffix. The
  6291. formatting of the fraction is done according to the specified \ref setFractionStyle. The appended
  6292. symbol is specified with \ref setPiSymbol.
  6293. \seebaseclassmethod
  6294. */
  6295. QString QCPAxisTickerPi::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  6296. {
  6297. double tickInPis = tick/mPiValue;
  6298. if (mPeriodicity > 0)
  6299. tickInPis = fmod(tickInPis, mPeriodicity);
  6300. if (mFractionStyle != fsFloatingPoint && mPiTickStep > 0.09 && mPiTickStep < 50)
  6301. {
  6302. // simply construct fraction from decimal like 1.234 -> 1234/1000 and then simplify fraction, smaller digits are irrelevant due to mPiTickStep conditional above
  6303. int denominator = 1000;
  6304. int numerator = qRound(tickInPis*denominator);
  6305. simplifyFraction(numerator, denominator);
  6306. if (qAbs(numerator) == 1 && denominator == 1)
  6307. return (numerator < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed();
  6308. else if (numerator == 0)
  6309. return QLatin1String("0");
  6310. else
  6311. return fractionToString(numerator, denominator) + mPiSymbol;
  6312. } else
  6313. {
  6314. if (qFuzzyIsNull(tickInPis))
  6315. return QLatin1String("0");
  6316. else if (qFuzzyCompare(qAbs(tickInPis), 1.0))
  6317. return (tickInPis < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed();
  6318. else
  6319. return QCPAxisTicker::getTickLabel(tickInPis, locale, formatChar, precision) + mPiSymbol;
  6320. }
  6321. }
  6322. /*! \internal
  6323. Takes the fraction given by \a numerator and \a denominator and modifies the values to make sure
  6324. the fraction is in irreducible form, i.e. numerator and denominator don't share any common
  6325. factors which could be cancelled.
  6326. */
  6327. void QCPAxisTickerPi::simplifyFraction(int &numerator, int &denominator) const
  6328. {
  6329. if (numerator == 0 || denominator == 0)
  6330. return;
  6331. int num = numerator;
  6332. int denom = denominator;
  6333. while (denom != 0) // euclidean gcd algorithm
  6334. {
  6335. int oldDenom = denom;
  6336. denom = num % denom;
  6337. num = oldDenom;
  6338. }
  6339. // num is now gcd of numerator and denominator
  6340. numerator /= num;
  6341. denominator /= num;
  6342. }
  6343. /*! \internal
  6344. Takes the fraction given by \a numerator and \a denominator and returns a string representation.
  6345. The result depends on the configured fraction style (\ref setFractionStyle).
  6346. This method is used to format the numerical/fractional part when generating tick labels. It
  6347. simplifies the passed fraction to an irreducible form using \ref simplifyFraction and factors out
  6348. any integer parts of the fraction (e.g. "10/4" becomes "2 1/2").
  6349. */
  6350. QString QCPAxisTickerPi::fractionToString(int numerator, int denominator) const
  6351. {
  6352. if (denominator == 0)
  6353. {
  6354. qDebug() << Q_FUNC_INFO << "called with zero denominator";
  6355. return QString();
  6356. }
  6357. if (mFractionStyle == fsFloatingPoint) // should never be the case when calling this function
  6358. {
  6359. qDebug() << Q_FUNC_INFO << "shouldn't be called with fraction style fsDecimal";
  6360. return QString::number(numerator/double(denominator)); // failsafe
  6361. }
  6362. int sign = numerator*denominator < 0 ? -1 : 1;
  6363. numerator = qAbs(numerator);
  6364. denominator = qAbs(denominator);
  6365. if (denominator == 1)
  6366. {
  6367. return QString::number(sign*numerator);
  6368. } else
  6369. {
  6370. int integerPart = numerator/denominator;
  6371. int remainder = numerator%denominator;
  6372. if (remainder == 0)
  6373. {
  6374. return QString::number(sign*integerPart);
  6375. } else
  6376. {
  6377. if (mFractionStyle == fsAsciiFractions)
  6378. {
  6379. return QString(QLatin1String("%1%2%3/%4"))
  6380. .arg(sign == -1 ? QLatin1String("-") : QLatin1String(""))
  6381. .arg(integerPart > 0 ? QString::number(integerPart)+QLatin1String(" ") : QString(QLatin1String("")))
  6382. .arg(remainder)
  6383. .arg(denominator);
  6384. } else if (mFractionStyle == fsUnicodeFractions)
  6385. {
  6386. return QString(QLatin1String("%1%2%3"))
  6387. .arg(sign == -1 ? QLatin1String("-") : QLatin1String(""))
  6388. .arg(integerPart > 0 ? QString::number(integerPart) : QLatin1String(""))
  6389. .arg(unicodeFraction(remainder, denominator));
  6390. }
  6391. }
  6392. }
  6393. return QString();
  6394. }
  6395. /*! \internal
  6396. Returns the unicode string representation of the fraction given by \a numerator and \a
  6397. denominator. This is the representation used in \ref fractionToString when the fraction style
  6398. (\ref setFractionStyle) is \ref fsUnicodeFractions.
  6399. This method doesn't use the single-character common fractions but builds each fraction from a
  6400. superscript unicode number, the unicode fraction character, and a subscript unicode number.
  6401. */
  6402. QString QCPAxisTickerPi::unicodeFraction(int numerator, int denominator) const
  6403. {
  6404. return unicodeSuperscript(numerator)+QChar(0x2044)+unicodeSubscript(denominator);
  6405. }
  6406. /*! \internal
  6407. Returns the unicode string representing \a number as superscript. This is used to build
  6408. unicode fractions in \ref unicodeFraction.
  6409. */
  6410. QString QCPAxisTickerPi::unicodeSuperscript(int number) const
  6411. {
  6412. if (number == 0)
  6413. return QString(QChar(0x2070));
  6414. QString result;
  6415. while (number > 0)
  6416. {
  6417. const int digit = number%10;
  6418. switch (digit)
  6419. {
  6420. case 1: { result.prepend(QChar(0x00B9)); break; }
  6421. case 2: { result.prepend(QChar(0x00B2)); break; }
  6422. case 3: { result.prepend(QChar(0x00B3)); break; }
  6423. default: { result.prepend(QChar(0x2070+digit)); break; }
  6424. }
  6425. number /= 10;
  6426. }
  6427. return result;
  6428. }
  6429. /*! \internal
  6430. Returns the unicode string representing \a number as subscript. This is used to build unicode
  6431. fractions in \ref unicodeFraction.
  6432. */
  6433. QString QCPAxisTickerPi::unicodeSubscript(int number) const
  6434. {
  6435. if (number == 0)
  6436. return QString(QChar(0x2080));
  6437. QString result;
  6438. while (number > 0)
  6439. {
  6440. result.prepend(QChar(0x2080+number%10));
  6441. number /= 10;
  6442. }
  6443. return result;
  6444. }
  6445. /* end of 'src/axis/axistickerpi.cpp' */
  6446. /* including file 'src/axis/axistickerlog.cpp' */
  6447. /* modified 2022-11-06T12:45:56, size 7890 */
  6448. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6449. //////////////////// QCPAxisTickerLog
  6450. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6451. /*! \class QCPAxisTickerLog
  6452. \brief Specialized axis ticker suited for logarithmic axes
  6453. \image html axisticker-log.png
  6454. This QCPAxisTicker subclass generates ticks with unequal tick intervals suited for logarithmic
  6455. axis scales. The ticks are placed at powers of the specified log base (\ref setLogBase).
  6456. Especially in the case of a log base equal to 10 (the default), it might be desirable to have
  6457. tick labels in the form of powers of ten without mantissa display. To achieve this, set the
  6458. number precision (\ref QCPAxis::setNumberPrecision) to zero and the number format (\ref
  6459. QCPAxis::setNumberFormat) to scientific (exponential) display with beautifully typeset decimal
  6460. powers, so a format string of <tt>"eb"</tt>. This will result in the following axis tick labels:
  6461. \image html axisticker-log-powers.png
  6462. The ticker can be created and assigned to an axis like this:
  6463. \snippet documentation/doc-image-generator/mainwindow.cpp axistickerlog-creation
  6464. Note that the nature of logarithmic ticks imply that there exists a smallest possible tick step,
  6465. corresponding to one multiplication by the log base. If the user zooms in further than that, no
  6466. new ticks would appear, leading to very sparse or even no axis ticks on the axis. To prevent this
  6467. situation, this ticker falls back to regular tick generation if the axis range would be covered
  6468. by too few logarithmically placed ticks.
  6469. */
  6470. /*!
  6471. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  6472. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  6473. */
  6474. QCPAxisTickerLog::QCPAxisTickerLog() :
  6475. mLogBase(10.0),
  6476. mSubTickCount(8), // generates 10 intervals
  6477. mLogBaseLnInv(1.0/qLn(mLogBase))
  6478. {
  6479. }
  6480. /*!
  6481. Sets the logarithm base used for tick coordinate generation. The ticks will be placed at integer
  6482. powers of \a base.
  6483. */
  6484. void QCPAxisTickerLog::setLogBase(double base)
  6485. {
  6486. if (base > 0)
  6487. {
  6488. mLogBase = base;
  6489. mLogBaseLnInv = 1.0/qLn(mLogBase);
  6490. } else
  6491. qDebug() << Q_FUNC_INFO << "log base has to be greater than zero:" << base;
  6492. }
  6493. /*!
  6494. Sets the number of sub ticks in a tick interval. Within each interval, the sub ticks are spaced
  6495. linearly to provide a better visual guide, so the sub tick density increases toward the higher
  6496. tick.
  6497. Note that \a subTicks is the number of sub ticks (not sub intervals) in one tick interval. So in
  6498. the case of logarithm base 10 an intuitive sub tick spacing would be achieved with eight sub
  6499. ticks (the default). This means e.g. between the ticks 10 and 100 there will be eight ticks,
  6500. namely at 20, 30, 40, 50, 60, 70, 80 and 90.
  6501. */
  6502. void QCPAxisTickerLog::setSubTickCount(int subTicks)
  6503. {
  6504. if (subTicks >= 0)
  6505. mSubTickCount = subTicks;
  6506. else
  6507. qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks;
  6508. }
  6509. /*! \internal
  6510. Returns the sub tick count specified in \ref setSubTickCount. For QCPAxisTickerLog, there is no
  6511. automatic sub tick count calculation necessary.
  6512. \seebaseclassmethod
  6513. */
  6514. int QCPAxisTickerLog::getSubTickCount(double tickStep)
  6515. {
  6516. Q_UNUSED(tickStep)
  6517. return mSubTickCount;
  6518. }
  6519. /*! \internal
  6520. Creates ticks with a spacing given by the logarithm base and an increasing integer power in the
  6521. provided \a range. The step in which the power increases tick by tick is chosen in order to keep
  6522. the total number of ticks as close as possible to the tick count (\ref setTickCount).
  6523. The parameter \a tickStep is ignored for the normal logarithmic ticker generation. Only when
  6524. zoomed in very far such that not enough logarithmically placed ticks would be visible, this
  6525. function falls back to the regular QCPAxisTicker::createTickVector, which then uses \a tickStep.
  6526. \seebaseclassmethod
  6527. */
  6528. QVector<double> QCPAxisTickerLog::createTickVector(double tickStep, const QCPRange &range)
  6529. {
  6530. QVector<double> result;
  6531. if (range.lower > 0 && range.upper > 0) // positive range
  6532. {
  6533. const double baseTickCount = qLn(range.upper/range.lower)*mLogBaseLnInv;
  6534. if (baseTickCount < 1.6) // if too few log ticks would be visible in axis range, fall back to regular tick vector generation
  6535. return QCPAxisTicker::createTickVector(tickStep, range);
  6536. const double exactPowerStep = baseTickCount/double(mTickCount+1e-10);
  6537. const double newLogBase = qPow(mLogBase, qMax(int(cleanMantissa(exactPowerStep)), 1));
  6538. double currentTick = qPow(newLogBase, qFloor(qLn(range.lower)/qLn(newLogBase)));
  6539. result.append(currentTick);
  6540. while (currentTick < range.upper && currentTick > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
  6541. {
  6542. currentTick *= newLogBase;
  6543. result.append(currentTick);
  6544. }
  6545. } else if (range.lower < 0 && range.upper < 0) // negative range
  6546. {
  6547. const double baseTickCount = qLn(range.lower/range.upper)*mLogBaseLnInv;
  6548. if (baseTickCount < 1.6) // if too few log ticks would be visible in axis range, fall back to regular tick vector generation
  6549. return QCPAxisTicker::createTickVector(tickStep, range);
  6550. const double exactPowerStep = baseTickCount/double(mTickCount+1e-10);
  6551. const double newLogBase = qPow(mLogBase, qMax(int(cleanMantissa(exactPowerStep)), 1));
  6552. double currentTick = -qPow(newLogBase, qCeil(qLn(-range.lower)/qLn(newLogBase)));
  6553. result.append(currentTick);
  6554. while (currentTick < range.upper && currentTick < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
  6555. {
  6556. currentTick /= newLogBase;
  6557. result.append(currentTick);
  6558. }
  6559. } else // invalid range for logarithmic scale, because lower and upper have different sign
  6560. {
  6561. qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << range.lower << ".." << range.upper;
  6562. }
  6563. return result;
  6564. }
  6565. /* end of 'src/axis/axistickerlog.cpp' */
  6566. /* including file 'src/axis/axis.cpp' */
  6567. /* modified 2022-11-06T12:45:56, size 99911 */
  6568. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6569. //////////////////// QCPGrid
  6570. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6571. /*! \class QCPGrid
  6572. \brief Responsible for drawing the grid of a QCPAxis.
  6573. This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the
  6574. grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref
  6575. QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself.
  6576. The axis and grid drawing was split into two classes to allow them to be placed on different
  6577. layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid
  6578. in the background and the axes in the foreground, and any plottables/items in between. This
  6579. described situation is the default setup, see the QCPLayer documentation.
  6580. */
  6581. /*!
  6582. Creates a QCPGrid instance and sets default values.
  6583. You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid.
  6584. */
  6585. QCPGrid::QCPGrid(QCPAxis *parentAxis) :
  6586. QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis),
  6587. mSubGridVisible{},
  6588. mAntialiasedSubGrid{},
  6589. mAntialiasedZeroLine{},
  6590. mParentAxis(parentAxis)
  6591. {
  6592. // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called
  6593. setParent(parentAxis);
  6594. setPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
  6595. setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
  6596. setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine));
  6597. setSubGridVisible(false);
  6598. setAntialiased(false);
  6599. setAntialiasedSubGrid(false);
  6600. setAntialiasedZeroLine(false);
  6601. }
  6602. /*!
  6603. Sets whether grid lines at sub tick marks are drawn.
  6604. \see setSubGridPen
  6605. */
  6606. void QCPGrid::setSubGridVisible(bool visible)
  6607. {
  6608. mSubGridVisible = visible;
  6609. }
  6610. /*!
  6611. Sets whether sub grid lines are drawn antialiased.
  6612. */
  6613. void QCPGrid::setAntialiasedSubGrid(bool enabled)
  6614. {
  6615. mAntialiasedSubGrid = enabled;
  6616. }
  6617. /*!
  6618. Sets whether zero lines are drawn antialiased.
  6619. */
  6620. void QCPGrid::setAntialiasedZeroLine(bool enabled)
  6621. {
  6622. mAntialiasedZeroLine = enabled;
  6623. }
  6624. /*!
  6625. Sets the pen with which (major) grid lines are drawn.
  6626. */
  6627. void QCPGrid::setPen(const QPen &pen)
  6628. {
  6629. mPen = pen;
  6630. }
  6631. /*!
  6632. Sets the pen with which sub grid lines are drawn.
  6633. */
  6634. void QCPGrid::setSubGridPen(const QPen &pen)
  6635. {
  6636. mSubGridPen = pen;
  6637. }
  6638. /*!
  6639. Sets the pen with which zero lines are drawn.
  6640. Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid
  6641. lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen.
  6642. */
  6643. void QCPGrid::setZeroLinePen(const QPen &pen)
  6644. {
  6645. mZeroLinePen = pen;
  6646. }
  6647. /*! \internal
  6648. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  6649. before drawing the major grid lines.
  6650. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  6651. This function takes into account the local setting of the antialiasing flag as well as the
  6652. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  6653. QCustomPlot::setNotAntialiasedElements.
  6654. \see setAntialiased
  6655. */
  6656. void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const
  6657. {
  6658. applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid);
  6659. }
  6660. /*! \internal
  6661. Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning
  6662. over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen).
  6663. */
  6664. void QCPGrid::draw(QCPPainter *painter)
  6665. {
  6666. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  6667. if (mParentAxis->subTicks() && mSubGridVisible)
  6668. drawSubGridLines(painter);
  6669. drawGridLines(painter);
  6670. }
  6671. /*! \internal
  6672. Draws the main grid lines and possibly a zero line with the specified painter.
  6673. This is a helper function called by \ref draw.
  6674. */
  6675. void QCPGrid::drawGridLines(QCPPainter *painter) const
  6676. {
  6677. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  6678. const int tickCount = mParentAxis->mTickVector.size();
  6679. double t; // helper variable, result of coordinate-to-pixel transforms
  6680. if (mParentAxis->orientation() == Qt::Horizontal)
  6681. {
  6682. // draw zeroline:
  6683. int zeroLineIndex = -1;
  6684. if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
  6685. {
  6686. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  6687. painter->setPen(mZeroLinePen);
  6688. double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero
  6689. for (int i=0; i<tickCount; ++i)
  6690. {
  6691. if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
  6692. {
  6693. zeroLineIndex = i;
  6694. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
  6695. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  6696. break;
  6697. }
  6698. }
  6699. }
  6700. // draw grid lines:
  6701. applyDefaultAntialiasingHint(painter);
  6702. painter->setPen(mPen);
  6703. for (int i=0; i<tickCount; ++i)
  6704. {
  6705. if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
  6706. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
  6707. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  6708. }
  6709. } else
  6710. {
  6711. // draw zeroline:
  6712. int zeroLineIndex = -1;
  6713. if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
  6714. {
  6715. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  6716. painter->setPen(mZeroLinePen);
  6717. double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero
  6718. for (int i=0; i<tickCount; ++i)
  6719. {
  6720. if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
  6721. {
  6722. zeroLineIndex = i;
  6723. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
  6724. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  6725. break;
  6726. }
  6727. }
  6728. }
  6729. // draw grid lines:
  6730. applyDefaultAntialiasingHint(painter);
  6731. painter->setPen(mPen);
  6732. for (int i=0; i<tickCount; ++i)
  6733. {
  6734. if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
  6735. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
  6736. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  6737. }
  6738. }
  6739. }
  6740. /*! \internal
  6741. Draws the sub grid lines with the specified painter.
  6742. This is a helper function called by \ref draw.
  6743. */
  6744. void QCPGrid::drawSubGridLines(QCPPainter *painter) const
  6745. {
  6746. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  6747. applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid);
  6748. double t; // helper variable, result of coordinate-to-pixel transforms
  6749. painter->setPen(mSubGridPen);
  6750. if (mParentAxis->orientation() == Qt::Horizontal)
  6751. {
  6752. foreach (double tickCoord, mParentAxis->mSubTickVector)
  6753. {
  6754. t = mParentAxis->coordToPixel(tickCoord); // x
  6755. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  6756. }
  6757. } else
  6758. {
  6759. foreach (double tickCoord, mParentAxis->mSubTickVector)
  6760. {
  6761. t = mParentAxis->coordToPixel(tickCoord); // y
  6762. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  6763. }
  6764. }
  6765. }
  6766. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6767. //////////////////// QCPAxis
  6768. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6769. /*! \class QCPAxis
  6770. \brief Manages a single axis inside a QCustomPlot.
  6771. Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via
  6772. QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and
  6773. QCustomPlot::yAxis2 (right).
  6774. Axes are always part of an axis rect, see QCPAxisRect.
  6775. \image html AxisNamesOverview.png
  6776. <center>Naming convention of axis parts</center>
  6777. \n
  6778. \image html AxisRectSpacingOverview.png
  6779. <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line
  6780. on the left represents the QCustomPlot widget border.</center>
  6781. Each axis holds an instance of QCPAxisTicker which is used to generate the tick coordinates and
  6782. tick labels. You can access the currently installed \ref ticker or set a new one (possibly one of
  6783. the specialized subclasses, or your own subclass) via \ref setTicker. For details, see the
  6784. documentation of QCPAxisTicker.
  6785. */
  6786. /* start of documentation of inline functions */
  6787. /*! \fn Qt::Orientation QCPAxis::orientation() const
  6788. Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced
  6789. from the axis type (left, top, right or bottom).
  6790. \see orientation(AxisType type), pixelOrientation
  6791. */
  6792. /*! \fn QCPGrid *QCPAxis::grid() const
  6793. Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the
  6794. grid is displayed.
  6795. */
  6796. /*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type)
  6797. Returns the orientation of the specified axis type
  6798. \see orientation(), pixelOrientation
  6799. */
  6800. /*! \fn int QCPAxis::pixelOrientation() const
  6801. Returns which direction points towards higher coordinate values/keys, in pixel space.
  6802. This method returns either 1 or -1. If it returns 1, then going in the positive direction along
  6803. the orientation of the axis in pixels corresponds to going from lower to higher axis coordinates.
  6804. On the other hand, if this method returns -1, going to smaller pixel values corresponds to going
  6805. from lower to higher axis coordinates.
  6806. For example, this is useful to easily shift axis coordinates by a certain amount given in pixels,
  6807. without having to care about reversed or vertically aligned axes:
  6808. \code
  6809. double newKey = keyAxis->pixelToCoord(keyAxis->coordToPixel(oldKey)+10*keyAxis->pixelOrientation());
  6810. \endcode
  6811. \a newKey will then contain a key that is ten pixels towards higher keys, starting from \a oldKey.
  6812. */
  6813. /*! \fn QSharedPointer<QCPAxisTicker> QCPAxis::ticker() const
  6814. Returns a modifiable shared pointer to the currently installed axis ticker. The axis ticker is
  6815. responsible for generating the tick positions and tick labels of this axis. You can access the
  6816. \ref QCPAxisTicker with this method and modify basic properties such as the approximate tick count
  6817. (\ref QCPAxisTicker::setTickCount).
  6818. You can gain more control over the axis ticks by setting a different \ref QCPAxisTicker subclass, see
  6819. the documentation there. A new axis ticker can be set with \ref setTicker.
  6820. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  6821. ticker simply by passing the same shared pointer to multiple axes.
  6822. \see setTicker
  6823. */
  6824. /* end of documentation of inline functions */
  6825. /* start of documentation of signals */
  6826. /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange)
  6827. This signal is emitted when the range of this axis has changed. You can connect it to the \ref
  6828. setRange slot of another axis to communicate the new range to the other axis, in order for it to
  6829. be synchronized.
  6830. You may also manipulate/correct the range with \ref setRange in a slot connected to this signal.
  6831. This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper
  6832. range shouldn't go beyond certain values (see \ref QCPRange::bounded). For example, the following
  6833. slot would limit the x axis to ranges between 0 and 10:
  6834. \code
  6835. customPlot->xAxis->setRange(newRange.bounded(0, 10))
  6836. \endcode
  6837. */
  6838. /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange)
  6839. \overload
  6840. Additionally to the new range, this signal also provides the previous range held by the axis as
  6841. \a oldRange.
  6842. */
  6843. /*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType);
  6844. This signal is emitted when the scale type changes, by calls to \ref setScaleType
  6845. */
  6846. /*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection)
  6847. This signal is emitted when the selection state of this axis has changed, either by user interaction
  6848. or by a direct call to \ref setSelectedParts.
  6849. */
  6850. /*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts);
  6851. This signal is emitted when the selectability changes, by calls to \ref setSelectableParts
  6852. */
  6853. /* end of documentation of signals */
  6854. /*!
  6855. Constructs an Axis instance of Type \a type for the axis rect \a parent.
  6856. Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create
  6857. them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however,
  6858. create them manually and then inject them also via \ref QCPAxisRect::addAxis.
  6859. */
  6860. QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) :
  6861. QCPLayerable(parent->parentPlot(), QString(), parent),
  6862. // axis base:
  6863. mAxisType(type),
  6864. mAxisRect(parent),
  6865. mPadding(5),
  6866. mOrientation(orientation(type)),
  6867. mSelectableParts(spAxis | spTickLabels | spAxisLabel),
  6868. mSelectedParts(spNone),
  6869. mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  6870. mSelectedBasePen(QPen(Qt::blue, 2)),
  6871. // axis label:
  6872. mLabel(),
  6873. mLabelFont(mParentPlot->font()),
  6874. mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
  6875. mLabelColor(Qt::black),
  6876. mSelectedLabelColor(Qt::blue),
  6877. // tick labels:
  6878. mTickLabels(true),
  6879. mTickLabelFont(mParentPlot->font()),
  6880. mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
  6881. mTickLabelColor(Qt::black),
  6882. mSelectedTickLabelColor(Qt::blue),
  6883. mNumberPrecision(6),
  6884. mNumberFormatChar('g'),
  6885. mNumberBeautifulPowers(true),
  6886. // ticks and subticks:
  6887. mTicks(true),
  6888. mSubTicks(true),
  6889. mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  6890. mSelectedTickPen(QPen(Qt::blue, 2)),
  6891. mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  6892. mSelectedSubTickPen(QPen(Qt::blue, 2)),
  6893. // scale and range:
  6894. mRange(0, 5),
  6895. mRangeReversed(false),
  6896. mScaleType(stLinear),
  6897. // internal members:
  6898. mGrid(new QCPGrid(this)),
  6899. mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())),
  6900. mTicker(new QCPAxisTicker),
  6901. mCachedMarginValid(false),
  6902. mCachedMargin(0),
  6903. mDragging(false)
  6904. {
  6905. setParent(parent);
  6906. mGrid->setVisible(false);
  6907. setAntialiased(false);
  6908. 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
  6909. if (type == atTop)
  6910. {
  6911. setTickLabelPadding(3);
  6912. setLabelPadding(6);
  6913. } else if (type == atRight)
  6914. {
  6915. setTickLabelPadding(7);
  6916. setLabelPadding(12);
  6917. } else if (type == atBottom)
  6918. {
  6919. setTickLabelPadding(3);
  6920. setLabelPadding(3);
  6921. } else if (type == atLeft)
  6922. {
  6923. setTickLabelPadding(5);
  6924. setLabelPadding(10);
  6925. }
  6926. }
  6927. QCPAxis::~QCPAxis()
  6928. {
  6929. delete mAxisPainter;
  6930. delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order
  6931. }
  6932. /* No documentation as it is a property getter */
  6933. int QCPAxis::tickLabelPadding() const
  6934. {
  6935. return mAxisPainter->tickLabelPadding;
  6936. }
  6937. /* No documentation as it is a property getter */
  6938. double QCPAxis::tickLabelRotation() const
  6939. {
  6940. return mAxisPainter->tickLabelRotation;
  6941. }
  6942. /* No documentation as it is a property getter */
  6943. QCPAxis::LabelSide QCPAxis::tickLabelSide() const
  6944. {
  6945. return mAxisPainter->tickLabelSide;
  6946. }
  6947. /* No documentation as it is a property getter */
  6948. QString QCPAxis::numberFormat() const
  6949. {
  6950. QString result;
  6951. result.append(mNumberFormatChar);
  6952. if (mNumberBeautifulPowers)
  6953. {
  6954. result.append(QLatin1Char('b'));
  6955. if (mAxisPainter->numberMultiplyCross)
  6956. result.append(QLatin1Char('c'));
  6957. }
  6958. return result;
  6959. }
  6960. /* No documentation as it is a property getter */
  6961. int QCPAxis::tickLengthIn() const
  6962. {
  6963. return mAxisPainter->tickLengthIn;
  6964. }
  6965. /* No documentation as it is a property getter */
  6966. int QCPAxis::tickLengthOut() const
  6967. {
  6968. return mAxisPainter->tickLengthOut;
  6969. }
  6970. /* No documentation as it is a property getter */
  6971. int QCPAxis::subTickLengthIn() const
  6972. {
  6973. return mAxisPainter->subTickLengthIn;
  6974. }
  6975. /* No documentation as it is a property getter */
  6976. int QCPAxis::subTickLengthOut() const
  6977. {
  6978. return mAxisPainter->subTickLengthOut;
  6979. }
  6980. /* No documentation as it is a property getter */
  6981. int QCPAxis::labelPadding() const
  6982. {
  6983. return mAxisPainter->labelPadding;
  6984. }
  6985. /* No documentation as it is a property getter */
  6986. int QCPAxis::offset() const
  6987. {
  6988. return mAxisPainter->offset;
  6989. }
  6990. /* No documentation as it is a property getter */
  6991. QCPLineEnding QCPAxis::lowerEnding() const
  6992. {
  6993. return mAxisPainter->lowerEnding;
  6994. }
  6995. /* No documentation as it is a property getter */
  6996. QCPLineEnding QCPAxis::upperEnding() const
  6997. {
  6998. return mAxisPainter->upperEnding;
  6999. }
  7000. /*!
  7001. Sets whether the axis uses a linear scale or a logarithmic scale.
  7002. Note that this method controls the coordinate transformation. For logarithmic scales, you will
  7003. likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting
  7004. the axis ticker to an instance of \ref QCPAxisTickerLog :
  7005. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-creation
  7006. See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick
  7007. creation.
  7008. \ref setNumberPrecision
  7009. */
  7010. void QCPAxis::setScaleType(QCPAxis::ScaleType type)
  7011. {
  7012. if (mScaleType != type)
  7013. {
  7014. mScaleType = type;
  7015. if (mScaleType == stLogarithmic)
  7016. setRange(mRange.sanitizedForLogScale());
  7017. mCachedMarginValid = false;
  7018. emit scaleTypeChanged(mScaleType);
  7019. }
  7020. }
  7021. /*!
  7022. Sets the range of the axis.
  7023. This slot may be connected with the \ref rangeChanged signal of another axis so this axis
  7024. is always synchronized with the other axis range, when it changes.
  7025. To invert the direction of an axis, use \ref setRangeReversed.
  7026. */
  7027. void QCPAxis::setRange(const QCPRange &range)
  7028. {
  7029. if (range.lower == mRange.lower && range.upper == mRange.upper)
  7030. return;
  7031. if (!QCPRange::validRange(range)) return;
  7032. QCPRange oldRange = mRange;
  7033. if (mScaleType == stLogarithmic)
  7034. {
  7035. mRange = range.sanitizedForLogScale();
  7036. } else
  7037. {
  7038. mRange = range.sanitizedForLinScale();
  7039. }
  7040. emit rangeChanged(mRange);
  7041. emit rangeChanged(mRange, oldRange);
  7042. }
  7043. /*!
  7044. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  7045. (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
  7046. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  7047. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  7048. directly.
  7049. \see SelectablePart, setSelectedParts
  7050. */
  7051. void QCPAxis::setSelectableParts(const SelectableParts &selectable)
  7052. {
  7053. if (mSelectableParts != selectable)
  7054. {
  7055. mSelectableParts = selectable;
  7056. emit selectableChanged(mSelectableParts);
  7057. }
  7058. }
  7059. /*!
  7060. Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
  7061. is selected, it uses a different pen/font.
  7062. The entire selection mechanism for axes is handled automatically when \ref
  7063. QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
  7064. wish to change the selection state manually.
  7065. This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
  7066. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  7067. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
  7068. setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
  7069. */
  7070. void QCPAxis::setSelectedParts(const SelectableParts &selected)
  7071. {
  7072. if (mSelectedParts != selected)
  7073. {
  7074. mSelectedParts = selected;
  7075. emit selectionChanged(mSelectedParts);
  7076. }
  7077. }
  7078. /*!
  7079. \overload
  7080. Sets the lower and upper bound of the axis range.
  7081. To invert the direction of an axis, use \ref setRangeReversed.
  7082. There is also a slot to set a range, see \ref setRange(const QCPRange &range).
  7083. */
  7084. void QCPAxis::setRange(double lower, double upper)
  7085. {
  7086. if (lower == mRange.lower && upper == mRange.upper)
  7087. return;
  7088. if (!QCPRange::validRange(lower, upper)) return;
  7089. QCPRange oldRange = mRange;
  7090. mRange.lower = lower;
  7091. mRange.upper = upper;
  7092. if (mScaleType == stLogarithmic)
  7093. {
  7094. mRange = mRange.sanitizedForLogScale();
  7095. } else
  7096. {
  7097. mRange = mRange.sanitizedForLinScale();
  7098. }
  7099. emit rangeChanged(mRange);
  7100. emit rangeChanged(mRange, oldRange);
  7101. }
  7102. /*!
  7103. \overload
  7104. Sets the range of the axis.
  7105. The \a position coordinate indicates together with the \a alignment parameter, where the new
  7106. range will be positioned. \a size defines the size of the new axis range. \a alignment may be
  7107. Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
  7108. or center of the range to be aligned with \a position. Any other values of \a alignment will
  7109. default to Qt::AlignCenter.
  7110. */
  7111. void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment)
  7112. {
  7113. if (alignment == Qt::AlignLeft)
  7114. setRange(position, position+size);
  7115. else if (alignment == Qt::AlignRight)
  7116. setRange(position-size, position);
  7117. else // alignment == Qt::AlignCenter
  7118. setRange(position-size/2.0, position+size/2.0);
  7119. }
  7120. /*!
  7121. Sets the lower bound of the axis range. The upper bound is not changed.
  7122. \see setRange
  7123. */
  7124. void QCPAxis::setRangeLower(double lower)
  7125. {
  7126. if (mRange.lower == lower)
  7127. return;
  7128. QCPRange oldRange = mRange;
  7129. mRange.lower = lower;
  7130. if (mScaleType == stLogarithmic)
  7131. {
  7132. mRange = mRange.sanitizedForLogScale();
  7133. } else
  7134. {
  7135. mRange = mRange.sanitizedForLinScale();
  7136. }
  7137. emit rangeChanged(mRange);
  7138. emit rangeChanged(mRange, oldRange);
  7139. }
  7140. /*!
  7141. Sets the upper bound of the axis range. The lower bound is not changed.
  7142. \see setRange
  7143. */
  7144. void QCPAxis::setRangeUpper(double upper)
  7145. {
  7146. if (mRange.upper == upper)
  7147. return;
  7148. QCPRange oldRange = mRange;
  7149. mRange.upper = upper;
  7150. if (mScaleType == stLogarithmic)
  7151. {
  7152. mRange = mRange.sanitizedForLogScale();
  7153. } else
  7154. {
  7155. mRange = mRange.sanitizedForLinScale();
  7156. }
  7157. emit rangeChanged(mRange);
  7158. emit rangeChanged(mRange, oldRange);
  7159. }
  7160. /*!
  7161. Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
  7162. axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
  7163. direction of increasing values is inverted.
  7164. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
  7165. of the \ref setRange interface will still reference the mathematically smaller number than the \a
  7166. upper part.
  7167. */
  7168. void QCPAxis::setRangeReversed(bool reversed)
  7169. {
  7170. mRangeReversed = reversed;
  7171. }
  7172. /*!
  7173. The axis ticker is responsible for generating the tick positions and tick labels. See the
  7174. documentation of QCPAxisTicker for details on how to work with axis tickers.
  7175. You can change the tick positioning/labeling behaviour of this axis by setting a different
  7176. QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
  7177. ticker, access it via \ref ticker.
  7178. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  7179. ticker simply by passing the same shared pointer to multiple axes.
  7180. \see ticker
  7181. */
  7182. void QCPAxis::setTicker(QSharedPointer<QCPAxisTicker> ticker)
  7183. {
  7184. if (ticker)
  7185. mTicker = ticker;
  7186. else
  7187. qDebug() << Q_FUNC_INFO << "can not set nullptr as axis ticker";
  7188. // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
  7189. }
  7190. /*!
  7191. Sets whether tick marks are displayed.
  7192. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
  7193. that, see \ref setTickLabels.
  7194. \see setSubTicks
  7195. */
  7196. void QCPAxis::setTicks(bool show)
  7197. {
  7198. if (mTicks != show)
  7199. {
  7200. mTicks = show;
  7201. mCachedMarginValid = false;
  7202. }
  7203. }
  7204. /*!
  7205. Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
  7206. */
  7207. void QCPAxis::setTickLabels(bool show)
  7208. {
  7209. if (mTickLabels != show)
  7210. {
  7211. mTickLabels = show;
  7212. mCachedMarginValid = false;
  7213. if (!mTickLabels)
  7214. mTickVectorLabels.clear();
  7215. }
  7216. }
  7217. /*!
  7218. Sets the distance between the axis base line (including any outward ticks) and the tick labels.
  7219. \see setLabelPadding, setPadding
  7220. */
  7221. void QCPAxis::setTickLabelPadding(int padding)
  7222. {
  7223. if (mAxisPainter->tickLabelPadding != padding)
  7224. {
  7225. mAxisPainter->tickLabelPadding = padding;
  7226. mCachedMarginValid = false;
  7227. }
  7228. }
  7229. /*!
  7230. Sets the font of the tick labels.
  7231. \see setTickLabels, setTickLabelColor
  7232. */
  7233. void QCPAxis::setTickLabelFont(const QFont &font)
  7234. {
  7235. if (font != mTickLabelFont)
  7236. {
  7237. mTickLabelFont = font;
  7238. mCachedMarginValid = false;
  7239. }
  7240. }
  7241. /*!
  7242. Sets the color of the tick labels.
  7243. \see setTickLabels, setTickLabelFont
  7244. */
  7245. void QCPAxis::setTickLabelColor(const QColor &color)
  7246. {
  7247. mTickLabelColor = color;
  7248. }
  7249. /*!
  7250. Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
  7251. the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
  7252. from -90 to 90 degrees.
  7253. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
  7254. other angles, the label is drawn with an offset such that it seems to point toward or away from
  7255. the tick mark.
  7256. */
  7257. void QCPAxis::setTickLabelRotation(double degrees)
  7258. {
  7259. if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation))
  7260. {
  7261. mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0);
  7262. mCachedMarginValid = false;
  7263. }
  7264. }
  7265. /*!
  7266. Sets whether the tick labels (numbers) shall appear inside or outside the axis rect.
  7267. The usual and default setting is \ref lsOutside. Very compact plots sometimes require tick labels
  7268. to be inside the axis rect, to save space. If \a side is set to \ref lsInside, the tick labels
  7269. appear on the inside are additionally clipped to the axis rect.
  7270. */
  7271. void QCPAxis::setTickLabelSide(LabelSide side)
  7272. {
  7273. mAxisPainter->tickLabelSide = side;
  7274. mCachedMarginValid = false;
  7275. }
  7276. /*!
  7277. Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
  7278. of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
  7279. that, see the "Argument Formats" section in the detailed description of the QString class.
  7280. \a formatCode is a string of one, two or three characters.
  7281. <b>The first character</b> is identical to
  7282. the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
  7283. format, 'g'/'G' scientific or fixed, whichever is shorter. For the 'e', 'E', and 'f' formats,
  7284. the precision set by \ref setNumberPrecision represents the number of digits after the decimal
  7285. point. For the 'g' and 'G' formats, the precision represents the maximum number of significant
  7286. digits, trailing zeroes are omitted.
  7287. <b>The second and third characters</b> are optional and specific to QCustomPlot:\n
  7288. If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
  7289. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for
  7290. "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
  7291. [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
  7292. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
  7293. be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
  7294. cross and 183 (0xB7) for the dot.
  7295. Examples for \a formatCode:
  7296. \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
  7297. normal scientific format is used
  7298. \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
  7299. beautifully typeset decimal powers and a dot as multiplication sign
  7300. \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
  7301. multiplication sign
  7302. \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
  7303. powers. Format code will be reduced to 'f'.
  7304. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
  7305. code will not be changed.
  7306. */
  7307. void QCPAxis::setNumberFormat(const QString &formatCode)
  7308. {
  7309. if (formatCode.isEmpty())
  7310. {
  7311. qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
  7312. return;
  7313. }
  7314. mCachedMarginValid = false;
  7315. // interpret first char as number format char:
  7316. QString allowedFormatChars(QLatin1String("eEfgG"));
  7317. if (allowedFormatChars.contains(formatCode.at(0)))
  7318. {
  7319. mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
  7320. } else
  7321. {
  7322. qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
  7323. return;
  7324. }
  7325. if (formatCode.length() < 2)
  7326. {
  7327. mNumberBeautifulPowers = false;
  7328. mAxisPainter->numberMultiplyCross = false;
  7329. return;
  7330. }
  7331. // interpret second char as indicator for beautiful decimal powers:
  7332. if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
  7333. {
  7334. mNumberBeautifulPowers = true;
  7335. } else
  7336. {
  7337. qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
  7338. return;
  7339. }
  7340. if (formatCode.length() < 3)
  7341. {
  7342. mAxisPainter->numberMultiplyCross = false;
  7343. return;
  7344. }
  7345. // interpret third char as indicator for dot or cross multiplication symbol:
  7346. if (formatCode.at(2) == QLatin1Char('c'))
  7347. {
  7348. mAxisPainter->numberMultiplyCross = true;
  7349. } else if (formatCode.at(2) == QLatin1Char('d'))
  7350. {
  7351. mAxisPainter->numberMultiplyCross = false;
  7352. } else
  7353. {
  7354. qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
  7355. return;
  7356. }
  7357. }
  7358. /*!
  7359. Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
  7360. for details. The effect of precisions are most notably for number Formats starting with 'e', see
  7361. \ref setNumberFormat
  7362. */
  7363. void QCPAxis::setNumberPrecision(int precision)
  7364. {
  7365. if (mNumberPrecision != precision)
  7366. {
  7367. mNumberPrecision = precision;
  7368. mCachedMarginValid = false;
  7369. }
  7370. }
  7371. /*!
  7372. Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
  7373. plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
  7374. zero, the tick labels and axis label will increase their distance to the axis accordingly, so
  7375. they won't collide with the ticks.
  7376. \see setSubTickLength, setTickLengthIn, setTickLengthOut
  7377. */
  7378. void QCPAxis::setTickLength(int inside, int outside)
  7379. {
  7380. setTickLengthIn(inside);
  7381. setTickLengthOut(outside);
  7382. }
  7383. /*!
  7384. Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
  7385. inside the plot.
  7386. \see setTickLengthOut, setTickLength, setSubTickLength
  7387. */
  7388. void QCPAxis::setTickLengthIn(int inside)
  7389. {
  7390. if (mAxisPainter->tickLengthIn != inside)
  7391. {
  7392. mAxisPainter->tickLengthIn = inside;
  7393. }
  7394. }
  7395. /*!
  7396. Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
  7397. outside the plot. If \a outside is greater than zero, the tick labels and axis label will
  7398. increase their distance to the axis accordingly, so they won't collide with the ticks.
  7399. \see setTickLengthIn, setTickLength, setSubTickLength
  7400. */
  7401. void QCPAxis::setTickLengthOut(int outside)
  7402. {
  7403. if (mAxisPainter->tickLengthOut != outside)
  7404. {
  7405. mAxisPainter->tickLengthOut = outside;
  7406. mCachedMarginValid = false; // only outside tick length can change margin
  7407. }
  7408. }
  7409. /*!
  7410. Sets whether sub tick marks are displayed.
  7411. Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
  7412. \see setTicks
  7413. */
  7414. void QCPAxis::setSubTicks(bool show)
  7415. {
  7416. if (mSubTicks != show)
  7417. {
  7418. mSubTicks = show;
  7419. mCachedMarginValid = false;
  7420. }
  7421. }
  7422. /*!
  7423. Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
  7424. the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
  7425. than zero, the tick labels and axis label will increase their distance to the axis accordingly,
  7426. so they won't collide with the ticks.
  7427. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
  7428. */
  7429. void QCPAxis::setSubTickLength(int inside, int outside)
  7430. {
  7431. setSubTickLengthIn(inside);
  7432. setSubTickLengthOut(outside);
  7433. }
  7434. /*!
  7435. Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
  7436. the plot.
  7437. \see setSubTickLengthOut, setSubTickLength, setTickLength
  7438. */
  7439. void QCPAxis::setSubTickLengthIn(int inside)
  7440. {
  7441. if (mAxisPainter->subTickLengthIn != inside)
  7442. {
  7443. mAxisPainter->subTickLengthIn = inside;
  7444. }
  7445. }
  7446. /*!
  7447. Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
  7448. outside the plot. If \a outside is greater than zero, the tick labels will increase their
  7449. distance to the axis accordingly, so they won't collide with the ticks.
  7450. \see setSubTickLengthIn, setSubTickLength, setTickLength
  7451. */
  7452. void QCPAxis::setSubTickLengthOut(int outside)
  7453. {
  7454. if (mAxisPainter->subTickLengthOut != outside)
  7455. {
  7456. mAxisPainter->subTickLengthOut = outside;
  7457. mCachedMarginValid = false; // only outside tick length can change margin
  7458. }
  7459. }
  7460. /*!
  7461. Sets the pen, the axis base line is drawn with.
  7462. \see setTickPen, setSubTickPen
  7463. */
  7464. void QCPAxis::setBasePen(const QPen &pen)
  7465. {
  7466. mBasePen = pen;
  7467. }
  7468. /*!
  7469. Sets the pen, tick marks will be drawn with.
  7470. \see setTickLength, setBasePen
  7471. */
  7472. void QCPAxis::setTickPen(const QPen &pen)
  7473. {
  7474. mTickPen = pen;
  7475. }
  7476. /*!
  7477. Sets the pen, subtick marks will be drawn with.
  7478. \see setSubTickCount, setSubTickLength, setBasePen
  7479. */
  7480. void QCPAxis::setSubTickPen(const QPen &pen)
  7481. {
  7482. mSubTickPen = pen;
  7483. }
  7484. /*!
  7485. Sets the font of the axis label.
  7486. \see setLabelColor
  7487. */
  7488. void QCPAxis::setLabelFont(const QFont &font)
  7489. {
  7490. if (mLabelFont != font)
  7491. {
  7492. mLabelFont = font;
  7493. mCachedMarginValid = false;
  7494. }
  7495. }
  7496. /*!
  7497. Sets the color of the axis label.
  7498. \see setLabelFont
  7499. */
  7500. void QCPAxis::setLabelColor(const QColor &color)
  7501. {
  7502. mLabelColor = color;
  7503. }
  7504. /*!
  7505. Sets the text of the axis label that will be shown below/above or next to the axis, depending on
  7506. its orientation. To disable axis labels, pass an empty string as \a str.
  7507. */
  7508. void QCPAxis::setLabel(const QString &str)
  7509. {
  7510. if (mLabel != str)
  7511. {
  7512. mLabel = str;
  7513. mCachedMarginValid = false;
  7514. }
  7515. }
  7516. /*!
  7517. Sets the distance between the tick labels and the axis label.
  7518. \see setTickLabelPadding, setPadding
  7519. */
  7520. void QCPAxis::setLabelPadding(int padding)
  7521. {
  7522. if (mAxisPainter->labelPadding != padding)
  7523. {
  7524. mAxisPainter->labelPadding = padding;
  7525. mCachedMarginValid = false;
  7526. }
  7527. }
  7528. /*!
  7529. Sets the padding of the axis.
  7530. When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space,
  7531. that is left blank.
  7532. The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled.
  7533. \see setLabelPadding, setTickLabelPadding
  7534. */
  7535. void QCPAxis::setPadding(int padding)
  7536. {
  7537. if (mPadding != padding)
  7538. {
  7539. mPadding = padding;
  7540. mCachedMarginValid = false;
  7541. }
  7542. }
  7543. /*!
  7544. Sets the offset the axis has to its axis rect side.
  7545. If an axis rect side has multiple axes and automatic margin calculation is enabled for that side,
  7546. only the offset of the inner most axis has meaning (even if it is set to be invisible). The
  7547. offset of the other, outer axes is controlled automatically, to place them at appropriate
  7548. positions.
  7549. */
  7550. void QCPAxis::setOffset(int offset)
  7551. {
  7552. mAxisPainter->offset = offset;
  7553. }
  7554. /*!
  7555. Sets the font that is used for tick labels when they are selected.
  7556. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7557. */
  7558. void QCPAxis::setSelectedTickLabelFont(const QFont &font)
  7559. {
  7560. if (font != mSelectedTickLabelFont)
  7561. {
  7562. mSelectedTickLabelFont = font;
  7563. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  7564. }
  7565. }
  7566. /*!
  7567. Sets the font that is used for the axis label when it is selected.
  7568. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7569. */
  7570. void QCPAxis::setSelectedLabelFont(const QFont &font)
  7571. {
  7572. mSelectedLabelFont = font;
  7573. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  7574. }
  7575. /*!
  7576. Sets the color that is used for tick labels when they are selected.
  7577. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7578. */
  7579. void QCPAxis::setSelectedTickLabelColor(const QColor &color)
  7580. {
  7581. if (color != mSelectedTickLabelColor)
  7582. {
  7583. mSelectedTickLabelColor = color;
  7584. }
  7585. }
  7586. /*!
  7587. Sets the color that is used for the axis label when it is selected.
  7588. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7589. */
  7590. void QCPAxis::setSelectedLabelColor(const QColor &color)
  7591. {
  7592. mSelectedLabelColor = color;
  7593. }
  7594. /*!
  7595. Sets the pen that is used to draw the axis base line when selected.
  7596. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7597. */
  7598. void QCPAxis::setSelectedBasePen(const QPen &pen)
  7599. {
  7600. mSelectedBasePen = pen;
  7601. }
  7602. /*!
  7603. Sets the pen that is used to draw the (major) ticks when selected.
  7604. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7605. */
  7606. void QCPAxis::setSelectedTickPen(const QPen &pen)
  7607. {
  7608. mSelectedTickPen = pen;
  7609. }
  7610. /*!
  7611. Sets the pen that is used to draw the subticks when selected.
  7612. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7613. */
  7614. void QCPAxis::setSelectedSubTickPen(const QPen &pen)
  7615. {
  7616. mSelectedSubTickPen = pen;
  7617. }
  7618. /*!
  7619. Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available
  7620. styles.
  7621. For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending.
  7622. Note that this meaning does not change when the axis range is reversed with \ref
  7623. setRangeReversed.
  7624. \see setUpperEnding
  7625. */
  7626. void QCPAxis::setLowerEnding(const QCPLineEnding &ending)
  7627. {
  7628. mAxisPainter->lowerEnding = ending;
  7629. }
  7630. /*!
  7631. Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available
  7632. styles.
  7633. For horizontal axes, this method refers to the right ending, for vertical axes the top ending.
  7634. Note that this meaning does not change when the axis range is reversed with \ref
  7635. setRangeReversed.
  7636. \see setLowerEnding
  7637. */
  7638. void QCPAxis::setUpperEnding(const QCPLineEnding &ending)
  7639. {
  7640. mAxisPainter->upperEnding = ending;
  7641. }
  7642. /*!
  7643. If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
  7644. bounds of the range. The range is simply moved by \a diff.
  7645. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
  7646. corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
  7647. */
  7648. void QCPAxis::moveRange(double diff)
  7649. {
  7650. QCPRange oldRange = mRange;
  7651. if (mScaleType == stLinear)
  7652. {
  7653. mRange.lower += diff;
  7654. mRange.upper += diff;
  7655. } else // mScaleType == stLogarithmic
  7656. {
  7657. mRange.lower *= diff;
  7658. mRange.upper *= diff;
  7659. }
  7660. emit rangeChanged(mRange);
  7661. emit rangeChanged(mRange, oldRange);
  7662. }
  7663. /*!
  7664. Scales the range of this axis by \a factor around the center of the current axis range. For
  7665. example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
  7666. range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
  7667. the center will have moved symmetrically closer).
  7668. If you wish to scale around a different coordinate than the current axis range center, use the
  7669. overload \ref scaleRange(double factor, double center).
  7670. */
  7671. void QCPAxis::scaleRange(double factor)
  7672. {
  7673. scaleRange(factor, range().center());
  7674. }
  7675. /*! \overload
  7676. Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
  7677. factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
  7678. coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
  7679. around 1.0 will have moved symmetrically closer to 1.0).
  7680. \see scaleRange(double factor)
  7681. */
  7682. void QCPAxis::scaleRange(double factor, double center)
  7683. {
  7684. QCPRange oldRange = mRange;
  7685. if (mScaleType == stLinear)
  7686. {
  7687. QCPRange newRange;
  7688. newRange.lower = (mRange.lower-center)*factor + center;
  7689. newRange.upper = (mRange.upper-center)*factor + center;
  7690. if (QCPRange::validRange(newRange))
  7691. mRange = newRange.sanitizedForLinScale();
  7692. } else // mScaleType == stLogarithmic
  7693. {
  7694. if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range
  7695. {
  7696. QCPRange newRange;
  7697. newRange.lower = qPow(mRange.lower/center, factor)*center;
  7698. newRange.upper = qPow(mRange.upper/center, factor)*center;
  7699. if (QCPRange::validRange(newRange))
  7700. mRange = newRange.sanitizedForLogScale();
  7701. } else
  7702. qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center;
  7703. }
  7704. emit rangeChanged(mRange);
  7705. emit rangeChanged(mRange, oldRange);
  7706. }
  7707. /*!
  7708. Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will
  7709. be done around the center of the current axis range.
  7710. For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs
  7711. plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the
  7712. axis rect has.
  7713. This is an operation that changes the range of this axis once, it doesn't fix the scale ratio
  7714. indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent
  7715. won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent
  7716. will follow.
  7717. */
  7718. void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio)
  7719. {
  7720. int otherPixelSize, ownPixelSize;
  7721. if (otherAxis->orientation() == Qt::Horizontal)
  7722. otherPixelSize = otherAxis->axisRect()->width();
  7723. else
  7724. otherPixelSize = otherAxis->axisRect()->height();
  7725. if (orientation() == Qt::Horizontal)
  7726. ownPixelSize = axisRect()->width();
  7727. else
  7728. ownPixelSize = axisRect()->height();
  7729. double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/double(otherPixelSize);
  7730. setRange(range().center(), newRangeSize, Qt::AlignCenter);
  7731. }
  7732. /*!
  7733. Changes the axis range such that all plottables associated with this axis are fully visible in
  7734. that dimension.
  7735. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
  7736. */
  7737. void QCPAxis::rescale(bool onlyVisiblePlottables)
  7738. {
  7739. QCPRange newRange;
  7740. bool haveRange = false;
  7741. foreach (QCPAbstractPlottable *plottable, plottables())
  7742. {
  7743. if (!plottable->realVisibility() && onlyVisiblePlottables)
  7744. continue;
  7745. QCPRange plottableRange;
  7746. bool currentFoundRange;
  7747. QCP::SignDomain signDomain = QCP::sdBoth;
  7748. if (mScaleType == stLogarithmic)
  7749. signDomain = (mRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  7750. if (plottable->keyAxis() == this)
  7751. plottableRange = plottable->getKeyRange(currentFoundRange, signDomain);
  7752. else
  7753. plottableRange = plottable->getValueRange(currentFoundRange, signDomain);
  7754. if (currentFoundRange)
  7755. {
  7756. if (!haveRange)
  7757. newRange = plottableRange;
  7758. else
  7759. newRange.expand(plottableRange);
  7760. haveRange = true;
  7761. }
  7762. }
  7763. if (haveRange)
  7764. {
  7765. 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
  7766. {
  7767. 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
  7768. if (mScaleType == stLinear)
  7769. {
  7770. newRange.lower = center-mRange.size()/2.0;
  7771. newRange.upper = center+mRange.size()/2.0;
  7772. } else // mScaleType == stLogarithmic
  7773. {
  7774. newRange.lower = center/qSqrt(mRange.upper/mRange.lower);
  7775. newRange.upper = center*qSqrt(mRange.upper/mRange.lower);
  7776. }
  7777. }
  7778. setRange(newRange);
  7779. }
  7780. }
  7781. /*!
  7782. Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
  7783. */
  7784. double QCPAxis::pixelToCoord(double value) const
  7785. {
  7786. if (orientation() == Qt::Horizontal)
  7787. {
  7788. if (mScaleType == stLinear)
  7789. {
  7790. if (!mRangeReversed)
  7791. return (value-mAxisRect->left())/double(mAxisRect->width())*mRange.size()+mRange.lower;
  7792. else
  7793. return -(value-mAxisRect->left())/double(mAxisRect->width())*mRange.size()+mRange.upper;
  7794. } else // mScaleType == stLogarithmic
  7795. {
  7796. if (!mRangeReversed)
  7797. return qPow(mRange.upper/mRange.lower, (value-mAxisRect->left())/double(mAxisRect->width()))*mRange.lower;
  7798. else
  7799. return qPow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/double(mAxisRect->width()))*mRange.upper;
  7800. }
  7801. } else // orientation() == Qt::Vertical
  7802. {
  7803. if (mScaleType == stLinear)
  7804. {
  7805. if (!mRangeReversed)
  7806. return (mAxisRect->bottom()-value)/double(mAxisRect->height())*mRange.size()+mRange.lower;
  7807. else
  7808. return -(mAxisRect->bottom()-value)/double(mAxisRect->height())*mRange.size()+mRange.upper;
  7809. } else // mScaleType == stLogarithmic
  7810. {
  7811. if (!mRangeReversed)
  7812. return qPow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/double(mAxisRect->height()))*mRange.lower;
  7813. else
  7814. return qPow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/double(mAxisRect->height()))*mRange.upper;
  7815. }
  7816. }
  7817. }
  7818. /*!
  7819. Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
  7820. */
  7821. double QCPAxis::coordToPixel(double value) const
  7822. {
  7823. if (orientation() == Qt::Horizontal)
  7824. {
  7825. if (mScaleType == stLinear)
  7826. {
  7827. if (!mRangeReversed)
  7828. return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left();
  7829. else
  7830. return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left();
  7831. } else // mScaleType == stLogarithmic
  7832. {
  7833. if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7834. return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200;
  7835. else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7836. return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200;
  7837. else
  7838. {
  7839. if (!mRangeReversed)
  7840. return qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
  7841. else
  7842. return qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
  7843. }
  7844. }
  7845. } else // orientation() == Qt::Vertical
  7846. {
  7847. if (mScaleType == stLinear)
  7848. {
  7849. if (!mRangeReversed)
  7850. return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height();
  7851. else
  7852. return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height();
  7853. } else // mScaleType == stLogarithmic
  7854. {
  7855. if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7856. return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200;
  7857. else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7858. return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200;
  7859. else
  7860. {
  7861. if (!mRangeReversed)
  7862. return mAxisRect->bottom()-qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->height();
  7863. else
  7864. return mAxisRect->bottom()-qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->height();
  7865. }
  7866. }
  7867. }
  7868. }
  7869. /*!
  7870. Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
  7871. is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
  7872. function does not change the current selection state of the axis.
  7873. If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
  7874. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
  7875. */
  7876. QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const
  7877. {
  7878. if (!mVisible)
  7879. return spNone;
  7880. if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
  7881. return spAxis;
  7882. else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
  7883. return spTickLabels;
  7884. else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
  7885. return spAxisLabel;
  7886. else
  7887. return spNone;
  7888. }
  7889. /* inherits documentation from base class */
  7890. double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  7891. {
  7892. if (!mParentPlot) return -1;
  7893. SelectablePart part = getPartAt(pos);
  7894. if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
  7895. return -1;
  7896. if (details)
  7897. details->setValue(part);
  7898. return mParentPlot->selectionTolerance()*0.99;
  7899. }
  7900. /*!
  7901. Returns a list of all the plottables that have this axis as key or value axis.
  7902. If you are only interested in plottables of type QCPGraph, see \ref graphs.
  7903. \see graphs, items
  7904. */
  7905. QList<QCPAbstractPlottable*> QCPAxis::plottables() const
  7906. {
  7907. QList<QCPAbstractPlottable*> result;
  7908. if (!mParentPlot) return result;
  7909. foreach (QCPAbstractPlottable *plottable, mParentPlot->mPlottables)
  7910. {
  7911. if (plottable->keyAxis() == this || plottable->valueAxis() == this)
  7912. result.append(plottable);
  7913. }
  7914. return result;
  7915. }
  7916. /*!
  7917. Returns a list of all the graphs that have this axis as key or value axis.
  7918. \see plottables, items
  7919. */
  7920. QList<QCPGraph*> QCPAxis::graphs() const
  7921. {
  7922. QList<QCPGraph*> result;
  7923. if (!mParentPlot) return result;
  7924. foreach (QCPGraph *graph, mParentPlot->mGraphs)
  7925. {
  7926. if (graph->keyAxis() == this || graph->valueAxis() == this)
  7927. result.append(graph);
  7928. }
  7929. return result;
  7930. }
  7931. /*!
  7932. Returns a list of all the items that are associated with this axis. An item is considered
  7933. associated with an axis if at least one of its positions uses the axis as key or value axis.
  7934. \see plottables, graphs
  7935. */
  7936. QList<QCPAbstractItem*> QCPAxis::items() const
  7937. {
  7938. QList<QCPAbstractItem*> result;
  7939. if (!mParentPlot) return result;
  7940. foreach (QCPAbstractItem *item, mParentPlot->mItems)
  7941. {
  7942. foreach (QCPItemPosition *position, item->positions())
  7943. {
  7944. if (position->keyAxis() == this || position->valueAxis() == this)
  7945. {
  7946. result.append(item);
  7947. break;
  7948. }
  7949. }
  7950. }
  7951. return result;
  7952. }
  7953. /*!
  7954. Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to
  7955. QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.)
  7956. */
  7957. QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side)
  7958. {
  7959. switch (side)
  7960. {
  7961. case QCP::msLeft: return atLeft;
  7962. case QCP::msRight: return atRight;
  7963. case QCP::msTop: return atTop;
  7964. case QCP::msBottom: return atBottom;
  7965. default: break;
  7966. }
  7967. qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << static_cast<int>(side);
  7968. return atLeft;
  7969. }
  7970. /*!
  7971. Returns the axis type that describes the opposite axis of an axis with the specified \a type.
  7972. */
  7973. QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type)
  7974. {
  7975. switch (type)
  7976. {
  7977. case atLeft: return atRight;
  7978. case atRight: return atLeft;
  7979. case atBottom: return atTop;
  7980. case atTop: return atBottom;
  7981. }
  7982. qDebug() << Q_FUNC_INFO << "invalid axis type";
  7983. return atLeft;
  7984. }
  7985. /* inherits documentation from base class */
  7986. void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  7987. {
  7988. Q_UNUSED(event)
  7989. SelectablePart part = details.value<SelectablePart>();
  7990. if (mSelectableParts.testFlag(part))
  7991. {
  7992. SelectableParts selBefore = mSelectedParts;
  7993. setSelectedParts(additive ? mSelectedParts^part : part);
  7994. if (selectionStateChanged)
  7995. *selectionStateChanged = mSelectedParts != selBefore;
  7996. }
  7997. }
  7998. /* inherits documentation from base class */
  7999. void QCPAxis::deselectEvent(bool *selectionStateChanged)
  8000. {
  8001. SelectableParts selBefore = mSelectedParts;
  8002. setSelectedParts(mSelectedParts & ~mSelectableParts);
  8003. if (selectionStateChanged)
  8004. *selectionStateChanged = mSelectedParts != selBefore;
  8005. }
  8006. /*! \internal
  8007. This mouse event reimplementation provides the functionality to let the user drag individual axes
  8008. exclusively, by startig the drag on top of the axis.
  8009. For the axis to accept this event and perform the single axis drag, the parent \ref QCPAxisRect
  8010. must be configured accordingly, i.e. it must allow range dragging in the orientation of this axis
  8011. (\ref QCPAxisRect::setRangeDrag) and this axis must be a draggable axis (\ref
  8012. QCPAxisRect::setRangeDragAxes)
  8013. \seebaseclassmethod
  8014. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  8015. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  8016. */
  8017. void QCPAxis::mousePressEvent(QMouseEvent *event, const QVariant &details)
  8018. {
  8019. Q_UNUSED(details)
  8020. if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag) ||
  8021. !mAxisRect->rangeDrag().testFlag(orientation()) ||
  8022. !mAxisRect->rangeDragAxes(orientation()).contains(this))
  8023. {
  8024. event->ignore();
  8025. return;
  8026. }
  8027. if (event->buttons() & Qt::LeftButton)
  8028. {
  8029. mDragging = true;
  8030. // initialize antialiasing backup in case we start dragging:
  8031. if (mParentPlot->noAntialiasingOnDrag())
  8032. {
  8033. mAADragBackup = mParentPlot->antialiasedElements();
  8034. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  8035. }
  8036. // Mouse range dragging interaction:
  8037. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  8038. mDragStartRange = mRange;
  8039. }
  8040. }
  8041. /*! \internal
  8042. This mouse event reimplementation provides the functionality to let the user drag individual axes
  8043. exclusively, by startig the drag on top of the axis.
  8044. \seebaseclassmethod
  8045. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  8046. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  8047. \see QCPAxis::mousePressEvent
  8048. */
  8049. void QCPAxis::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  8050. {
  8051. if (mDragging)
  8052. {
  8053. const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y();
  8054. const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y();
  8055. if (mScaleType == QCPAxis::stLinear)
  8056. {
  8057. const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel);
  8058. setRange(mDragStartRange.lower+diff, mDragStartRange.upper+diff);
  8059. } else if (mScaleType == QCPAxis::stLogarithmic)
  8060. {
  8061. const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel);
  8062. setRange(mDragStartRange.lower*diff, mDragStartRange.upper*diff);
  8063. }
  8064. if (mParentPlot->noAntialiasingOnDrag())
  8065. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  8066. mParentPlot->replot(QCustomPlot::rpQueuedReplot);
  8067. }
  8068. }
  8069. /*! \internal
  8070. This mouse event reimplementation provides the functionality to let the user drag individual axes
  8071. exclusively, by startig the drag on top of the axis.
  8072. \seebaseclassmethod
  8073. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  8074. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  8075. \see QCPAxis::mousePressEvent
  8076. */
  8077. void QCPAxis::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  8078. {
  8079. Q_UNUSED(event)
  8080. Q_UNUSED(startPos)
  8081. mDragging = false;
  8082. if (mParentPlot->noAntialiasingOnDrag())
  8083. {
  8084. mParentPlot->setAntialiasedElements(mAADragBackup);
  8085. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  8086. }
  8087. }
  8088. /*! \internal
  8089. This mouse event reimplementation provides the functionality to let the user zoom individual axes
  8090. exclusively, by performing the wheel event on top of the axis.
  8091. For the axis to accept this event and perform the single axis zoom, the parent \ref QCPAxisRect
  8092. must be configured accordingly, i.e. it must allow range zooming in the orientation of this axis
  8093. (\ref QCPAxisRect::setRangeZoom) and this axis must be a zoomable axis (\ref
  8094. QCPAxisRect::setRangeZoomAxes)
  8095. \seebaseclassmethod
  8096. \note The zooming of possibly multiple axes at once by performing the wheel event anywhere in the
  8097. axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::wheelEvent.
  8098. */
  8099. void QCPAxis::wheelEvent(QWheelEvent *event)
  8100. {
  8101. // Mouse range zooming interaction:
  8102. if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom) ||
  8103. !mAxisRect->rangeZoom().testFlag(orientation()) ||
  8104. !mAxisRect->rangeZoomAxes(orientation()).contains(this))
  8105. {
  8106. event->ignore();
  8107. return;
  8108. }
  8109. #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  8110. const double delta = event->delta();
  8111. #else
  8112. const double delta = event->angleDelta().y();
  8113. #endif
  8114. #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  8115. const QPointF pos = event->pos();
  8116. #else
  8117. const QPointF pos = event->position();
  8118. #endif
  8119. const double wheelSteps = delta/120.0; // a single step delta is +/-120 usually
  8120. const double factor = qPow(mAxisRect->rangeZoomFactor(orientation()), wheelSteps);
  8121. scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? pos.x() : pos.y()));
  8122. mParentPlot->replot();
  8123. }
  8124. /*! \internal
  8125. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  8126. before drawing axis lines.
  8127. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  8128. This function takes into account the local setting of the antialiasing flag as well as the
  8129. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  8130. QCustomPlot::setNotAntialiasedElements.
  8131. \seebaseclassmethod
  8132. \see setAntialiased
  8133. */
  8134. void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const
  8135. {
  8136. applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
  8137. }
  8138. /*! \internal
  8139. Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance.
  8140. \seebaseclassmethod
  8141. */
  8142. void QCPAxis::draw(QCPPainter *painter)
  8143. {
  8144. QVector<double> subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  8145. QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  8146. QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
  8147. tickPositions.reserve(mTickVector.size());
  8148. tickLabels.reserve(mTickVector.size());
  8149. subTickPositions.reserve(mSubTickVector.size());
  8150. if (mTicks)
  8151. {
  8152. for (int i=0; i<mTickVector.size(); ++i)
  8153. {
  8154. tickPositions.append(coordToPixel(mTickVector.at(i)));
  8155. if (mTickLabels)
  8156. tickLabels.append(mTickVectorLabels.at(i));
  8157. }
  8158. if (mSubTicks)
  8159. {
  8160. const int subTickCount = mSubTickVector.size();
  8161. for (int i=0; i<subTickCount; ++i)
  8162. subTickPositions.append(coordToPixel(mSubTickVector.at(i)));
  8163. }
  8164. }
  8165. // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to draw the axis.
  8166. // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
  8167. mAxisPainter->type = mAxisType;
  8168. mAxisPainter->basePen = getBasePen();
  8169. mAxisPainter->labelFont = getLabelFont();
  8170. mAxisPainter->labelColor = getLabelColor();
  8171. mAxisPainter->label = mLabel;
  8172. mAxisPainter->substituteExponent = mNumberBeautifulPowers;
  8173. mAxisPainter->tickPen = getTickPen();
  8174. mAxisPainter->subTickPen = getSubTickPen();
  8175. mAxisPainter->tickLabelFont = getTickLabelFont();
  8176. mAxisPainter->tickLabelColor = getTickLabelColor();
  8177. mAxisPainter->axisRect = mAxisRect->rect();
  8178. mAxisPainter->viewportRect = mParentPlot->viewport();
  8179. mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic;
  8180. mAxisPainter->reversedEndings = mRangeReversed;
  8181. mAxisPainter->tickPositions = tickPositions;
  8182. mAxisPainter->tickLabels = tickLabels;
  8183. mAxisPainter->subTickPositions = subTickPositions;
  8184. mAxisPainter->draw(painter);
  8185. }
  8186. /*! \internal
  8187. Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
  8188. QCPAxisTicker::generate on the currently installed ticker.
  8189. If a change in the label text/count is detected, the cached axis margin is invalidated to make
  8190. sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
  8191. */
  8192. void QCPAxis::setupTickVectors()
  8193. {
  8194. if (!mParentPlot) return;
  8195. if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
  8196. QVector<QString> oldLabels = mTickVectorLabels;
  8197. mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : nullptr, mTickLabels ? &mTickVectorLabels : nullptr);
  8198. mCachedMarginValid &= mTickVectorLabels == oldLabels; // if labels have changed, margin might have changed, too
  8199. }
  8200. /*! \internal
  8201. Returns the pen that is used to draw the axis base line. Depending on the selection state, this
  8202. is either mSelectedBasePen or mBasePen.
  8203. */
  8204. QPen QCPAxis::getBasePen() const
  8205. {
  8206. return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
  8207. }
  8208. /*! \internal
  8209. Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
  8210. is either mSelectedTickPen or mTickPen.
  8211. */
  8212. QPen QCPAxis::getTickPen() const
  8213. {
  8214. return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
  8215. }
  8216. /*! \internal
  8217. Returns the pen that is used to draw the subticks. Depending on the selection state, this
  8218. is either mSelectedSubTickPen or mSubTickPen.
  8219. */
  8220. QPen QCPAxis::getSubTickPen() const
  8221. {
  8222. return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
  8223. }
  8224. /*! \internal
  8225. Returns the font that is used to draw the tick labels. Depending on the selection state, this
  8226. is either mSelectedTickLabelFont or mTickLabelFont.
  8227. */
  8228. QFont QCPAxis::getTickLabelFont() const
  8229. {
  8230. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
  8231. }
  8232. /*! \internal
  8233. Returns the font that is used to draw the axis label. Depending on the selection state, this
  8234. is either mSelectedLabelFont or mLabelFont.
  8235. */
  8236. QFont QCPAxis::getLabelFont() const
  8237. {
  8238. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
  8239. }
  8240. /*! \internal
  8241. Returns the color that is used to draw the tick labels. Depending on the selection state, this
  8242. is either mSelectedTickLabelColor or mTickLabelColor.
  8243. */
  8244. QColor QCPAxis::getTickLabelColor() const
  8245. {
  8246. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
  8247. }
  8248. /*! \internal
  8249. Returns the color that is used to draw the axis label. Depending on the selection state, this
  8250. is either mSelectedLabelColor or mLabelColor.
  8251. */
  8252. QColor QCPAxis::getLabelColor() const
  8253. {
  8254. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
  8255. }
  8256. /*! \internal
  8257. Returns the appropriate outward margin for this axis. It is needed if \ref
  8258. QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref
  8259. atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom
  8260. margin and so forth. For the calculation, this function goes through similar steps as \ref draw,
  8261. so changing one function likely requires the modification of the other one as well.
  8262. The margin consists of the outward tick length, tick label padding, tick label size, label
  8263. padding, label size, and padding.
  8264. The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc.
  8265. unchanged are very fast.
  8266. */
  8267. int QCPAxis::calculateMargin()
  8268. {
  8269. if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis
  8270. return 0;
  8271. if (mCachedMarginValid)
  8272. return mCachedMargin;
  8273. // run through similar steps as QCPAxis::draw, and calculate margin needed to fit axis and its labels
  8274. int margin = 0;
  8275. QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  8276. QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
  8277. tickPositions.reserve(mTickVector.size());
  8278. tickLabels.reserve(mTickVector.size());
  8279. if (mTicks)
  8280. {
  8281. for (int i=0; i<mTickVector.size(); ++i)
  8282. {
  8283. tickPositions.append(coordToPixel(mTickVector.at(i)));
  8284. if (mTickLabels)
  8285. tickLabels.append(mTickVectorLabels.at(i));
  8286. }
  8287. }
  8288. // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size.
  8289. // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
  8290. mAxisPainter->type = mAxisType;
  8291. mAxisPainter->labelFont = getLabelFont();
  8292. mAxisPainter->label = mLabel;
  8293. mAxisPainter->tickLabelFont = mTickLabelFont;
  8294. mAxisPainter->axisRect = mAxisRect->rect();
  8295. mAxisPainter->viewportRect = mParentPlot->viewport();
  8296. mAxisPainter->tickPositions = tickPositions;
  8297. mAxisPainter->tickLabels = tickLabels;
  8298. margin += mAxisPainter->size();
  8299. margin += mPadding;
  8300. mCachedMargin = margin;
  8301. mCachedMarginValid = true;
  8302. return margin;
  8303. }
  8304. /* inherits documentation from base class */
  8305. QCP::Interaction QCPAxis::selectionCategory() const
  8306. {
  8307. return QCP::iSelectAxes;
  8308. }
  8309. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8310. //////////////////// QCPAxisPainterPrivate
  8311. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8312. /*! \class QCPAxisPainterPrivate
  8313. \internal
  8314. \brief (Private)
  8315. This is a private class and not part of the public QCustomPlot interface.
  8316. It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and
  8317. axis label. It also buffers the labels to reduce replot times. The parameters are configured by
  8318. directly accessing the public member variables.
  8319. */
  8320. /*!
  8321. Constructs a QCPAxisPainterPrivate instance. Make sure to not create a new instance on every
  8322. redraw, to utilize the caching mechanisms.
  8323. */
  8324. QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) :
  8325. type(QCPAxis::atLeft),
  8326. basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  8327. lowerEnding(QCPLineEnding::esNone),
  8328. upperEnding(QCPLineEnding::esNone),
  8329. labelPadding(0),
  8330. tickLabelPadding(0),
  8331. tickLabelRotation(0),
  8332. tickLabelSide(QCPAxis::lsOutside),
  8333. substituteExponent(true),
  8334. numberMultiplyCross(false),
  8335. tickLengthIn(5),
  8336. tickLengthOut(0),
  8337. subTickLengthIn(2),
  8338. subTickLengthOut(0),
  8339. tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  8340. subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  8341. offset(0),
  8342. abbreviateDecimalPowers(false),
  8343. reversedEndings(false),
  8344. mParentPlot(parentPlot),
  8345. mLabelCache(16) // cache at most 16 (tick) labels
  8346. {
  8347. }
  8348. QCPAxisPainterPrivate::~QCPAxisPainterPrivate()
  8349. {
  8350. }
  8351. /*! \internal
  8352. Draws the axis with the specified \a painter.
  8353. The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set
  8354. here, too.
  8355. */
  8356. void QCPAxisPainterPrivate::draw(QCPPainter *painter)
  8357. {
  8358. QByteArray newHash = generateLabelParameterHash();
  8359. if (newHash != mLabelParameterHash)
  8360. {
  8361. mLabelCache.clear();
  8362. mLabelParameterHash = newHash;
  8363. }
  8364. QPoint origin;
  8365. switch (type)
  8366. {
  8367. case QCPAxis::atLeft: origin = axisRect.bottomLeft() +QPoint(-offset, 0); break;
  8368. case QCPAxis::atRight: origin = axisRect.bottomRight()+QPoint(+offset, 0); break;
  8369. case QCPAxis::atTop: origin = axisRect.topLeft() +QPoint(0, -offset); break;
  8370. case QCPAxis::atBottom: origin = axisRect.bottomLeft() +QPoint(0, +offset); break;
  8371. }
  8372. double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes)
  8373. switch (type)
  8374. {
  8375. case QCPAxis::atTop: yCor = -1; break;
  8376. case QCPAxis::atRight: xCor = 1; break;
  8377. default: break;
  8378. }
  8379. int margin = 0;
  8380. // draw baseline:
  8381. QLineF baseLine;
  8382. painter->setPen(basePen);
  8383. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8384. baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(axisRect.width()+xCor, yCor));
  8385. else
  8386. baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -axisRect.height()+yCor));
  8387. if (reversedEndings)
  8388. baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later
  8389. painter->drawLine(baseLine);
  8390. // draw ticks:
  8391. if (!tickPositions.isEmpty())
  8392. {
  8393. painter->setPen(tickPen);
  8394. int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis)
  8395. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8396. {
  8397. foreach (double tickPos, tickPositions)
  8398. painter->drawLine(QLineF(tickPos+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPos+xCor, origin.y()+tickLengthIn*tickDir+yCor));
  8399. } else
  8400. {
  8401. foreach (double tickPos, tickPositions)
  8402. painter->drawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPos+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPos+yCor));
  8403. }
  8404. }
  8405. // draw subticks:
  8406. if (!subTickPositions.isEmpty())
  8407. {
  8408. painter->setPen(subTickPen);
  8409. // direction of ticks ("inward" is right for left axis and left for right axis)
  8410. int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1;
  8411. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8412. {
  8413. foreach (double subTickPos, subTickPositions)
  8414. painter->drawLine(QLineF(subTickPos+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPos+xCor, origin.y()+subTickLengthIn*tickDir+yCor));
  8415. } else
  8416. {
  8417. foreach (double subTickPos, subTickPositions)
  8418. painter->drawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPos+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPos+yCor));
  8419. }
  8420. }
  8421. margin += qMax(0, qMax(tickLengthOut, subTickLengthOut));
  8422. // draw axis base endings:
  8423. bool antialiasingBackup = painter->antialiasing();
  8424. painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't
  8425. painter->setBrush(QBrush(basePen.color()));
  8426. QCPVector2D baseLineVector(baseLine.dx(), baseLine.dy());
  8427. if (lowerEnding.style() != QCPLineEnding::esNone)
  8428. lowerEnding.draw(painter, QCPVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector);
  8429. if (upperEnding.style() != QCPLineEnding::esNone)
  8430. upperEnding.draw(painter, QCPVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector);
  8431. painter->setAntialiasing(antialiasingBackup);
  8432. // tick labels:
  8433. QRect oldClipRect;
  8434. if (tickLabelSide == QCPAxis::lsInside) // if using inside labels, clip them to the axis rect
  8435. {
  8436. oldClipRect = painter->clipRegion().boundingRect();
  8437. painter->setClipRect(axisRect);
  8438. }
  8439. QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label
  8440. if (!tickLabels.isEmpty())
  8441. {
  8442. if (tickLabelSide == QCPAxis::lsOutside)
  8443. margin += tickLabelPadding;
  8444. painter->setFont(tickLabelFont);
  8445. painter->setPen(QPen(tickLabelColor));
  8446. const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size());
  8447. int distanceToAxis = margin;
  8448. if (tickLabelSide == QCPAxis::lsInside)
  8449. distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding);
  8450. for (int i=0; i<maxLabelIndex; ++i)
  8451. placeTickLabel(painter, tickPositions.at(i), distanceToAxis, tickLabels.at(i), &tickLabelsSize);
  8452. if (tickLabelSide == QCPAxis::lsOutside)
  8453. margin += (QCPAxis::orientation(type) == Qt::Horizontal) ? tickLabelsSize.height() : tickLabelsSize.width();
  8454. }
  8455. if (tickLabelSide == QCPAxis::lsInside)
  8456. painter->setClipRect(oldClipRect);
  8457. // axis label:
  8458. QRect labelBounds;
  8459. if (!label.isEmpty())
  8460. {
  8461. margin += labelPadding;
  8462. painter->setFont(labelFont);
  8463. painter->setPen(QPen(labelColor));
  8464. labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label);
  8465. if (type == QCPAxis::atLeft)
  8466. {
  8467. QTransform oldTransform = painter->transform();
  8468. painter->translate((origin.x()-margin-labelBounds.height()), origin.y());
  8469. painter->rotate(-90);
  8470. painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  8471. painter->setTransform(oldTransform);
  8472. }
  8473. else if (type == QCPAxis::atRight)
  8474. {
  8475. QTransform oldTransform = painter->transform();
  8476. painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-axisRect.height());
  8477. painter->rotate(90);
  8478. painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  8479. painter->setTransform(oldTransform);
  8480. }
  8481. else if (type == QCPAxis::atTop)
  8482. painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  8483. else if (type == QCPAxis::atBottom)
  8484. painter->drawText(origin.x(), origin.y()+margin, axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  8485. }
  8486. // set selection boxes:
  8487. int selectionTolerance = 0;
  8488. if (mParentPlot)
  8489. selectionTolerance = mParentPlot->selectionTolerance();
  8490. else
  8491. qDebug() << Q_FUNC_INFO << "mParentPlot is null";
  8492. int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance);
  8493. int selAxisInSize = selectionTolerance;
  8494. int selTickLabelSize;
  8495. int selTickLabelOffset;
  8496. if (tickLabelSide == QCPAxis::lsOutside)
  8497. {
  8498. selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
  8499. selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding;
  8500. } else
  8501. {
  8502. selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
  8503. selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding);
  8504. }
  8505. int selLabelSize = labelBounds.height();
  8506. int selLabelOffset = qMax(tickLengthOut, subTickLengthOut)+(!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside ? tickLabelPadding+selTickLabelSize : 0)+labelPadding;
  8507. if (type == QCPAxis::atLeft)
  8508. {
  8509. mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, axisRect.top(), origin.x()+selAxisInSize, axisRect.bottom());
  8510. mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, axisRect.top(), origin.x()-selTickLabelOffset, axisRect.bottom());
  8511. mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, axisRect.top(), origin.x()-selLabelOffset, axisRect.bottom());
  8512. } else if (type == QCPAxis::atRight)
  8513. {
  8514. mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, axisRect.top(), origin.x()+selAxisOutSize, axisRect.bottom());
  8515. mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, axisRect.top(), origin.x()+selTickLabelOffset, axisRect.bottom());
  8516. mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, axisRect.top(), origin.x()+selLabelOffset, axisRect.bottom());
  8517. } else if (type == QCPAxis::atTop)
  8518. {
  8519. mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisOutSize, axisRect.right(), origin.y()+selAxisInSize);
  8520. mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, axisRect.right(), origin.y()-selTickLabelOffset);
  8521. mLabelSelectionBox.setCoords(axisRect.left(), origin.y()-selLabelOffset-selLabelSize, axisRect.right(), origin.y()-selLabelOffset);
  8522. } else if (type == QCPAxis::atBottom)
  8523. {
  8524. mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisInSize, axisRect.right(), origin.y()+selAxisOutSize);
  8525. mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, axisRect.right(), origin.y()+selTickLabelOffset);
  8526. mLabelSelectionBox.setCoords(axisRect.left(), origin.y()+selLabelOffset+selLabelSize, axisRect.right(), origin.y()+selLabelOffset);
  8527. }
  8528. mAxisSelectionBox = mAxisSelectionBox.normalized();
  8529. mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized();
  8530. mLabelSelectionBox = mLabelSelectionBox.normalized();
  8531. // draw hitboxes for debug purposes:
  8532. //painter->setBrush(Qt::NoBrush);
  8533. //painter->drawRects(QVector<QRect>() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox);
  8534. }
  8535. /*! \internal
  8536. Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone
  8537. direction) needed to fit the axis.
  8538. */
  8539. int QCPAxisPainterPrivate::size()
  8540. {
  8541. int result = 0;
  8542. QByteArray newHash = generateLabelParameterHash();
  8543. if (newHash != mLabelParameterHash)
  8544. {
  8545. mLabelCache.clear();
  8546. mLabelParameterHash = newHash;
  8547. }
  8548. // get length of tick marks pointing outwards:
  8549. if (!tickPositions.isEmpty())
  8550. result += qMax(0, qMax(tickLengthOut, subTickLengthOut));
  8551. // calculate size of tick labels:
  8552. if (tickLabelSide == QCPAxis::lsOutside)
  8553. {
  8554. QSize tickLabelsSize(0, 0);
  8555. if (!tickLabels.isEmpty())
  8556. {
  8557. foreach (const QString &tickLabel, tickLabels)
  8558. getMaxTickLabelSize(tickLabelFont, tickLabel, &tickLabelsSize);
  8559. result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width();
  8560. result += tickLabelPadding;
  8561. }
  8562. }
  8563. // calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees):
  8564. if (!label.isEmpty())
  8565. {
  8566. QFontMetrics fontMetrics(labelFont);
  8567. QRect bounds;
  8568. bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label);
  8569. result += bounds.height() + labelPadding;
  8570. }
  8571. return result;
  8572. }
  8573. /*! \internal
  8574. Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This
  8575. method is called automatically in \ref draw, if any parameters have changed that invalidate the
  8576. cached labels, such as font, color, etc.
  8577. */
  8578. void QCPAxisPainterPrivate::clearCache()
  8579. {
  8580. mLabelCache.clear();
  8581. }
  8582. /*! \internal
  8583. Returns a hash that allows uniquely identifying whether the label parameters have changed such
  8584. that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the
  8585. return value of this method hasn't changed since the last redraw, the respective label parameters
  8586. haven't changed and cached labels may be used.
  8587. */
  8588. QByteArray QCPAxisPainterPrivate::generateLabelParameterHash() const
  8589. {
  8590. QByteArray result;
  8591. result.append(QByteArray::number(mParentPlot->bufferDevicePixelRatio()));
  8592. result.append(QByteArray::number(tickLabelRotation));
  8593. result.append(QByteArray::number(int(tickLabelSide)));
  8594. result.append(QByteArray::number(int(substituteExponent)));
  8595. result.append(QByteArray::number(int(numberMultiplyCross)));
  8596. result.append(tickLabelColor.name().toLatin1()+QByteArray::number(tickLabelColor.alpha(), 16));
  8597. result.append(tickLabelFont.toString().toLatin1());
  8598. return result;
  8599. }
  8600. /*! \internal
  8601. Draws a single tick label with the provided \a painter, utilizing the internal label cache to
  8602. significantly speed up drawing of labels that were drawn in previous calls. The tick label is
  8603. always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in
  8604. pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence
  8605. for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate),
  8606. at which the label should be drawn.
  8607. In order to later draw the axis label in a place that doesn't overlap with the tick labels, the
  8608. largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref
  8609. drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a
  8610. tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently
  8611. holds.
  8612. The label is drawn with the font and pen that are currently set on the \a painter. To draw
  8613. superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref
  8614. getTickLabelData).
  8615. */
  8616. void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize)
  8617. {
  8618. // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly!
  8619. if (text.isEmpty()) return;
  8620. QSize finalSize;
  8621. QPointF labelAnchor;
  8622. switch (type)
  8623. {
  8624. case QCPAxis::atLeft: labelAnchor = QPointF(axisRect.left()-distanceToAxis-offset, position); break;
  8625. case QCPAxis::atRight: labelAnchor = QPointF(axisRect.right()+distanceToAxis+offset, position); break;
  8626. case QCPAxis::atTop: labelAnchor = QPointF(position, axisRect.top()-distanceToAxis-offset); break;
  8627. case QCPAxis::atBottom: labelAnchor = QPointF(position, axisRect.bottom()+distanceToAxis+offset); break;
  8628. }
  8629. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled
  8630. {
  8631. CachedLabel *cachedLabel = mLabelCache.take(text); // attempt to get label from cache
  8632. if (!cachedLabel) // no cached label existed, create it
  8633. {
  8634. cachedLabel = new CachedLabel;
  8635. TickLabelData labelData = getTickLabelData(painter->font(), text);
  8636. cachedLabel->offset = getTickLabelDrawOffset(labelData)+labelData.rotatedTotalBounds.topLeft();
  8637. if (!qFuzzyCompare(1.0, mParentPlot->bufferDevicePixelRatio()))
  8638. {
  8639. cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()*mParentPlot->bufferDevicePixelRatio());
  8640. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  8641. # ifdef QCP_DEVICEPIXELRATIO_FLOAT
  8642. cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF());
  8643. # else
  8644. cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio());
  8645. # endif
  8646. #endif
  8647. } else
  8648. cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
  8649. cachedLabel->pixmap.fill(Qt::transparent);
  8650. QCPPainter cachePainter(&cachedLabel->pixmap);
  8651. cachePainter.setPen(painter->pen());
  8652. drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData);
  8653. }
  8654. // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
  8655. bool labelClippedByBorder = false;
  8656. if (tickLabelSide == QCPAxis::lsOutside)
  8657. {
  8658. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8659. labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width()/mParentPlot->bufferDevicePixelRatio() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left();
  8660. else
  8661. labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height()/mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top();
  8662. }
  8663. if (!labelClippedByBorder)
  8664. {
  8665. painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap);
  8666. finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
  8667. }
  8668. mLabelCache.insert(text, cachedLabel); // return label to cache or insert for the first time if newly created
  8669. } else // label caching disabled, draw text directly on surface:
  8670. {
  8671. TickLabelData labelData = getTickLabelData(painter->font(), text);
  8672. QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData);
  8673. // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
  8674. bool labelClippedByBorder = false;
  8675. if (tickLabelSide == QCPAxis::lsOutside)
  8676. {
  8677. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8678. labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left();
  8679. else
  8680. labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top();
  8681. }
  8682. if (!labelClippedByBorder)
  8683. {
  8684. drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData);
  8685. finalSize = labelData.rotatedTotalBounds.size();
  8686. }
  8687. }
  8688. // expand passed tickLabelsSize if current tick label is larger:
  8689. if (finalSize.width() > tickLabelsSize->width())
  8690. tickLabelsSize->setWidth(finalSize.width());
  8691. if (finalSize.height() > tickLabelsSize->height())
  8692. tickLabelsSize->setHeight(finalSize.height());
  8693. }
  8694. /*! \internal
  8695. This is a \ref placeTickLabel helper function.
  8696. Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a
  8697. y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to
  8698. directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when
  8699. QCP::phCacheLabels plotting hint is not set.
  8700. */
  8701. void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const
  8702. {
  8703. // backup painter settings that we're about to change:
  8704. QTransform oldTransform = painter->transform();
  8705. QFont oldFont = painter->font();
  8706. // transform painter to position/rotation:
  8707. painter->translate(x, y);
  8708. if (!qFuzzyIsNull(tickLabelRotation))
  8709. painter->rotate(tickLabelRotation);
  8710. // draw text:
  8711. if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used
  8712. {
  8713. painter->setFont(labelData.baseFont);
  8714. painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart);
  8715. if (!labelData.suffixPart.isEmpty())
  8716. painter->drawText(labelData.baseBounds.width()+1+labelData.expBounds.width(), 0, 0, 0, Qt::TextDontClip, labelData.suffixPart);
  8717. painter->setFont(labelData.expFont);
  8718. painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart);
  8719. } else
  8720. {
  8721. painter->setFont(labelData.baseFont);
  8722. painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart);
  8723. }
  8724. // reset painter settings to what it was before:
  8725. painter->setTransform(oldTransform);
  8726. painter->setFont(oldFont);
  8727. }
  8728. /*! \internal
  8729. This is a \ref placeTickLabel helper function.
  8730. Transforms the passed \a text and \a font to a tickLabelData structure that can then be further
  8731. processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and
  8732. exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes.
  8733. */
  8734. QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const
  8735. {
  8736. TickLabelData result;
  8737. // determine whether beautiful decimal powers should be used
  8738. bool useBeautifulPowers = false;
  8739. int ePos = -1; // first index of exponent part, text before that will be basePart, text until eLast will be expPart
  8740. int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart
  8741. if (substituteExponent)
  8742. {
  8743. ePos = text.indexOf(QString(mParentPlot->locale().exponential()));
  8744. if (ePos > 0 && text.at(ePos-1).isDigit())
  8745. {
  8746. eLast = ePos;
  8747. while (eLast+1 < text.size() && (text.at(eLast+1) == QLatin1Char('+') || text.at(eLast+1) == QLatin1Char('-') || text.at(eLast+1).isDigit()))
  8748. ++eLast;
  8749. if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as beautifiable power
  8750. useBeautifulPowers = true;
  8751. }
  8752. }
  8753. // calculate text bounding rects and do string preparation for beautiful decimal powers:
  8754. result.baseFont = font;
  8755. if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line
  8756. 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
  8757. if (useBeautifulPowers)
  8758. {
  8759. // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent:
  8760. result.basePart = text.left(ePos);
  8761. result.suffixPart = text.mid(eLast+1); // also drawn normally but after exponent
  8762. // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base:
  8763. if (abbreviateDecimalPowers && result.basePart == QLatin1String("1"))
  8764. result.basePart = QLatin1String("10");
  8765. else
  8766. result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + QLatin1String("10");
  8767. result.expPart = text.mid(ePos+1, eLast-ePos);
  8768. // clip "+" and leading zeros off expPart:
  8769. while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e'
  8770. result.expPart.remove(1, 1);
  8771. if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+'))
  8772. result.expPart.remove(0, 1);
  8773. // prepare smaller font for exponent:
  8774. result.expFont = font;
  8775. if (result.expFont.pointSize() > 0)
  8776. result.expFont.setPointSize(int(result.expFont.pointSize()*0.75));
  8777. else
  8778. result.expFont.setPixelSize(int(result.expFont.pixelSize()*0.75));
  8779. // calculate bounding rects of base part(s), exponent part and total one:
  8780. result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart);
  8781. result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart);
  8782. if (!result.suffixPart.isEmpty())
  8783. result.suffixBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.suffixPart);
  8784. 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
  8785. } else // useBeautifulPowers == false
  8786. {
  8787. result.basePart = text;
  8788. result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart);
  8789. }
  8790. 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
  8791. // calculate possibly different bounding rect after rotation:
  8792. result.rotatedTotalBounds = result.totalBounds;
  8793. if (!qFuzzyIsNull(tickLabelRotation))
  8794. {
  8795. QTransform transform;
  8796. transform.rotate(tickLabelRotation);
  8797. result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds);
  8798. }
  8799. return result;
  8800. }
  8801. /*! \internal
  8802. This is a \ref placeTickLabel helper function.
  8803. Calculates the offset at which the top left corner of the specified tick label shall be drawn.
  8804. The offset is relative to a point right next to the tick the label belongs to.
  8805. This function is thus responsible for e.g. centering tick labels under ticks and positioning them
  8806. appropriately when they are rotated.
  8807. */
  8808. QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const
  8809. {
  8810. /*
  8811. calculate label offset from base point at tick (non-trivial, for best visual appearance): short
  8812. explanation for bottom axis: The anchor, i.e. the point in the label that is placed
  8813. horizontally under the corresponding tick is always on the label side that is closer to the
  8814. axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height
  8815. is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text
  8816. will be centered under the tick (i.e. displaced horizontally by half its height). At the same
  8817. time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick
  8818. labels.
  8819. */
  8820. bool doRotation = !qFuzzyIsNull(tickLabelRotation);
  8821. bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes.
  8822. double radians = tickLabelRotation/180.0*M_PI;
  8823. double x = 0;
  8824. double y = 0;
  8825. if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsInside)) // Anchor at right side of tick label
  8826. {
  8827. if (doRotation)
  8828. {
  8829. if (tickLabelRotation > 0)
  8830. {
  8831. x = -qCos(radians)*labelData.totalBounds.width();
  8832. y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0;
  8833. } else
  8834. {
  8835. x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height();
  8836. y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0;
  8837. }
  8838. } else
  8839. {
  8840. x = -labelData.totalBounds.width();
  8841. y = -labelData.totalBounds.height()/2.0;
  8842. }
  8843. } else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsInside)) // Anchor at left side of tick label
  8844. {
  8845. if (doRotation)
  8846. {
  8847. if (tickLabelRotation > 0)
  8848. {
  8849. x = +qSin(radians)*labelData.totalBounds.height();
  8850. y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0;
  8851. } else
  8852. {
  8853. x = 0;
  8854. y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0;
  8855. }
  8856. } else
  8857. {
  8858. x = 0;
  8859. y = -labelData.totalBounds.height()/2.0;
  8860. }
  8861. } else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsInside)) // Anchor at bottom side of tick label
  8862. {
  8863. if (doRotation)
  8864. {
  8865. if (tickLabelRotation > 0)
  8866. {
  8867. x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0;
  8868. y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height();
  8869. } else
  8870. {
  8871. x = -qSin(-radians)*labelData.totalBounds.height()/2.0;
  8872. y = -qCos(-radians)*labelData.totalBounds.height();
  8873. }
  8874. } else
  8875. {
  8876. x = -labelData.totalBounds.width()/2.0;
  8877. y = -labelData.totalBounds.height();
  8878. }
  8879. } else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsInside)) // Anchor at top side of tick label
  8880. {
  8881. if (doRotation)
  8882. {
  8883. if (tickLabelRotation > 0)
  8884. {
  8885. x = +qSin(radians)*labelData.totalBounds.height()/2.0;
  8886. y = 0;
  8887. } else
  8888. {
  8889. x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0;
  8890. y = +qSin(-radians)*labelData.totalBounds.width();
  8891. }
  8892. } else
  8893. {
  8894. x = -labelData.totalBounds.width()/2.0;
  8895. y = 0;
  8896. }
  8897. }
  8898. return {x, y};
  8899. }
  8900. /*! \internal
  8901. Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label
  8902. to be drawn, depending on number format etc. Since only the largest tick label is wanted for the
  8903. margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a
  8904. smaller width/height.
  8905. */
  8906. void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const
  8907. {
  8908. // note: this function must return the same tick label sizes as the placeTickLabel function.
  8909. QSize finalSize;
  8910. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label
  8911. {
  8912. const CachedLabel *cachedLabel = mLabelCache.object(text);
  8913. finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
  8914. } else // label caching disabled or no label with this text cached:
  8915. {
  8916. TickLabelData labelData = getTickLabelData(font, text);
  8917. finalSize = labelData.rotatedTotalBounds.size();
  8918. }
  8919. // expand passed tickLabelsSize if current tick label is larger:
  8920. if (finalSize.width() > tickLabelsSize->width())
  8921. tickLabelsSize->setWidth(finalSize.width());
  8922. if (finalSize.height() > tickLabelsSize->height())
  8923. tickLabelsSize->setHeight(finalSize.height());
  8924. }
  8925. /* end of 'src/axis/axis.cpp' */
  8926. /* including file 'src/scatterstyle.cpp' */
  8927. /* modified 2022-11-06T12:45:56, size 17466 */
  8928. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8929. //////////////////// QCPScatterStyle
  8930. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8931. /*! \class QCPScatterStyle
  8932. \brief Represents the visual appearance of scatter points
  8933. This class holds information about shape, color and size of scatter points. In plottables like
  8934. QCPGraph it is used to store how scatter points shall be drawn. For example, \ref
  8935. QCPGraph::setScatterStyle takes a QCPScatterStyle instance.
  8936. A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a
  8937. fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can
  8938. be controlled with \ref setSize.
  8939. \section QCPScatterStyle-defining Specifying a scatter style
  8940. You can set all these configurations either by calling the respective functions on an instance:
  8941. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-1
  8942. Or you can use one of the various constructors that take different parameter combinations, making
  8943. it easy to specify a scatter style in a single call, like so:
  8944. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-2
  8945. \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable
  8946. There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref
  8947. QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref
  8948. isPenDefined will return false. It leads to scatter points that inherit the pen from the
  8949. plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line
  8950. color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes
  8951. it very convenient to set up typical scatter settings:
  8952. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-shortcreation
  8953. Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works
  8954. because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly
  8955. into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size)
  8956. constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref
  8957. ScatterShape, where actually a QCPScatterStyle is expected.
  8958. \section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps
  8959. QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points.
  8960. For custom shapes, you can provide a QPainterPath with the desired shape to the \ref
  8961. setCustomPath function or call the constructor that takes a painter path. The scatter shape will
  8962. automatically be set to \ref ssCustom.
  8963. For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the
  8964. constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap.
  8965. Note that \ref setSize does not influence the appearance of the pixmap.
  8966. */
  8967. /* start documentation of inline functions */
  8968. /*! \fn bool QCPScatterStyle::isNone() const
  8969. Returns whether the scatter shape is \ref ssNone.
  8970. \see setShape
  8971. */
  8972. /*! \fn bool QCPScatterStyle::isPenDefined() const
  8973. Returns whether a pen has been defined for this scatter style.
  8974. The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those
  8975. are \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen
  8976. is undefined, the pen of the respective plottable will be used for drawing scatters.
  8977. If a pen was defined for this scatter style instance, and you now wish to undefine the pen, call
  8978. \ref undefinePen.
  8979. \see setPen
  8980. */
  8981. /* end documentation of inline functions */
  8982. /*!
  8983. Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined.
  8984. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
  8985. from the plottable that uses this scatter style.
  8986. */
  8987. QCPScatterStyle::QCPScatterStyle() :
  8988. mSize(6),
  8989. mShape(ssNone),
  8990. mPen(Qt::NoPen),
  8991. mBrush(Qt::NoBrush),
  8992. mPenDefined(false)
  8993. {
  8994. }
  8995. /*!
  8996. Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or
  8997. brush is defined.
  8998. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
  8999. from the plottable that uses this scatter style.
  9000. */
  9001. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) :
  9002. mSize(size),
  9003. mShape(shape),
  9004. mPen(Qt::NoPen),
  9005. mBrush(Qt::NoBrush),
  9006. mPenDefined(false)
  9007. {
  9008. }
  9009. /*!
  9010. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
  9011. and size to \a size. No brush is defined, i.e. the scatter point will not be filled.
  9012. */
  9013. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) :
  9014. mSize(size),
  9015. mShape(shape),
  9016. mPen(QPen(color)),
  9017. mBrush(Qt::NoBrush),
  9018. mPenDefined(true)
  9019. {
  9020. }
  9021. /*!
  9022. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
  9023. the brush color to \a fill (with a solid pattern), and size to \a size.
  9024. */
  9025. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) :
  9026. mSize(size),
  9027. mShape(shape),
  9028. mPen(QPen(color)),
  9029. mBrush(QBrush(fill)),
  9030. mPenDefined(true)
  9031. {
  9032. }
  9033. /*!
  9034. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the
  9035. brush to \a brush, and size to \a size.
  9036. \warning In some cases it might be tempting to directly use a pen style like <tt>Qt::NoPen</tt> as \a pen
  9037. and a color like <tt>Qt::blue</tt> as \a brush. Notice however, that the corresponding call\n
  9038. <tt>QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)</tt>\n
  9039. doesn't necessarily lead C++ to use this constructor in some cases, but might mistake
  9040. <tt>Qt::NoPen</tt> for a QColor and use the
  9041. \ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size)
  9042. constructor instead (which will lead to an unexpected look of the scatter points). To prevent
  9043. this, be more explicit with the parameter types. For example, use <tt>QBrush(Qt::blue)</tt>
  9044. instead of just <tt>Qt::blue</tt>, to clearly point out to the compiler that this constructor is
  9045. wanted.
  9046. */
  9047. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) :
  9048. mSize(size),
  9049. mShape(shape),
  9050. mPen(pen),
  9051. mBrush(brush),
  9052. mPenDefined(pen.style() != Qt::NoPen)
  9053. {
  9054. }
  9055. /*!
  9056. Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape
  9057. is set to \ref ssPixmap.
  9058. */
  9059. QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) :
  9060. mSize(5),
  9061. mShape(ssPixmap),
  9062. mPen(Qt::NoPen),
  9063. mBrush(Qt::NoBrush),
  9064. mPixmap(pixmap),
  9065. mPenDefined(false)
  9066. {
  9067. }
  9068. /*!
  9069. Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The
  9070. scatter shape is set to \ref ssCustom.
  9071. The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly
  9072. different meaning than for built-in scatter points: The custom path will be drawn scaled by a
  9073. factor of \a size/6.0. Since the default \a size is 6, the custom path will appear in its
  9074. original size by default. To for example double the size of the path, set \a size to 12.
  9075. */
  9076. QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) :
  9077. mSize(size),
  9078. mShape(ssCustom),
  9079. mPen(pen),
  9080. mBrush(brush),
  9081. mCustomPath(customPath),
  9082. mPenDefined(pen.style() != Qt::NoPen)
  9083. {
  9084. }
  9085. /*!
  9086. Copies the specified \a properties from the \a other scatter style to this scatter style.
  9087. */
  9088. void QCPScatterStyle::setFromOther(const QCPScatterStyle &other, ScatterProperties properties)
  9089. {
  9090. if (properties.testFlag(spPen))
  9091. {
  9092. setPen(other.pen());
  9093. if (!other.isPenDefined())
  9094. undefinePen();
  9095. }
  9096. if (properties.testFlag(spBrush))
  9097. setBrush(other.brush());
  9098. if (properties.testFlag(spSize))
  9099. setSize(other.size());
  9100. if (properties.testFlag(spShape))
  9101. {
  9102. setShape(other.shape());
  9103. if (other.shape() == ssPixmap)
  9104. setPixmap(other.pixmap());
  9105. else if (other.shape() == ssCustom)
  9106. setCustomPath(other.customPath());
  9107. }
  9108. }
  9109. /*!
  9110. Sets the size (pixel diameter) of the drawn scatter points to \a size.
  9111. \see setShape
  9112. */
  9113. void QCPScatterStyle::setSize(double size)
  9114. {
  9115. mSize = size;
  9116. }
  9117. /*!
  9118. Sets the shape to \a shape.
  9119. Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref
  9120. ssPixmap and \ref ssCustom, respectively.
  9121. \see setSize
  9122. */
  9123. void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape)
  9124. {
  9125. mShape = shape;
  9126. }
  9127. /*!
  9128. Sets the pen that will be used to draw scatter points to \a pen.
  9129. If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after
  9130. a call to this function, even if \a pen is <tt>Qt::NoPen</tt>. If you have defined a pen
  9131. previously by calling this function and now wish to undefine the pen, call \ref undefinePen.
  9132. \see setBrush
  9133. */
  9134. void QCPScatterStyle::setPen(const QPen &pen)
  9135. {
  9136. mPenDefined = true;
  9137. mPen = pen;
  9138. }
  9139. /*!
  9140. Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter
  9141. shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does.
  9142. \see setPen
  9143. */
  9144. void QCPScatterStyle::setBrush(const QBrush &brush)
  9145. {
  9146. mBrush = brush;
  9147. }
  9148. /*!
  9149. Sets the pixmap that will be drawn as scatter point to \a pixmap.
  9150. Note that \ref setSize does not influence the appearance of the pixmap.
  9151. The scatter shape is automatically set to \ref ssPixmap.
  9152. */
  9153. void QCPScatterStyle::setPixmap(const QPixmap &pixmap)
  9154. {
  9155. setShape(ssPixmap);
  9156. mPixmap = pixmap;
  9157. }
  9158. /*!
  9159. Sets the custom shape that will be drawn as scatter point to \a customPath.
  9160. The scatter shape is automatically set to \ref ssCustom.
  9161. */
  9162. void QCPScatterStyle::setCustomPath(const QPainterPath &customPath)
  9163. {
  9164. setShape(ssCustom);
  9165. mCustomPath = customPath;
  9166. }
  9167. /*!
  9168. Sets this scatter style to have an undefined pen (see \ref isPenDefined for what an undefined pen
  9169. implies).
  9170. A call to \ref setPen will define a pen.
  9171. */
  9172. void QCPScatterStyle::undefinePen()
  9173. {
  9174. mPenDefined = false;
  9175. }
  9176. /*!
  9177. Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an
  9178. undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead.
  9179. This function is used by plottables (or any class that wants to draw scatters) just before a
  9180. number of scatters with this style shall be drawn with the \a painter.
  9181. \see drawShape
  9182. */
  9183. void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const
  9184. {
  9185. painter->setPen(mPenDefined ? mPen : defaultPen);
  9186. painter->setBrush(mBrush);
  9187. }
  9188. /*!
  9189. Draws the scatter shape with \a painter at position \a pos.
  9190. This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be
  9191. called before scatter points are drawn with \ref drawShape.
  9192. \see applyTo
  9193. */
  9194. void QCPScatterStyle::drawShape(QCPPainter *painter, const QPointF &pos) const
  9195. {
  9196. drawShape(painter, pos.x(), pos.y());
  9197. }
  9198. /*! \overload
  9199. Draws the scatter shape with \a painter at position \a x and \a y.
  9200. */
  9201. void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const
  9202. {
  9203. double w = mSize/2.0;
  9204. switch (mShape)
  9205. {
  9206. case ssNone: break;
  9207. case ssDot:
  9208. {
  9209. painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y));
  9210. break;
  9211. }
  9212. case ssCross:
  9213. {
  9214. painter->drawLine(QLineF(x-w, y-w, x+w, y+w));
  9215. painter->drawLine(QLineF(x-w, y+w, x+w, y-w));
  9216. break;
  9217. }
  9218. case ssPlus:
  9219. {
  9220. painter->drawLine(QLineF(x-w, y, x+w, y));
  9221. painter->drawLine(QLineF( x, y+w, x, y-w));
  9222. break;
  9223. }
  9224. case ssCircle:
  9225. {
  9226. painter->drawEllipse(QPointF(x , y), w, w);
  9227. break;
  9228. }
  9229. case ssDisc:
  9230. {
  9231. QBrush b = painter->brush();
  9232. painter->setBrush(painter->pen().color());
  9233. painter->drawEllipse(QPointF(x , y), w, w);
  9234. painter->setBrush(b);
  9235. break;
  9236. }
  9237. case ssSquare:
  9238. {
  9239. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  9240. break;
  9241. }
  9242. case ssDiamond:
  9243. {
  9244. QPointF lineArray[4] = {QPointF(x-w, y),
  9245. QPointF( x, y-w),
  9246. QPointF(x+w, y),
  9247. QPointF( x, y+w)};
  9248. painter->drawPolygon(lineArray, 4);
  9249. break;
  9250. }
  9251. case ssStar:
  9252. {
  9253. painter->drawLine(QLineF(x-w, y, x+w, y));
  9254. painter->drawLine(QLineF( x, y+w, x, y-w));
  9255. painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707));
  9256. painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707));
  9257. break;
  9258. }
  9259. case ssTriangle:
  9260. {
  9261. QPointF lineArray[3] = {QPointF(x-w, y+0.755*w),
  9262. QPointF(x+w, y+0.755*w),
  9263. QPointF( x, y-0.977*w)};
  9264. painter->drawPolygon(lineArray, 3);
  9265. break;
  9266. }
  9267. case ssTriangleInverted:
  9268. {
  9269. QPointF lineArray[3] = {QPointF(x-w, y-0.755*w),
  9270. QPointF(x+w, y-0.755*w),
  9271. QPointF( x, y+0.977*w)};
  9272. painter->drawPolygon(lineArray, 3);
  9273. break;
  9274. }
  9275. case ssCrossSquare:
  9276. {
  9277. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  9278. painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95));
  9279. painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w));
  9280. break;
  9281. }
  9282. case ssPlusSquare:
  9283. {
  9284. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  9285. painter->drawLine(QLineF(x-w, y, x+w*0.95, y));
  9286. painter->drawLine(QLineF( x, y+w, x, y-w));
  9287. break;
  9288. }
  9289. case ssCrossCircle:
  9290. {
  9291. painter->drawEllipse(QPointF(x, y), w, w);
  9292. painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670));
  9293. painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707));
  9294. break;
  9295. }
  9296. case ssPlusCircle:
  9297. {
  9298. painter->drawEllipse(QPointF(x, y), w, w);
  9299. painter->drawLine(QLineF(x-w, y, x+w, y));
  9300. painter->drawLine(QLineF( x, y+w, x, y-w));
  9301. break;
  9302. }
  9303. case ssPeace:
  9304. {
  9305. painter->drawEllipse(QPointF(x, y), w, w);
  9306. painter->drawLine(QLineF(x, y-w, x, y+w));
  9307. painter->drawLine(QLineF(x, y, x-w*0.707, y+w*0.707));
  9308. painter->drawLine(QLineF(x, y, x+w*0.707, y+w*0.707));
  9309. break;
  9310. }
  9311. case ssPixmap:
  9312. {
  9313. const double widthHalf = mPixmap.width()*0.5;
  9314. const double heightHalf = mPixmap.height()*0.5;
  9315. #if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
  9316. const QRectF clipRect = painter->clipRegion().boundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf);
  9317. #else
  9318. const QRectF clipRect = painter->clipBoundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf);
  9319. #endif
  9320. if (clipRect.contains(x, y))
  9321. painter->drawPixmap(qRound(x-widthHalf), qRound(y-heightHalf), mPixmap);
  9322. break;
  9323. }
  9324. case ssCustom:
  9325. {
  9326. QTransform oldTransform = painter->transform();
  9327. painter->translate(x, y);
  9328. painter->scale(mSize/6.0, mSize/6.0);
  9329. painter->drawPath(mCustomPath);
  9330. painter->setTransform(oldTransform);
  9331. break;
  9332. }
  9333. }
  9334. }
  9335. /* end of 'src/scatterstyle.cpp' */
  9336. /* including file 'src/plottable.cpp' */
  9337. /* modified 2022-11-06T12:45:56, size 38818 */
  9338. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9339. //////////////////// QCPSelectionDecorator
  9340. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9341. /*! \class QCPSelectionDecorator
  9342. \brief Controls how a plottable's data selection is drawn
  9343. Each \ref QCPAbstractPlottable instance has one \ref QCPSelectionDecorator (accessible via \ref
  9344. QCPAbstractPlottable::selectionDecorator) and uses it when drawing selected segments of its data.
  9345. The selection decorator controls both pen (\ref setPen) and brush (\ref setBrush), as well as the
  9346. scatter style (\ref setScatterStyle) if the plottable draws scatters. Since a \ref
  9347. QCPScatterStyle is itself composed of different properties such as color shape and size, the
  9348. decorator allows specifying exactly which of those properties shall be used for the selected data
  9349. point, via \ref setUsedScatterProperties.
  9350. A \ref QCPSelectionDecorator subclass instance can be passed to a plottable via \ref
  9351. QCPAbstractPlottable::setSelectionDecorator, allowing greater customizability of the appearance
  9352. of selected segments.
  9353. Use \ref copyFrom to easily transfer the settings of one decorator to another one. This is
  9354. especially useful since plottables take ownership of the passed selection decorator, and thus the
  9355. same decorator instance can not be passed to multiple plottables.
  9356. Selection decorators can also themselves perform drawing operations by reimplementing \ref
  9357. drawDecoration, which is called by the plottable's draw method. The base class \ref
  9358. QCPSelectionDecorator does not make use of this however. For example, \ref
  9359. QCPSelectionDecoratorBracket draws brackets around selected data segments.
  9360. */
  9361. /*!
  9362. Creates a new QCPSelectionDecorator instance with default values
  9363. */
  9364. QCPSelectionDecorator::QCPSelectionDecorator() :
  9365. mPen(QColor(80, 80, 255), 2.5),
  9366. mBrush(Qt::NoBrush),
  9367. mUsedScatterProperties(QCPScatterStyle::spNone),
  9368. mPlottable(nullptr)
  9369. {
  9370. }
  9371. QCPSelectionDecorator::~QCPSelectionDecorator()
  9372. {
  9373. }
  9374. /*!
  9375. Sets the pen that will be used by the parent plottable to draw selected data segments.
  9376. */
  9377. void QCPSelectionDecorator::setPen(const QPen &pen)
  9378. {
  9379. mPen = pen;
  9380. }
  9381. /*!
  9382. Sets the brush that will be used by the parent plottable to draw selected data segments.
  9383. */
  9384. void QCPSelectionDecorator::setBrush(const QBrush &brush)
  9385. {
  9386. mBrush = brush;
  9387. }
  9388. /*!
  9389. Sets the scatter style that will be used by the parent plottable to draw scatters in selected
  9390. data segments.
  9391. \a usedProperties specifies which parts of the passed \a scatterStyle will be used by the
  9392. plottable. The used properties can also be changed via \ref setUsedScatterProperties.
  9393. */
  9394. void QCPSelectionDecorator::setScatterStyle(const QCPScatterStyle &scatterStyle, QCPScatterStyle::ScatterProperties usedProperties)
  9395. {
  9396. mScatterStyle = scatterStyle;
  9397. setUsedScatterProperties(usedProperties);
  9398. }
  9399. /*!
  9400. Use this method to define which properties of the scatter style (set via \ref setScatterStyle)
  9401. will be used for selected data segments. All properties of the scatter style that are not
  9402. specified in \a properties will remain as specified in the plottable's original scatter style.
  9403. \see QCPScatterStyle::ScatterProperty
  9404. */
  9405. void QCPSelectionDecorator::setUsedScatterProperties(const QCPScatterStyle::ScatterProperties &properties)
  9406. {
  9407. mUsedScatterProperties = properties;
  9408. }
  9409. /*!
  9410. Sets the pen of \a painter to the pen of this selection decorator.
  9411. \see applyBrush, getFinalScatterStyle
  9412. */
  9413. void QCPSelectionDecorator::applyPen(QCPPainter *painter) const
  9414. {
  9415. painter->setPen(mPen);
  9416. }
  9417. /*!
  9418. Sets the brush of \a painter to the brush of this selection decorator.
  9419. \see applyPen, getFinalScatterStyle
  9420. */
  9421. void QCPSelectionDecorator::applyBrush(QCPPainter *painter) const
  9422. {
  9423. painter->setBrush(mBrush);
  9424. }
  9425. /*!
  9426. Returns the scatter style that the parent plottable shall use for selected scatter points. The
  9427. plottable's original (unselected) scatter style must be passed as \a unselectedStyle. Depending
  9428. on the setting of \ref setUsedScatterProperties, the returned scatter style is a mixture of this
  9429. selecion decorator's scatter style (\ref setScatterStyle), and \a unselectedStyle.
  9430. \see applyPen, applyBrush, setScatterStyle
  9431. */
  9432. QCPScatterStyle QCPSelectionDecorator::getFinalScatterStyle(const QCPScatterStyle &unselectedStyle) const
  9433. {
  9434. QCPScatterStyle result(unselectedStyle);
  9435. result.setFromOther(mScatterStyle, mUsedScatterProperties);
  9436. // if style shall inherit pen from plottable (has no own pen defined), give it the selected
  9437. // plottable pen explicitly, so it doesn't use the unselected plottable pen when used in the
  9438. // plottable:
  9439. if (!result.isPenDefined())
  9440. result.setPen(mPen);
  9441. return result;
  9442. }
  9443. /*!
  9444. Copies all properties (e.g. color, fill, scatter style) of the \a other selection decorator to
  9445. this selection decorator.
  9446. */
  9447. void QCPSelectionDecorator::copyFrom(const QCPSelectionDecorator *other)
  9448. {
  9449. setPen(other->pen());
  9450. setBrush(other->brush());
  9451. setScatterStyle(other->scatterStyle(), other->usedScatterProperties());
  9452. }
  9453. /*!
  9454. This method is called by all plottables' draw methods to allow custom selection decorations to be
  9455. drawn. Use the passed \a painter to perform the drawing operations. \a selection carries the data
  9456. selection for which the decoration shall be drawn.
  9457. The default base class implementation of \ref QCPSelectionDecorator has no special decoration, so
  9458. this method does nothing.
  9459. */
  9460. void QCPSelectionDecorator::drawDecoration(QCPPainter *painter, QCPDataSelection selection)
  9461. {
  9462. Q_UNUSED(painter)
  9463. Q_UNUSED(selection)
  9464. }
  9465. /*! \internal
  9466. This method is called as soon as a selection decorator is associated with a plottable, by a call
  9467. to \ref QCPAbstractPlottable::setSelectionDecorator. This way the selection decorator can obtain a pointer to the plottable that uses it (e.g. to access
  9468. data points via the \ref QCPAbstractPlottable::interface1D interface).
  9469. If the selection decorator was already added to a different plottable before, this method aborts
  9470. the registration and returns false.
  9471. */
  9472. bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottable)
  9473. {
  9474. if (!mPlottable)
  9475. {
  9476. mPlottable = plottable;
  9477. return true;
  9478. } else
  9479. {
  9480. qDebug() << Q_FUNC_INFO << "This selection decorator is already registered with plottable:" << reinterpret_cast<quintptr>(mPlottable);
  9481. return false;
  9482. }
  9483. }
  9484. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9485. //////////////////// QCPAbstractPlottable
  9486. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9487. /*! \class QCPAbstractPlottable
  9488. \brief The abstract base class for all data representing objects in a plot.
  9489. It defines a very basic interface like name, pen, brush, visibility etc. Since this class is
  9490. abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to
  9491. create new ways of displaying data (see "Creating own plottables" below). Plottables that display
  9492. one-dimensional data (i.e. data points have a single key dimension and one or multiple values at
  9493. each key) are based off of the template subclass \ref QCPAbstractPlottable1D, see details
  9494. there.
  9495. All further specifics are in the subclasses, for example:
  9496. \li A normal graph with possibly a line and/or scatter points \ref QCPGraph
  9497. (typically created with \ref QCustomPlot::addGraph)
  9498. \li A parametric curve: \ref QCPCurve
  9499. \li A bar chart: \ref QCPBars
  9500. \li A statistical box plot: \ref QCPStatisticalBox
  9501. \li A color encoded two-dimensional map: \ref QCPColorMap
  9502. \li An OHLC/Candlestick chart: \ref QCPFinancial
  9503. \section plottables-subclassing Creating own plottables
  9504. Subclassing directly from QCPAbstractPlottable is only recommended if you wish to display
  9505. two-dimensional data like \ref QCPColorMap, i.e. two logical key dimensions and one (or more)
  9506. data dimensions. If you want to display data with only one logical key dimension, you should
  9507. rather derive from \ref QCPAbstractPlottable1D.
  9508. If subclassing QCPAbstractPlottable directly, these are the pure virtual functions you must
  9509. implement:
  9510. \li \ref selectTest
  9511. \li \ref draw
  9512. \li \ref drawLegendIcon
  9513. \li \ref getKeyRange
  9514. \li \ref getValueRange
  9515. See the documentation of those functions for what they need to do.
  9516. For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot
  9517. coordinates to pixel coordinates. This function is quite convenient, because it takes the
  9518. orientation of the key and value axes into account for you (x and y are swapped when the key axis
  9519. is vertical and the value axis horizontal). If you are worried about performance (i.e. you need
  9520. to translate many points in a loop like QCPGraph), you can directly use \ref
  9521. QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis
  9522. yourself.
  9523. Here are some important members you inherit from QCPAbstractPlottable:
  9524. <table>
  9525. <tr>
  9526. <td>QCustomPlot *\b mParentPlot</td>
  9527. <td>A pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.</td>
  9528. </tr><tr>
  9529. <td>QString \b mName</td>
  9530. <td>The name of the plottable.</td>
  9531. </tr><tr>
  9532. <td>QPen \b mPen</td>
  9533. <td>The generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable
  9534. (e.g QCPGraph uses this pen for its graph lines and scatters)</td>
  9535. </tr><tr>
  9536. <td>QBrush \b mBrush</td>
  9537. <td>The generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable
  9538. (e.g. QCPGraph uses this brush to control filling under the graph)</td>
  9539. </tr><tr>
  9540. <td>QPointer<\ref QCPAxis> \b mKeyAxis, \b mValueAxis</td>
  9541. <td>The key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates
  9542. 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
  9543. the axes is null, don't draw the plottable.</td>
  9544. </tr><tr>
  9545. <td>\ref QCPSelectionDecorator \b mSelectionDecorator</td>
  9546. <td>The currently set selection decorator which specifies how selected data of the plottable shall be drawn and decorated.
  9547. When drawing your data, you must consult this decorator for the appropriate pen/brush before drawing unselected/selected data segments.
  9548. Finally, you should call its \ref QCPSelectionDecorator::drawDecoration method at the end of your \ref draw implementation.</td>
  9549. </tr><tr>
  9550. <td>\ref QCP::SelectionType \b mSelectable</td>
  9551. <td>In which composition, if at all, this plottable's data may be selected. Enforcing this setting on the data selection is done
  9552. by QCPAbstractPlottable automatically.</td>
  9553. </tr><tr>
  9554. <td>\ref QCPDataSelection \b mSelection</td>
  9555. <td>Holds the current selection state of the plottable's data, i.e. the selected data ranges (\ref QCPDataRange).</td>
  9556. </tr>
  9557. </table>
  9558. */
  9559. /* start of documentation of inline functions */
  9560. /*! \fn QCPSelectionDecorator *QCPAbstractPlottable::selectionDecorator() const
  9561. Provides access to the selection decorator of this plottable. The selection decorator controls
  9562. how selected data ranges are drawn (e.g. their pen color and fill), see \ref
  9563. QCPSelectionDecorator for details.
  9564. If you wish to use an own \ref QCPSelectionDecorator subclass, pass an instance of it to \ref
  9565. setSelectionDecorator.
  9566. */
  9567. /*! \fn bool QCPAbstractPlottable::selected() const
  9568. Returns true if there are any data points of the plottable currently selected. Use \ref selection
  9569. to retrieve the current \ref QCPDataSelection.
  9570. */
  9571. /*! \fn QCPDataSelection QCPAbstractPlottable::selection() const
  9572. Returns a \ref QCPDataSelection encompassing all the data points that are currently selected on
  9573. this plottable.
  9574. \see selected, setSelection, setSelectable
  9575. */
  9576. /*! \fn virtual QCPPlottableInterface1D *QCPAbstractPlottable::interface1D()
  9577. If this plottable is a one-dimensional plottable, i.e. it implements the \ref
  9578. QCPPlottableInterface1D, returns the \a this pointer with that type. Otherwise (e.g. in the case
  9579. of a \ref QCPColorMap) returns zero.
  9580. You can use this method to gain read access to data coordinates while holding a pointer to the
  9581. abstract base class only.
  9582. */
  9583. /* end of documentation of inline functions */
  9584. /* start of documentation of pure virtual functions */
  9585. /*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0
  9586. \internal
  9587. called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation
  9588. of this plottable inside \a rect, next to the plottable name.
  9589. The passed \a painter has its cliprect set to \a rect, so painting outside of \a rect won't
  9590. appear outside the legend icon border.
  9591. */
  9592. /*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const = 0
  9593. Returns the coordinate range that all data in this plottable span in the key axis dimension. For
  9594. logarithmic plots, one can set \a inSignDomain to either \ref QCP::sdNegative or \ref
  9595. QCP::sdPositive in order to restrict the returned range to that sign domain. E.g. when only
  9596. negative range is wanted, set \a inSignDomain to \ref QCP::sdNegative and all positive points
  9597. will be ignored for range calculation. For no restriction, just set \a inSignDomain to \ref
  9598. QCP::sdBoth (default). \a foundRange is an output parameter that indicates whether a range could
  9599. be found or not. If this is false, you shouldn't use the returned range (e.g. no points in data).
  9600. Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
  9601. this function may have size zero (e.g. when there is only one data point). In this case \a
  9602. foundRange would return true, but the returned range is not a valid range in terms of \ref
  9603. QCPRange::validRange.
  9604. \see rescaleAxes, getValueRange
  9605. */
  9606. /*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const = 0
  9607. Returns the coordinate range that the data points in the specified key range (\a inKeyRange) span
  9608. in the value axis dimension. For logarithmic plots, one can set \a inSignDomain to either \ref
  9609. QCP::sdNegative or \ref QCP::sdPositive in order to restrict the returned range to that sign
  9610. domain. E.g. when only negative range is wanted, set \a inSignDomain to \ref QCP::sdNegative and
  9611. all positive points will be ignored for range calculation. For no restriction, just set \a
  9612. inSignDomain to \ref QCP::sdBoth (default). \a foundRange is an output parameter that indicates
  9613. whether a range could be found or not. If this is false, you shouldn't use the returned range
  9614. (e.g. no points in data).
  9615. If \a inKeyRange has both lower and upper bound set to zero (is equal to <tt>QCPRange()</tt>),
  9616. all data points are considered, without any restriction on the keys.
  9617. Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
  9618. this function may have size zero (e.g. when there is only one data point). In this case \a
  9619. foundRange would return true, but the returned range is not a valid range in terms of \ref
  9620. QCPRange::validRange.
  9621. \see rescaleAxes, getKeyRange
  9622. */
  9623. /* end of documentation of pure virtual functions */
  9624. /* start of documentation of signals */
  9625. /*! \fn void QCPAbstractPlottable::selectionChanged(bool selected)
  9626. This signal is emitted when the selection state of this plottable has changed, either by user
  9627. interaction or by a direct call to \ref setSelection. The parameter \a selected indicates whether
  9628. there are any points selected or not.
  9629. \see selectionChanged(const QCPDataSelection &selection)
  9630. */
  9631. /*! \fn void QCPAbstractPlottable::selectionChanged(const QCPDataSelection &selection)
  9632. This signal is emitted when the selection state of this plottable has changed, either by user
  9633. interaction or by a direct call to \ref setSelection. The parameter \a selection holds the
  9634. currently selected data ranges.
  9635. \see selectionChanged(bool selected)
  9636. */
  9637. /*! \fn void QCPAbstractPlottable::selectableChanged(QCP::SelectionType selectable);
  9638. This signal is emitted when the selectability of this plottable has changed.
  9639. \see setSelectable
  9640. */
  9641. /* end of documentation of signals */
  9642. /*!
  9643. Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as
  9644. its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance
  9645. and have perpendicular orientations. If either of these restrictions is violated, a corresponding
  9646. message is printed to the debug output (qDebug), the construction is not aborted, though.
  9647. Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables,
  9648. it can't be directly instantiated.
  9649. You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead.
  9650. */
  9651. QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  9652. QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect()),
  9653. mName(),
  9654. mAntialiasedFill(true),
  9655. mAntialiasedScatters(true),
  9656. mPen(Qt::black),
  9657. mBrush(Qt::NoBrush),
  9658. mKeyAxis(keyAxis),
  9659. mValueAxis(valueAxis),
  9660. mSelectable(QCP::stWhole),
  9661. mSelectionDecorator(nullptr)
  9662. {
  9663. if (keyAxis->parentPlot() != valueAxis->parentPlot())
  9664. qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
  9665. if (keyAxis->orientation() == valueAxis->orientation())
  9666. qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other.";
  9667. mParentPlot->registerPlottable(this);
  9668. setSelectionDecorator(new QCPSelectionDecorator);
  9669. }
  9670. QCPAbstractPlottable::~QCPAbstractPlottable()
  9671. {
  9672. if (mSelectionDecorator)
  9673. {
  9674. delete mSelectionDecorator;
  9675. mSelectionDecorator = nullptr;
  9676. }
  9677. }
  9678. /*!
  9679. The name is the textual representation of this plottable as it is displayed in the legend
  9680. (\ref QCPLegend). It may contain any UTF-8 characters, including newlines.
  9681. */
  9682. void QCPAbstractPlottable::setName(const QString &name)
  9683. {
  9684. mName = name;
  9685. }
  9686. /*!
  9687. Sets whether fills of this plottable are drawn antialiased or not.
  9688. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  9689. QCustomPlot::setNotAntialiasedElements.
  9690. */
  9691. void QCPAbstractPlottable::setAntialiasedFill(bool enabled)
  9692. {
  9693. mAntialiasedFill = enabled;
  9694. }
  9695. /*!
  9696. Sets whether the scatter symbols of this plottable are drawn antialiased or not.
  9697. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  9698. QCustomPlot::setNotAntialiasedElements.
  9699. */
  9700. void QCPAbstractPlottable::setAntialiasedScatters(bool enabled)
  9701. {
  9702. mAntialiasedScatters = enabled;
  9703. }
  9704. /*!
  9705. The pen is used to draw basic lines that make up the plottable representation in the
  9706. plot.
  9707. For example, the \ref QCPGraph subclass draws its graph lines with this pen.
  9708. \see setBrush
  9709. */
  9710. void QCPAbstractPlottable::setPen(const QPen &pen)
  9711. {
  9712. mPen = pen;
  9713. }
  9714. /*!
  9715. The brush is used to draw basic fills of the plottable representation in the
  9716. plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
  9717. For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when
  9718. it's not set to Qt::NoBrush.
  9719. \see setPen
  9720. */
  9721. void QCPAbstractPlottable::setBrush(const QBrush &brush)
  9722. {
  9723. mBrush = brush;
  9724. }
  9725. /*!
  9726. The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
  9727. to the plottable's value axis. This function performs no checks to make sure this is the case.
  9728. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
  9729. y-axis (QCustomPlot::yAxis) as value axis.
  9730. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  9731. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  9732. \see setValueAxis
  9733. */
  9734. void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis)
  9735. {
  9736. mKeyAxis = axis;
  9737. }
  9738. /*!
  9739. The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is
  9740. orthogonal to the plottable's key axis. This function performs no checks to make sure this is the
  9741. case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and
  9742. the y-axis (QCustomPlot::yAxis) as value axis.
  9743. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  9744. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  9745. \see setKeyAxis
  9746. */
  9747. void QCPAbstractPlottable::setValueAxis(QCPAxis *axis)
  9748. {
  9749. mValueAxis = axis;
  9750. }
  9751. /*!
  9752. Sets which data ranges of this plottable are selected. Selected data ranges are drawn differently
  9753. (e.g. color) in the plot. This can be controlled via the selection decorator (see \ref
  9754. selectionDecorator).
  9755. The entire selection mechanism for plottables is handled automatically when \ref
  9756. QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
  9757. you wish to change the selection state programmatically.
  9758. Using \ref setSelectable you can further specify for each plottable whether and to which
  9759. granularity it is selectable. If \a selection is not compatible with the current \ref
  9760. QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted
  9761. accordingly (see \ref QCPDataSelection::enforceType).
  9762. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  9763. \see setSelectable, selectTest
  9764. */
  9765. void QCPAbstractPlottable::setSelection(QCPDataSelection selection)
  9766. {
  9767. selection.enforceType(mSelectable);
  9768. if (mSelection != selection)
  9769. {
  9770. mSelection = selection;
  9771. emit selectionChanged(selected());
  9772. emit selectionChanged(mSelection);
  9773. }
  9774. }
  9775. /*!
  9776. Use this method to set an own QCPSelectionDecorator (subclass) instance. This allows you to
  9777. customize the visual representation of selected data ranges further than by using the default
  9778. QCPSelectionDecorator.
  9779. The plottable takes ownership of the \a decorator.
  9780. The currently set decorator can be accessed via \ref selectionDecorator.
  9781. */
  9782. void QCPAbstractPlottable::setSelectionDecorator(QCPSelectionDecorator *decorator)
  9783. {
  9784. if (decorator)
  9785. {
  9786. if (decorator->registerWithPlottable(this))
  9787. {
  9788. delete mSelectionDecorator; // delete old decorator if necessary
  9789. mSelectionDecorator = decorator;
  9790. }
  9791. } else if (mSelectionDecorator) // just clear decorator
  9792. {
  9793. delete mSelectionDecorator;
  9794. mSelectionDecorator = nullptr;
  9795. }
  9796. }
  9797. /*!
  9798. Sets whether and to which granularity this plottable can be selected.
  9799. A selection can happen by clicking on the QCustomPlot surface (When \ref
  9800. QCustomPlot::setInteractions contains \ref QCP::iSelectPlottables), by dragging a selection rect
  9801. (When \ref QCustomPlot::setSelectionRectMode is \ref QCP::srmSelect), or programmatically by
  9802. calling \ref setSelection.
  9803. \see setSelection, QCP::SelectionType
  9804. */
  9805. void QCPAbstractPlottable::setSelectable(QCP::SelectionType selectable)
  9806. {
  9807. if (mSelectable != selectable)
  9808. {
  9809. mSelectable = selectable;
  9810. QCPDataSelection oldSelection = mSelection;
  9811. mSelection.enforceType(mSelectable);
  9812. emit selectableChanged(mSelectable);
  9813. if (mSelection != oldSelection)
  9814. {
  9815. emit selectionChanged(selected());
  9816. emit selectionChanged(mSelection);
  9817. }
  9818. }
  9819. }
  9820. /*!
  9821. Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface,
  9822. taking the orientations of the axes associated with this plottable into account (e.g. whether key
  9823. represents x or y).
  9824. \a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y.
  9825. \see pixelsToCoords, QCPAxis::coordToPixel
  9826. */
  9827. void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const
  9828. {
  9829. QCPAxis *keyAxis = mKeyAxis.data();
  9830. QCPAxis *valueAxis = mValueAxis.data();
  9831. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  9832. if (keyAxis->orientation() == Qt::Horizontal)
  9833. {
  9834. x = keyAxis->coordToPixel(key);
  9835. y = valueAxis->coordToPixel(value);
  9836. } else
  9837. {
  9838. y = keyAxis->coordToPixel(key);
  9839. x = valueAxis->coordToPixel(value);
  9840. }
  9841. }
  9842. /*! \overload
  9843. Transforms the given \a key and \a value to pixel coordinates and returns them in a QPointF.
  9844. */
  9845. const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const
  9846. {
  9847. QCPAxis *keyAxis = mKeyAxis.data();
  9848. QCPAxis *valueAxis = mValueAxis.data();
  9849. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
  9850. if (keyAxis->orientation() == Qt::Horizontal)
  9851. return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value));
  9852. else
  9853. return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key));
  9854. }
  9855. /*!
  9856. Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates,
  9857. taking the orientations of the axes associated with this plottable into account (e.g. whether key
  9858. represents x or y).
  9859. \a x and \a y are transformed to the plot coodinates and are written to \a key and \a value.
  9860. \see coordsToPixels, QCPAxis::coordToPixel
  9861. */
  9862. void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const
  9863. {
  9864. QCPAxis *keyAxis = mKeyAxis.data();
  9865. QCPAxis *valueAxis = mValueAxis.data();
  9866. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  9867. if (keyAxis->orientation() == Qt::Horizontal)
  9868. {
  9869. key = keyAxis->pixelToCoord(x);
  9870. value = valueAxis->pixelToCoord(y);
  9871. } else
  9872. {
  9873. key = keyAxis->pixelToCoord(y);
  9874. value = valueAxis->pixelToCoord(x);
  9875. }
  9876. }
  9877. /*! \overload
  9878. Returns the pixel input \a pixelPos as plot coordinates \a key and \a value.
  9879. */
  9880. void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
  9881. {
  9882. pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value);
  9883. }
  9884. /*!
  9885. Rescales the key and value axes associated with this plottable to contain all displayed data, so
  9886. the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make
  9887. sure not to rescale to an illegal range i.e. a range containing different signs and/or zero.
  9888. Instead it will stay in the current sign domain and ignore all parts of the plottable that lie
  9889. outside of that domain.
  9890. \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show
  9891. multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has
  9892. \a onlyEnlarge set to false (the default), and all subsequent set to true.
  9893. \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale
  9894. */
  9895. void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const
  9896. {
  9897. rescaleKeyAxis(onlyEnlarge);
  9898. rescaleValueAxis(onlyEnlarge);
  9899. }
  9900. /*!
  9901. Rescales the key axis of the plottable so the whole plottable is visible.
  9902. See \ref rescaleAxes for detailed behaviour.
  9903. */
  9904. void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const
  9905. {
  9906. QCPAxis *keyAxis = mKeyAxis.data();
  9907. if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
  9908. QCP::SignDomain signDomain = QCP::sdBoth;
  9909. if (keyAxis->scaleType() == QCPAxis::stLogarithmic)
  9910. signDomain = (keyAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  9911. bool foundRange;
  9912. QCPRange newRange = getKeyRange(foundRange, signDomain);
  9913. if (foundRange)
  9914. {
  9915. if (onlyEnlarge)
  9916. newRange.expand(keyAxis->range());
  9917. 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
  9918. {
  9919. 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
  9920. if (keyAxis->scaleType() == QCPAxis::stLinear)
  9921. {
  9922. newRange.lower = center-keyAxis->range().size()/2.0;
  9923. newRange.upper = center+keyAxis->range().size()/2.0;
  9924. } else // scaleType() == stLogarithmic
  9925. {
  9926. newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower);
  9927. newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower);
  9928. }
  9929. }
  9930. keyAxis->setRange(newRange);
  9931. }
  9932. }
  9933. /*!
  9934. Rescales the value axis of the plottable so the whole plottable is visible. If \a inKeyRange is
  9935. set to true, only the data points which are in the currently visible key axis range are
  9936. considered.
  9937. Returns true if the axis was actually scaled. This might not be the case if this plottable has an
  9938. invalid range, e.g. because it has no data points.
  9939. See \ref rescaleAxes for detailed behaviour.
  9940. */
  9941. void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const
  9942. {
  9943. QCPAxis *keyAxis = mKeyAxis.data();
  9944. QCPAxis *valueAxis = mValueAxis.data();
  9945. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  9946. QCP::SignDomain signDomain = QCP::sdBoth;
  9947. if (valueAxis->scaleType() == QCPAxis::stLogarithmic)
  9948. signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  9949. bool foundRange;
  9950. QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange());
  9951. if (foundRange)
  9952. {
  9953. if (onlyEnlarge)
  9954. newRange.expand(valueAxis->range());
  9955. 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
  9956. {
  9957. 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
  9958. if (valueAxis->scaleType() == QCPAxis::stLinear)
  9959. {
  9960. newRange.lower = center-valueAxis->range().size()/2.0;
  9961. newRange.upper = center+valueAxis->range().size()/2.0;
  9962. } else // scaleType() == stLogarithmic
  9963. {
  9964. newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  9965. newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  9966. }
  9967. }
  9968. valueAxis->setRange(newRange);
  9969. }
  9970. }
  9971. /*! \overload
  9972. Adds this plottable to the specified \a legend.
  9973. Creates a QCPPlottableLegendItem which is inserted into the legend. Returns true on success, i.e.
  9974. when the legend exists and a legend item associated with this plottable isn't already in the
  9975. legend.
  9976. If the plottable needs a more specialized representation in the legend, you can create a
  9977. corresponding subclass of \ref QCPPlottableLegendItem and add it to the legend manually instead
  9978. of calling this method.
  9979. \see removeFromLegend, QCPLegend::addItem
  9980. */
  9981. bool QCPAbstractPlottable::addToLegend(QCPLegend *legend)
  9982. {
  9983. if (!legend)
  9984. {
  9985. qDebug() << Q_FUNC_INFO << "passed legend is null";
  9986. return false;
  9987. }
  9988. if (legend->parentPlot() != mParentPlot)
  9989. {
  9990. qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable";
  9991. return false;
  9992. }
  9993. if (!legend->hasItemWithPlottable(this))
  9994. {
  9995. legend->addItem(new QCPPlottableLegendItem(legend, this));
  9996. return true;
  9997. } else
  9998. return false;
  9999. }
  10000. /*! \overload
  10001. Adds this plottable to the legend of the parent QCustomPlot (\ref QCustomPlot::legend).
  10002. \see removeFromLegend
  10003. */
  10004. bool QCPAbstractPlottable::addToLegend()
  10005. {
  10006. if (!mParentPlot || !mParentPlot->legend)
  10007. return false;
  10008. else
  10009. return addToLegend(mParentPlot->legend);
  10010. }
  10011. /*! \overload
  10012. Removes the plottable from the specifed \a legend. This means the \ref QCPPlottableLegendItem
  10013. that is associated with this plottable is removed.
  10014. Returns true on success, i.e. if the legend exists and a legend item associated with this
  10015. plottable was found and removed.
  10016. \see addToLegend, QCPLegend::removeItem
  10017. */
  10018. bool QCPAbstractPlottable::removeFromLegend(QCPLegend *legend) const
  10019. {
  10020. if (!legend)
  10021. {
  10022. qDebug() << Q_FUNC_INFO << "passed legend is null";
  10023. return false;
  10024. }
  10025. if (QCPPlottableLegendItem *lip = legend->itemWithPlottable(this))
  10026. return legend->removeItem(lip);
  10027. else
  10028. return false;
  10029. }
  10030. /*! \overload
  10031. Removes the plottable from the legend of the parent QCustomPlot.
  10032. \see addToLegend
  10033. */
  10034. bool QCPAbstractPlottable::removeFromLegend() const
  10035. {
  10036. if (!mParentPlot || !mParentPlot->legend)
  10037. return false;
  10038. else
  10039. return removeFromLegend(mParentPlot->legend);
  10040. }
  10041. /* inherits documentation from base class */
  10042. QRect QCPAbstractPlottable::clipRect() const
  10043. {
  10044. if (mKeyAxis && mValueAxis)
  10045. return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect();
  10046. else
  10047. return {};
  10048. }
  10049. /* inherits documentation from base class */
  10050. QCP::Interaction QCPAbstractPlottable::selectionCategory() const
  10051. {
  10052. return QCP::iSelectPlottables;
  10053. }
  10054. /*! \internal
  10055. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  10056. before drawing plottable lines.
  10057. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  10058. This function takes into account the local setting of the antialiasing flag as well as the
  10059. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  10060. QCustomPlot::setNotAntialiasedElements.
  10061. \seebaseclassmethod
  10062. \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint
  10063. */
  10064. void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const
  10065. {
  10066. applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables);
  10067. }
  10068. /*! \internal
  10069. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  10070. before drawing plottable fills.
  10071. This function takes into account the local setting of the antialiasing flag as well as the
  10072. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  10073. QCustomPlot::setNotAntialiasedElements.
  10074. \see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint
  10075. */
  10076. void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const
  10077. {
  10078. applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills);
  10079. }
  10080. /*! \internal
  10081. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  10082. before drawing plottable scatter points.
  10083. This function takes into account the local setting of the antialiasing flag as well as the
  10084. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  10085. QCustomPlot::setNotAntialiasedElements.
  10086. \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint
  10087. */
  10088. void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const
  10089. {
  10090. applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
  10091. }
  10092. /* inherits documentation from base class */
  10093. void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  10094. {
  10095. Q_UNUSED(event)
  10096. if (mSelectable != QCP::stNone)
  10097. {
  10098. QCPDataSelection newSelection = details.value<QCPDataSelection>();
  10099. QCPDataSelection selectionBefore = mSelection;
  10100. if (additive)
  10101. {
  10102. if (mSelectable == QCP::stWhole) // in whole selection mode, we toggle to no selection even if currently unselected point was hit
  10103. {
  10104. if (selected())
  10105. setSelection(QCPDataSelection());
  10106. else
  10107. setSelection(newSelection);
  10108. } else // in all other selection modes we toggle selections of homogeneously selected/unselected segments
  10109. {
  10110. if (mSelection.contains(newSelection)) // if entire newSelection is already selected, toggle selection
  10111. setSelection(mSelection-newSelection);
  10112. else
  10113. setSelection(mSelection+newSelection);
  10114. }
  10115. } else
  10116. setSelection(newSelection);
  10117. if (selectionStateChanged)
  10118. *selectionStateChanged = mSelection != selectionBefore;
  10119. }
  10120. }
  10121. /* inherits documentation from base class */
  10122. void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged)
  10123. {
  10124. if (mSelectable != QCP::stNone)
  10125. {
  10126. QCPDataSelection selectionBefore = mSelection;
  10127. setSelection(QCPDataSelection());
  10128. if (selectionStateChanged)
  10129. *selectionStateChanged = mSelection != selectionBefore;
  10130. }
  10131. }
  10132. /* end of 'src/plottable.cpp' */
  10133. /* including file 'src/item.cpp' */
  10134. /* modified 2022-11-06T12:45:56, size 49486 */
  10135. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10136. //////////////////// QCPItemAnchor
  10137. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10138. /*! \class QCPItemAnchor
  10139. \brief An anchor of an item to which positions can be attached to.
  10140. An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't
  10141. control anything on its item, but provides a way to tie other items via their positions to the
  10142. anchor.
  10143. For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight.
  10144. Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can
  10145. attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by
  10146. calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the
  10147. QCPItemRect. This way the start of the line will now always follow the respective anchor location
  10148. on the rect item.
  10149. Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an
  10150. anchor to other positions.
  10151. To learn how to provide anchors in your own item subclasses, see the subclassing section of the
  10152. QCPAbstractItem documentation.
  10153. */
  10154. /* start documentation of inline functions */
  10155. /*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition()
  10156. Returns \c nullptr if this instance is merely a QCPItemAnchor, and a valid pointer of type
  10157. QCPItemPosition* if it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor).
  10158. This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids
  10159. dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with
  10160. gcc compiler).
  10161. */
  10162. /* end documentation of inline functions */
  10163. /*!
  10164. Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if
  10165. you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as
  10166. explained in the subclassing section of the QCPAbstractItem documentation.
  10167. */
  10168. QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId) :
  10169. mName(name),
  10170. mParentPlot(parentPlot),
  10171. mParentItem(parentItem),
  10172. mAnchorId(anchorId)
  10173. {
  10174. }
  10175. QCPItemAnchor::~QCPItemAnchor()
  10176. {
  10177. // unregister as parent at children:
  10178. foreach (QCPItemPosition *child, mChildrenX.values())
  10179. {
  10180. if (child->parentAnchorX() == this)
  10181. child->setParentAnchorX(nullptr); // this acts back on this anchor and child removes itself from mChildrenX
  10182. }
  10183. foreach (QCPItemPosition *child, mChildrenY.values())
  10184. {
  10185. if (child->parentAnchorY() == this)
  10186. child->setParentAnchorY(nullptr); // this acts back on this anchor and child removes itself from mChildrenY
  10187. }
  10188. }
  10189. /*!
  10190. Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface.
  10191. The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the
  10192. parent item, QCPItemAnchor is just an intermediary.
  10193. */
  10194. QPointF QCPItemAnchor::pixelPosition() const
  10195. {
  10196. if (mParentItem)
  10197. {
  10198. if (mAnchorId > -1)
  10199. {
  10200. return mParentItem->anchorPixelPosition(mAnchorId);
  10201. } else
  10202. {
  10203. qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId;
  10204. return {};
  10205. }
  10206. } else
  10207. {
  10208. qDebug() << Q_FUNC_INFO << "no parent item set";
  10209. return {};
  10210. }
  10211. }
  10212. /*! \internal
  10213. Adds \a pos to the childX list of this anchor, which keeps track of which children use this
  10214. anchor as parent anchor for the respective coordinate. This is necessary to notify the children
  10215. prior to destruction of the anchor.
  10216. Note that this function does not change the parent setting in \a pos.
  10217. */
  10218. void QCPItemAnchor::addChildX(QCPItemPosition *pos)
  10219. {
  10220. if (!mChildrenX.contains(pos))
  10221. mChildrenX.insert(pos);
  10222. else
  10223. qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
  10224. }
  10225. /*! \internal
  10226. Removes \a pos from the childX list of this anchor.
  10227. Note that this function does not change the parent setting in \a pos.
  10228. */
  10229. void QCPItemAnchor::removeChildX(QCPItemPosition *pos)
  10230. {
  10231. if (!mChildrenX.remove(pos))
  10232. qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
  10233. }
  10234. /*! \internal
  10235. Adds \a pos to the childY list of this anchor, which keeps track of which children use this
  10236. anchor as parent anchor for the respective coordinate. This is necessary to notify the children
  10237. prior to destruction of the anchor.
  10238. Note that this function does not change the parent setting in \a pos.
  10239. */
  10240. void QCPItemAnchor::addChildY(QCPItemPosition *pos)
  10241. {
  10242. if (!mChildrenY.contains(pos))
  10243. mChildrenY.insert(pos);
  10244. else
  10245. qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
  10246. }
  10247. /*! \internal
  10248. Removes \a pos from the childY list of this anchor.
  10249. Note that this function does not change the parent setting in \a pos.
  10250. */
  10251. void QCPItemAnchor::removeChildY(QCPItemPosition *pos)
  10252. {
  10253. if (!mChildrenY.remove(pos))
  10254. qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
  10255. }
  10256. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10257. //////////////////// QCPItemPosition
  10258. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10259. /*! \class QCPItemPosition
  10260. \brief Manages the position of an item.
  10261. Every item has at least one public QCPItemPosition member pointer which provides ways to position the
  10262. item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two:
  10263. \a topLeft and \a bottomRight.
  10264. QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type
  10265. defines how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel
  10266. coordinates, as plot coordinates of certain axes (\ref QCPItemPosition::setAxes), as fractions of
  10267. the axis rect (\ref QCPItemPosition::setAxisRect), etc. For more advanced plots it is also
  10268. possible to assign different types per X/Y coordinate of the position (see \ref setTypeX, \ref
  10269. setTypeY). This way an item could be positioned for example at a fixed pixel distance from the
  10270. top in the Y direction, while following a plot coordinate in the X direction.
  10271. A QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. This way you can tie
  10272. multiple items together. If the QCPItemPosition has a parent, its coordinates (\ref setCoords)
  10273. are considered to be absolute pixels in the reference frame of the parent anchor, where (0, 0)
  10274. means directly ontop of the parent anchor. For example, You could attach the \a start position of
  10275. a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting point of the line
  10276. always be centered under the text label, no matter where the text is moved to. For more advanced
  10277. plots, it is possible to assign different parent anchors per X/Y coordinate of the position, see
  10278. \ref setParentAnchorX, \ref setParentAnchorY. This way an item could follow another item in the X
  10279. direction but stay at a fixed position in the Y direction. Or even follow item A in X, and item B
  10280. in Y.
  10281. Note that every QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent
  10282. anchor for other positions.
  10283. To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPosition. This
  10284. works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref
  10285. setPixelPosition transforms the coordinates appropriately, to make the position appear at the specified
  10286. pixel values.
  10287. */
  10288. /* start documentation of inline functions */
  10289. /*! \fn QCPItemPosition::PositionType *QCPItemPosition::type() const
  10290. Returns the current position type.
  10291. If different types were set for X and Y (\ref setTypeX, \ref setTypeY), this method returns the
  10292. type of the X coordinate. In that case rather use \a typeX() and \a typeY().
  10293. \see setType
  10294. */
  10295. /*! \fn QCPItemAnchor *QCPItemPosition::parentAnchor() const
  10296. Returns the current parent anchor.
  10297. If different parent anchors were set for X and Y (\ref setParentAnchorX, \ref setParentAnchorY),
  10298. this method returns the parent anchor of the Y coordinate. In that case rather use \a
  10299. parentAnchorX() and \a parentAnchorY().
  10300. \see setParentAnchor
  10301. */
  10302. /* end documentation of inline functions */
  10303. /*!
  10304. Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if
  10305. you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as
  10306. explained in the subclassing section of the QCPAbstractItem documentation.
  10307. */
  10308. QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name) :
  10309. QCPItemAnchor(parentPlot, parentItem, name),
  10310. mPositionTypeX(ptAbsolute),
  10311. mPositionTypeY(ptAbsolute),
  10312. mKey(0),
  10313. mValue(0),
  10314. mParentAnchorX(nullptr),
  10315. mParentAnchorY(nullptr)
  10316. {
  10317. }
  10318. QCPItemPosition::~QCPItemPosition()
  10319. {
  10320. // unregister as parent at children:
  10321. // Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then
  10322. // the setParentAnchor(0) call the correct QCPItemPosition::pixelPosition function instead of QCPItemAnchor::pixelPosition
  10323. foreach (QCPItemPosition *child, mChildrenX.values())
  10324. {
  10325. if (child->parentAnchorX() == this)
  10326. child->setParentAnchorX(nullptr); // this acts back on this anchor and child removes itself from mChildrenX
  10327. }
  10328. foreach (QCPItemPosition *child, mChildrenY.values())
  10329. {
  10330. if (child->parentAnchorY() == this)
  10331. child->setParentAnchorY(nullptr); // this acts back on this anchor and child removes itself from mChildrenY
  10332. }
  10333. // unregister as child in parent:
  10334. if (mParentAnchorX)
  10335. mParentAnchorX->removeChildX(this);
  10336. if (mParentAnchorY)
  10337. mParentAnchorY->removeChildY(this);
  10338. }
  10339. /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
  10340. QCPAxisRect *QCPItemPosition::axisRect() const
  10341. {
  10342. return mAxisRect.data();
  10343. }
  10344. /*!
  10345. Sets the type of the position. The type defines how the coordinates passed to \ref setCoords
  10346. should be handled and how the QCPItemPosition should behave in the plot.
  10347. The possible values for \a type can be separated in two main categories:
  10348. \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords
  10349. and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes.
  10350. By default, the QCustomPlot's x- and yAxis are used.
  10351. \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This
  10352. corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref
  10353. ptAxisRectRatio. They differ only in the way the absolute position is described, see the
  10354. documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify
  10355. the axis rect with \ref setAxisRect. By default this is set to the main axis rect.
  10356. Note that the position type \ref ptPlotCoords is only available (and sensible) when the position
  10357. has no parent anchor (\ref setParentAnchor).
  10358. If the type is changed, the apparent pixel position on the plot is preserved. This means
  10359. the coordinates as retrieved with coords() and set with \ref setCoords may change in the process.
  10360. This method sets the type for both X and Y directions. It is also possible to set different types
  10361. for X and Y, see \ref setTypeX, \ref setTypeY.
  10362. */
  10363. void QCPItemPosition::setType(QCPItemPosition::PositionType type)
  10364. {
  10365. setTypeX(type);
  10366. setTypeY(type);
  10367. }
  10368. /*!
  10369. This method sets the position type of the X coordinate to \a type.
  10370. For a detailed description of what a position type is, see the documentation of \ref setType.
  10371. \see setType, setTypeY
  10372. */
  10373. void QCPItemPosition::setTypeX(QCPItemPosition::PositionType type)
  10374. {
  10375. if (mPositionTypeX != type)
  10376. {
  10377. // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
  10378. // were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning.
  10379. bool retainPixelPosition = true;
  10380. if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
  10381. retainPixelPosition = false;
  10382. if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
  10383. retainPixelPosition = false;
  10384. QPointF pixel;
  10385. if (retainPixelPosition)
  10386. pixel = pixelPosition();
  10387. mPositionTypeX = type;
  10388. if (retainPixelPosition)
  10389. setPixelPosition(pixel);
  10390. }
  10391. }
  10392. /*!
  10393. This method sets the position type of the Y coordinate to \a type.
  10394. For a detailed description of what a position type is, see the documentation of \ref setType.
  10395. \see setType, setTypeX
  10396. */
  10397. void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type)
  10398. {
  10399. if (mPositionTypeY != type)
  10400. {
  10401. // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
  10402. // were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning.
  10403. bool retainPixelPosition = true;
  10404. if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
  10405. retainPixelPosition = false;
  10406. if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
  10407. retainPixelPosition = false;
  10408. QPointF pixel;
  10409. if (retainPixelPosition)
  10410. pixel = pixelPosition();
  10411. mPositionTypeY = type;
  10412. if (retainPixelPosition)
  10413. setPixelPosition(pixel);
  10414. }
  10415. }
  10416. /*!
  10417. Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now
  10418. follow any position changes of the anchor. The local coordinate system of positions with a parent
  10419. anchor always is absolute pixels, with (0, 0) being exactly on top of the parent anchor. (Hence
  10420. the type shouldn't be set to \ref ptPlotCoords for positions with parent anchors.)
  10421. if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved
  10422. during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position
  10423. will be exactly on top of the parent anchor.
  10424. To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to \c nullptr.
  10425. If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is
  10426. set to \ref ptAbsolute, to keep the position in a valid state.
  10427. This method sets the parent anchor for both X and Y directions. It is also possible to set
  10428. different parents for X and Y, see \ref setParentAnchorX, \ref setParentAnchorY.
  10429. */
  10430. bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
  10431. {
  10432. bool successX = setParentAnchorX(parentAnchor, keepPixelPosition);
  10433. bool successY = setParentAnchorY(parentAnchor, keepPixelPosition);
  10434. return successX && successY;
  10435. }
  10436. /*!
  10437. This method sets the parent anchor of the X coordinate to \a parentAnchor.
  10438. For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor.
  10439. \see setParentAnchor, setParentAnchorY
  10440. */
  10441. bool QCPItemPosition::setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
  10442. {
  10443. // make sure self is not assigned as parent:
  10444. if (parentAnchor == this)
  10445. {
  10446. qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
  10447. return false;
  10448. }
  10449. // make sure no recursive parent-child-relationships are created:
  10450. QCPItemAnchor *currentParent = parentAnchor;
  10451. while (currentParent)
  10452. {
  10453. if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
  10454. {
  10455. // is a QCPItemPosition, might have further parent, so keep iterating
  10456. if (currentParentPos == this)
  10457. {
  10458. qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
  10459. return false;
  10460. }
  10461. currentParent = currentParentPos->parentAnchorX();
  10462. } else
  10463. {
  10464. // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
  10465. // same, to prevent a position being child of an anchor which itself depends on the position,
  10466. // because they're both on the same item:
  10467. if (currentParent->mParentItem == mParentItem)
  10468. {
  10469. qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
  10470. return false;
  10471. }
  10472. break;
  10473. }
  10474. }
  10475. // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
  10476. if (!mParentAnchorX && mPositionTypeX == ptPlotCoords)
  10477. setTypeX(ptAbsolute);
  10478. // save pixel position:
  10479. QPointF pixelP;
  10480. if (keepPixelPosition)
  10481. pixelP = pixelPosition();
  10482. // unregister at current parent anchor:
  10483. if (mParentAnchorX)
  10484. mParentAnchorX->removeChildX(this);
  10485. // register at new parent anchor:
  10486. if (parentAnchor)
  10487. parentAnchor->addChildX(this);
  10488. mParentAnchorX = parentAnchor;
  10489. // restore pixel position under new parent:
  10490. if (keepPixelPosition)
  10491. setPixelPosition(pixelP);
  10492. else
  10493. setCoords(0, coords().y());
  10494. return true;
  10495. }
  10496. /*!
  10497. This method sets the parent anchor of the Y coordinate to \a parentAnchor.
  10498. For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor.
  10499. \see setParentAnchor, setParentAnchorX
  10500. */
  10501. bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
  10502. {
  10503. // make sure self is not assigned as parent:
  10504. if (parentAnchor == this)
  10505. {
  10506. qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
  10507. return false;
  10508. }
  10509. // make sure no recursive parent-child-relationships are created:
  10510. QCPItemAnchor *currentParent = parentAnchor;
  10511. while (currentParent)
  10512. {
  10513. if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
  10514. {
  10515. // is a QCPItemPosition, might have further parent, so keep iterating
  10516. if (currentParentPos == this)
  10517. {
  10518. qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
  10519. return false;
  10520. }
  10521. currentParent = currentParentPos->parentAnchorY();
  10522. } else
  10523. {
  10524. // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
  10525. // same, to prevent a position being child of an anchor which itself depends on the position,
  10526. // because they're both on the same item:
  10527. if (currentParent->mParentItem == mParentItem)
  10528. {
  10529. qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
  10530. return false;
  10531. }
  10532. break;
  10533. }
  10534. }
  10535. // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
  10536. if (!mParentAnchorY && mPositionTypeY == ptPlotCoords)
  10537. setTypeY(ptAbsolute);
  10538. // save pixel position:
  10539. QPointF pixelP;
  10540. if (keepPixelPosition)
  10541. pixelP = pixelPosition();
  10542. // unregister at current parent anchor:
  10543. if (mParentAnchorY)
  10544. mParentAnchorY->removeChildY(this);
  10545. // register at new parent anchor:
  10546. if (parentAnchor)
  10547. parentAnchor->addChildY(this);
  10548. mParentAnchorY = parentAnchor;
  10549. // restore pixel position under new parent:
  10550. if (keepPixelPosition)
  10551. setPixelPosition(pixelP);
  10552. else
  10553. setCoords(coords().x(), 0);
  10554. return true;
  10555. }
  10556. /*!
  10557. Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type
  10558. (\ref setType, \ref setTypeX, \ref setTypeY).
  10559. For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position
  10560. on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the
  10561. QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the
  10562. plot coordinate system defined by the axes set by \ref setAxes. By default those are the
  10563. QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available
  10564. coordinate types and their meaning.
  10565. If different types were configured for X and Y (\ref setTypeX, \ref setTypeY), \a key and \a
  10566. value must also be provided in the different coordinate systems. Here, the X type refers to \a
  10567. key, and the Y type refers to \a value.
  10568. \see setPixelPosition
  10569. */
  10570. void QCPItemPosition::setCoords(double key, double value)
  10571. {
  10572. mKey = key;
  10573. mValue = value;
  10574. }
  10575. /*! \overload
  10576. Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the
  10577. meaning of \a value of the \ref setCoords(double key, double value) method.
  10578. */
  10579. void QCPItemPosition::setCoords(const QPointF &pos)
  10580. {
  10581. setCoords(pos.x(), pos.y());
  10582. }
  10583. /*!
  10584. Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It
  10585. includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor).
  10586. \see setPixelPosition
  10587. */
  10588. QPointF QCPItemPosition::pixelPosition() const
  10589. {
  10590. QPointF result;
  10591. // determine X:
  10592. switch (mPositionTypeX)
  10593. {
  10594. case ptAbsolute:
  10595. {
  10596. result.rx() = mKey;
  10597. if (mParentAnchorX)
  10598. result.rx() += mParentAnchorX->pixelPosition().x();
  10599. break;
  10600. }
  10601. case ptViewportRatio:
  10602. {
  10603. result.rx() = mKey*mParentPlot->viewport().width();
  10604. if (mParentAnchorX)
  10605. result.rx() += mParentAnchorX->pixelPosition().x();
  10606. else
  10607. result.rx() += mParentPlot->viewport().left();
  10608. break;
  10609. }
  10610. case ptAxisRectRatio:
  10611. {
  10612. if (mAxisRect)
  10613. {
  10614. result.rx() = mKey*mAxisRect.data()->width();
  10615. if (mParentAnchorX)
  10616. result.rx() += mParentAnchorX->pixelPosition().x();
  10617. else
  10618. result.rx() += mAxisRect.data()->left();
  10619. } else
  10620. qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
  10621. break;
  10622. }
  10623. case ptPlotCoords:
  10624. {
  10625. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
  10626. result.rx() = mKeyAxis.data()->coordToPixel(mKey);
  10627. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
  10628. result.rx() = mValueAxis.data()->coordToPixel(mValue);
  10629. else
  10630. qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined";
  10631. break;
  10632. }
  10633. }
  10634. // determine Y:
  10635. switch (mPositionTypeY)
  10636. {
  10637. case ptAbsolute:
  10638. {
  10639. result.ry() = mValue;
  10640. if (mParentAnchorY)
  10641. result.ry() += mParentAnchorY->pixelPosition().y();
  10642. break;
  10643. }
  10644. case ptViewportRatio:
  10645. {
  10646. result.ry() = mValue*mParentPlot->viewport().height();
  10647. if (mParentAnchorY)
  10648. result.ry() += mParentAnchorY->pixelPosition().y();
  10649. else
  10650. result.ry() += mParentPlot->viewport().top();
  10651. break;
  10652. }
  10653. case ptAxisRectRatio:
  10654. {
  10655. if (mAxisRect)
  10656. {
  10657. result.ry() = mValue*mAxisRect.data()->height();
  10658. if (mParentAnchorY)
  10659. result.ry() += mParentAnchorY->pixelPosition().y();
  10660. else
  10661. result.ry() += mAxisRect.data()->top();
  10662. } else
  10663. qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
  10664. break;
  10665. }
  10666. case ptPlotCoords:
  10667. {
  10668. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
  10669. result.ry() = mKeyAxis.data()->coordToPixel(mKey);
  10670. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
  10671. result.ry() = mValueAxis.data()->coordToPixel(mValue);
  10672. else
  10673. qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined";
  10674. break;
  10675. }
  10676. }
  10677. return result;
  10678. }
  10679. /*!
  10680. When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the
  10681. coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and
  10682. yAxis of the QCustomPlot.
  10683. */
  10684. void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis)
  10685. {
  10686. mKeyAxis = keyAxis;
  10687. mValueAxis = valueAxis;
  10688. }
  10689. /*!
  10690. When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the
  10691. coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of
  10692. the QCustomPlot.
  10693. */
  10694. void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect)
  10695. {
  10696. mAxisRect = axisRect;
  10697. }
  10698. /*!
  10699. Sets the apparent pixel position. This works no matter what type (\ref setType) this
  10700. QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed
  10701. appropriately, to make the position finally appear at the specified pixel values.
  10702. Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is
  10703. identical to that of \ref setCoords.
  10704. \see pixelPosition, setCoords
  10705. */
  10706. void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition)
  10707. {
  10708. double x = pixelPosition.x();
  10709. double y = pixelPosition.y();
  10710. switch (mPositionTypeX)
  10711. {
  10712. case ptAbsolute:
  10713. {
  10714. if (mParentAnchorX)
  10715. x -= mParentAnchorX->pixelPosition().x();
  10716. break;
  10717. }
  10718. case ptViewportRatio:
  10719. {
  10720. if (mParentAnchorX)
  10721. x -= mParentAnchorX->pixelPosition().x();
  10722. else
  10723. x -= mParentPlot->viewport().left();
  10724. x /= double(mParentPlot->viewport().width());
  10725. break;
  10726. }
  10727. case ptAxisRectRatio:
  10728. {
  10729. if (mAxisRect)
  10730. {
  10731. if (mParentAnchorX)
  10732. x -= mParentAnchorX->pixelPosition().x();
  10733. else
  10734. x -= mAxisRect.data()->left();
  10735. x /= double(mAxisRect.data()->width());
  10736. } else
  10737. qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
  10738. break;
  10739. }
  10740. case ptPlotCoords:
  10741. {
  10742. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
  10743. x = mKeyAxis.data()->pixelToCoord(x);
  10744. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
  10745. y = mValueAxis.data()->pixelToCoord(x);
  10746. else
  10747. qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined";
  10748. break;
  10749. }
  10750. }
  10751. switch (mPositionTypeY)
  10752. {
  10753. case ptAbsolute:
  10754. {
  10755. if (mParentAnchorY)
  10756. y -= mParentAnchorY->pixelPosition().y();
  10757. break;
  10758. }
  10759. case ptViewportRatio:
  10760. {
  10761. if (mParentAnchorY)
  10762. y -= mParentAnchorY->pixelPosition().y();
  10763. else
  10764. y -= mParentPlot->viewport().top();
  10765. y /= double(mParentPlot->viewport().height());
  10766. break;
  10767. }
  10768. case ptAxisRectRatio:
  10769. {
  10770. if (mAxisRect)
  10771. {
  10772. if (mParentAnchorY)
  10773. y -= mParentAnchorY->pixelPosition().y();
  10774. else
  10775. y -= mAxisRect.data()->top();
  10776. y /= double(mAxisRect.data()->height());
  10777. } else
  10778. qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
  10779. break;
  10780. }
  10781. case ptPlotCoords:
  10782. {
  10783. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
  10784. x = mKeyAxis.data()->pixelToCoord(y);
  10785. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
  10786. y = mValueAxis.data()->pixelToCoord(y);
  10787. else
  10788. qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined";
  10789. break;
  10790. }
  10791. }
  10792. setCoords(x, y);
  10793. }
  10794. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10795. //////////////////// QCPAbstractItem
  10796. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10797. /*! \class QCPAbstractItem
  10798. \brief The abstract base class for all items in a plot.
  10799. In QCustomPlot, items are supplemental graphical elements that are neither plottables
  10800. (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus
  10801. plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each
  10802. specific item has at least one QCPItemPosition member which controls the positioning. Some items
  10803. are defined by more than one coordinate and thus have two or more QCPItemPosition members (For
  10804. example, QCPItemRect has \a topLeft and \a bottomRight).
  10805. This abstract base class defines a very basic interface like visibility and clipping. Since this
  10806. class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass
  10807. yourself to create new items.
  10808. The built-in items are:
  10809. <table>
  10810. <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>
  10811. <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>
  10812. <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>
  10813. <tr><td>QCPItemRect</td><td>A rectangle</td></tr>
  10814. <tr><td>QCPItemEllipse</td><td>An ellipse</td></tr>
  10815. <tr><td>QCPItemPixmap</td><td>An arbitrary pixmap</td></tr>
  10816. <tr><td>QCPItemText</td><td>A text label</td></tr>
  10817. <tr><td>QCPItemBracket</td><td>A bracket which may be used to reference/highlight certain parts in the plot.</td></tr>
  10818. <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>
  10819. </table>
  10820. \section items-clipping Clipping
  10821. Items are by default clipped to the main axis rect (they are only visible inside the axis rect).
  10822. To make an item visible outside that axis rect, disable clipping via \ref setClipToAxisRect
  10823. "setClipToAxisRect(false)".
  10824. On the other hand if you want the item to be clipped to a different axis rect, specify it via
  10825. \ref setClipAxisRect. This clipAxisRect property of an item is only used for clipping behaviour, and
  10826. in principle is independent of the coordinate axes the item might be tied to via its position
  10827. members (\ref QCPItemPosition::setAxes). However, it is common that the axis rect for clipping
  10828. also contains the axes used for the item positions.
  10829. \section items-using Using items
  10830. First you instantiate the item you want to use and add it to the plot:
  10831. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-1
  10832. by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just
  10833. set the plot coordinates where the line should start/end:
  10834. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-2
  10835. If we don't want the line to be positioned in plot coordinates but a different coordinate system,
  10836. e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like this:
  10837. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-3
  10838. Then we can set the coordinates, this time in pixels:
  10839. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-4
  10840. and make the line visible on the entire QCustomPlot, by disabling clipping to the axis rect:
  10841. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-5
  10842. For more advanced plots, it is even possible to set different types and parent anchors per X/Y
  10843. coordinate of an item position, using for example \ref QCPItemPosition::setTypeX or \ref
  10844. QCPItemPosition::setParentAnchorX. For details, see the documentation of \ref QCPItemPosition.
  10845. \section items-subclassing Creating own items
  10846. To create an own item, you implement a subclass of QCPAbstractItem. These are the pure
  10847. virtual functions, you must implement:
  10848. \li \ref selectTest
  10849. \li \ref draw
  10850. See the documentation of those functions for what they need to do.
  10851. \subsection items-positioning Allowing the item to be positioned
  10852. As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall
  10853. have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add
  10854. a public member of type QCPItemPosition like so:
  10855. \code QCPItemPosition * const myPosition;\endcode
  10856. the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition
  10857. instance it points to, can be modified, of course).
  10858. The initialization of this pointer is made easy with the \ref createPosition function. Just assign
  10859. the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition
  10860. takes a string which is the name of the position, typically this is identical to the variable name.
  10861. For example, the constructor of QCPItemExample could look like this:
  10862. \code
  10863. QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) :
  10864. QCPAbstractItem(parentPlot),
  10865. myPosition(createPosition("myPosition"))
  10866. {
  10867. // other constructor code
  10868. }
  10869. \endcode
  10870. \subsection items-drawing The draw function
  10871. To give your item a visual representation, reimplement the \ref draw function and use the passed
  10872. QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the
  10873. position member(s) via \ref QCPItemPosition::pixelPosition.
  10874. To optimize performance you should calculate a bounding rect first (don't forget to take the pen
  10875. width into account), check whether it intersects the \ref clipRect, and only draw the item at all
  10876. if this is the case.
  10877. \subsection items-selection The selectTest function
  10878. Your implementation of the \ref selectTest function may use the helpers \ref
  10879. QCPVector2D::distanceSquaredToLine and \ref rectDistance. With these, the implementation of the
  10880. selection test becomes significantly simpler for most items. See the documentation of \ref
  10881. selectTest for what the function parameters mean and what the function should return.
  10882. \subsection anchors Providing anchors
  10883. Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public
  10884. member, e.g.
  10885. \code QCPItemAnchor * const bottom;\endcode
  10886. and create it in the constructor with the \ref createAnchor function, assigning it a name and an
  10887. anchor id (an integer enumerating all anchors on the item, you may create an own enum for this).
  10888. Since anchors can be placed anywhere, relative to the item's position(s), your item needs to
  10889. provide the position of every anchor with the reimplementation of the \ref anchorPixelPosition(int
  10890. anchorId) function.
  10891. In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel
  10892. position when anything attached to the anchor needs to know the coordinates.
  10893. */
  10894. /* start of documentation of inline functions */
  10895. /*! \fn QList<QCPItemPosition*> QCPAbstractItem::positions() const
  10896. Returns all positions of the item in a list.
  10897. \see anchors, position
  10898. */
  10899. /*! \fn QList<QCPItemAnchor*> QCPAbstractItem::anchors() const
  10900. Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always
  10901. also an anchor, the list will also contain the positions of this item.
  10902. \see positions, anchor
  10903. */
  10904. /* end of documentation of inline functions */
  10905. /* start documentation of pure virtual functions */
  10906. /*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0
  10907. \internal
  10908. Draws this item with the provided \a painter.
  10909. The cliprect of the provided painter is set to the rect returned by \ref clipRect before this
  10910. function is called. The clipRect depends on the clipping settings defined by \ref
  10911. setClipToAxisRect and \ref setClipAxisRect.
  10912. */
  10913. /* end documentation of pure virtual functions */
  10914. /* start documentation of signals */
  10915. /*! \fn void QCPAbstractItem::selectionChanged(bool selected)
  10916. This signal is emitted when the selection state of this item has changed, either by user interaction
  10917. or by a direct call to \ref setSelected.
  10918. */
  10919. /* end documentation of signals */
  10920. /*!
  10921. Base class constructor which initializes base class members.
  10922. */
  10923. QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) :
  10924. QCPLayerable(parentPlot),
  10925. mClipToAxisRect(false),
  10926. mSelectable(true),
  10927. mSelected(false)
  10928. {
  10929. parentPlot->registerItem(this);
  10930. QList<QCPAxisRect*> rects = parentPlot->axisRects();
  10931. if (!rects.isEmpty())
  10932. {
  10933. setClipToAxisRect(true);
  10934. setClipAxisRect(rects.first());
  10935. }
  10936. }
  10937. QCPAbstractItem::~QCPAbstractItem()
  10938. {
  10939. // don't delete mPositions because every position is also an anchor and thus in mAnchors
  10940. qDeleteAll(mAnchors);
  10941. }
  10942. /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
  10943. QCPAxisRect *QCPAbstractItem::clipAxisRect() const
  10944. {
  10945. return mClipAxisRect.data();
  10946. }
  10947. /*!
  10948. Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the
  10949. entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect.
  10950. \see setClipAxisRect
  10951. */
  10952. void QCPAbstractItem::setClipToAxisRect(bool clip)
  10953. {
  10954. mClipToAxisRect = clip;
  10955. if (mClipToAxisRect)
  10956. setParentLayerable(mClipAxisRect.data());
  10957. }
  10958. /*!
  10959. Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref
  10960. setClipToAxisRect is set to true.
  10961. \see setClipToAxisRect
  10962. */
  10963. void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect)
  10964. {
  10965. mClipAxisRect = rect;
  10966. if (mClipToAxisRect)
  10967. setParentLayerable(mClipAxisRect.data());
  10968. }
  10969. /*!
  10970. Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface.
  10971. (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.)
  10972. However, even when \a selectable was set to false, it is possible to set the selection manually,
  10973. by calling \ref setSelected.
  10974. \see QCustomPlot::setInteractions, setSelected
  10975. */
  10976. void QCPAbstractItem::setSelectable(bool selectable)
  10977. {
  10978. if (mSelectable != selectable)
  10979. {
  10980. mSelectable = selectable;
  10981. emit selectableChanged(mSelectable);
  10982. }
  10983. }
  10984. /*!
  10985. Sets whether this item is selected or not. When selected, it might use a different visual
  10986. appearance (e.g. pen and brush), this depends on the specific item though.
  10987. The entire selection mechanism for items is handled automatically when \ref
  10988. QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this
  10989. function when you wish to change the selection state manually.
  10990. This function can change the selection state even when \ref setSelectable was set to false.
  10991. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  10992. \see setSelectable, selectTest
  10993. */
  10994. void QCPAbstractItem::setSelected(bool selected)
  10995. {
  10996. if (mSelected != selected)
  10997. {
  10998. mSelected = selected;
  10999. emit selectionChanged(mSelected);
  11000. }
  11001. }
  11002. /*!
  11003. Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by
  11004. that name, returns \c nullptr.
  11005. This function provides an alternative way to access item positions. Normally, you access
  11006. positions direcly by their member pointers (which typically have the same variable name as \a
  11007. name).
  11008. \see positions, anchor
  11009. */
  11010. QCPItemPosition *QCPAbstractItem::position(const QString &name) const
  11011. {
  11012. foreach (QCPItemPosition *position, mPositions)
  11013. {
  11014. if (position->name() == name)
  11015. return position;
  11016. }
  11017. qDebug() << Q_FUNC_INFO << "position with name not found:" << name;
  11018. return nullptr;
  11019. }
  11020. /*!
  11021. Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by
  11022. that name, returns \c nullptr.
  11023. This function provides an alternative way to access item anchors. Normally, you access
  11024. anchors direcly by their member pointers (which typically have the same variable name as \a
  11025. name).
  11026. \see anchors, position
  11027. */
  11028. QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const
  11029. {
  11030. foreach (QCPItemAnchor *anchor, mAnchors)
  11031. {
  11032. if (anchor->name() == name)
  11033. return anchor;
  11034. }
  11035. qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name;
  11036. return nullptr;
  11037. }
  11038. /*!
  11039. Returns whether this item has an anchor with the specified \a name.
  11040. Note that you can check for positions with this function, too. This is because every position is
  11041. also an anchor (QCPItemPosition inherits from QCPItemAnchor).
  11042. \see anchor, position
  11043. */
  11044. bool QCPAbstractItem::hasAnchor(const QString &name) const
  11045. {
  11046. foreach (QCPItemAnchor *anchor, mAnchors)
  11047. {
  11048. if (anchor->name() == name)
  11049. return true;
  11050. }
  11051. return false;
  11052. }
  11053. /*! \internal
  11054. Returns the rect the visual representation of this item is clipped to. This depends on the
  11055. current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect.
  11056. If the item is not clipped to an axis rect, QCustomPlot's viewport rect is returned.
  11057. \see draw
  11058. */
  11059. QRect QCPAbstractItem::clipRect() const
  11060. {
  11061. if (mClipToAxisRect && mClipAxisRect)
  11062. return mClipAxisRect.data()->rect();
  11063. else
  11064. return mParentPlot->viewport();
  11065. }
  11066. /*! \internal
  11067. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  11068. before drawing item lines.
  11069. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  11070. This function takes into account the local setting of the antialiasing flag as well as the
  11071. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  11072. QCustomPlot::setNotAntialiasedElements.
  11073. \see setAntialiased
  11074. */
  11075. void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
  11076. {
  11077. applyAntialiasingHint(painter, mAntialiased, QCP::aeItems);
  11078. }
  11079. /*! \internal
  11080. A convenience function which returns the selectTest value for a specified \a rect and a specified
  11081. click position \a pos. \a filledRect defines whether a click inside the rect should also be
  11082. considered a hit or whether only the rect border is sensitive to hits.
  11083. This function may be used to help with the implementation of the \ref selectTest function for
  11084. specific items.
  11085. For example, if your item consists of four rects, call this function four times, once for each
  11086. rect, in your \ref selectTest reimplementation. Finally, return the minimum (non -1) of all four
  11087. returned values.
  11088. */
  11089. double QCPAbstractItem::rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const
  11090. {
  11091. double result = -1;
  11092. // distance to border:
  11093. const QList<QLineF> lines = QList<QLineF>() << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight())
  11094. << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight());
  11095. const QCPVector2D posVec(pos);
  11096. double minDistSqr = (std::numeric_limits<double>::max)();
  11097. foreach (const QLineF &line, lines)
  11098. {
  11099. double distSqr = posVec.distanceSquaredToLine(line.p1(), line.p2());
  11100. if (distSqr < minDistSqr)
  11101. minDistSqr = distSqr;
  11102. }
  11103. result = qSqrt(minDistSqr);
  11104. // filled rect, allow click inside to count as hit:
  11105. if (filledRect && result > mParentPlot->selectionTolerance()*0.99)
  11106. {
  11107. if (rect.contains(pos))
  11108. result = mParentPlot->selectionTolerance()*0.99;
  11109. }
  11110. return result;
  11111. }
  11112. /*! \internal
  11113. Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in
  11114. item subclasses if they want to provide anchors (QCPItemAnchor).
  11115. For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor
  11116. ids and returns the respective pixel points of the specified anchor.
  11117. \see createAnchor
  11118. */
  11119. QPointF QCPAbstractItem::anchorPixelPosition(int anchorId) const
  11120. {
  11121. qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId;
  11122. return {};
  11123. }
  11124. /*! \internal
  11125. Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified
  11126. \a name must be a unique string that is usually identical to the variable name of the position
  11127. member (This is needed to provide the name-based \ref position access to positions).
  11128. Don't delete positions created by this function manually, as the item will take care of it.
  11129. Use this function in the constructor (initialization list) of the specific item subclass to
  11130. create each position member. Don't create QCPItemPositions with \b new yourself, because they
  11131. won't be registered with the item properly.
  11132. \see createAnchor
  11133. */
  11134. QCPItemPosition *QCPAbstractItem::createPosition(const QString &name)
  11135. {
  11136. if (hasAnchor(name))
  11137. qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
  11138. QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name);
  11139. mPositions.append(newPosition);
  11140. mAnchors.append(newPosition); // every position is also an anchor
  11141. newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis);
  11142. newPosition->setType(QCPItemPosition::ptPlotCoords);
  11143. if (mParentPlot->axisRect())
  11144. newPosition->setAxisRect(mParentPlot->axisRect());
  11145. newPosition->setCoords(0, 0);
  11146. return newPosition;
  11147. }
  11148. /*! \internal
  11149. Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified
  11150. \a name must be a unique string that is usually identical to the variable name of the anchor
  11151. member (This is needed to provide the name based \ref anchor access to anchors).
  11152. The \a anchorId must be a number identifying the created anchor. It is recommended to create an
  11153. enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor
  11154. to identify itself when it calls QCPAbstractItem::anchorPixelPosition. That function then returns
  11155. the correct pixel coordinates for the passed anchor id.
  11156. Don't delete anchors created by this function manually, as the item will take care of it.
  11157. Use this function in the constructor (initialization list) of the specific item subclass to
  11158. create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they
  11159. won't be registered with the item properly.
  11160. \see createPosition
  11161. */
  11162. QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId)
  11163. {
  11164. if (hasAnchor(name))
  11165. qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
  11166. QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId);
  11167. mAnchors.append(newAnchor);
  11168. return newAnchor;
  11169. }
  11170. /* inherits documentation from base class */
  11171. void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  11172. {
  11173. Q_UNUSED(event)
  11174. Q_UNUSED(details)
  11175. if (mSelectable)
  11176. {
  11177. bool selBefore = mSelected;
  11178. setSelected(additive ? !mSelected : true);
  11179. if (selectionStateChanged)
  11180. *selectionStateChanged = mSelected != selBefore;
  11181. }
  11182. }
  11183. /* inherits documentation from base class */
  11184. void QCPAbstractItem::deselectEvent(bool *selectionStateChanged)
  11185. {
  11186. if (mSelectable)
  11187. {
  11188. bool selBefore = mSelected;
  11189. setSelected(false);
  11190. if (selectionStateChanged)
  11191. *selectionStateChanged = mSelected != selBefore;
  11192. }
  11193. }
  11194. /* inherits documentation from base class */
  11195. QCP::Interaction QCPAbstractItem::selectionCategory() const
  11196. {
  11197. return QCP::iSelectItems;
  11198. }
  11199. /* end of 'src/item.cpp' */
  11200. /* including file 'src/core.cpp' */
  11201. /* modified 2022-11-06T12:45:56, size 127625 */
  11202. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11203. //////////////////// QCustomPlot
  11204. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11205. /*! \class QCustomPlot
  11206. \brief The central class of the library. This is the QWidget which displays the plot and
  11207. interacts with the user.
  11208. For tutorials on how to use QCustomPlot, see the website\n
  11209. https://www.qcustomplot.com/
  11210. */
  11211. /* start of documentation of inline functions */
  11212. /*! \fn QCPSelectionRect *QCustomPlot::selectionRect() const
  11213. Allows access to the currently used QCPSelectionRect instance (or subclass thereof), that is used
  11214. to handle and draw selection rect interactions (see \ref setSelectionRectMode).
  11215. \see setSelectionRect
  11216. */
  11217. /*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const
  11218. Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just
  11219. one cell with the main QCPAxisRect inside.
  11220. */
  11221. /* end of documentation of inline functions */
  11222. /* start of documentation of signals */
  11223. /*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event)
  11224. This signal is emitted when the QCustomPlot receives a mouse double click event.
  11225. */
  11226. /*! \fn void QCustomPlot::mousePress(QMouseEvent *event)
  11227. This signal is emitted when the QCustomPlot receives a mouse press event.
  11228. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
  11229. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
  11230. QCPAxisRect::setRangeDragAxes.
  11231. */
  11232. /*! \fn void QCustomPlot::mouseMove(QMouseEvent *event)
  11233. This signal is emitted when the QCustomPlot receives a mouse move event.
  11234. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
  11235. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
  11236. QCPAxisRect::setRangeDragAxes.
  11237. \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here,
  11238. because the dragging starting point was saved the moment the mouse was pressed. Thus it only has
  11239. a meaning for the range drag axes that were set at that moment. If you want to change the drag
  11240. axes, consider doing this in the \ref mousePress signal instead.
  11241. */
  11242. /*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event)
  11243. This signal is emitted when the QCustomPlot receives a mouse release event.
  11244. It is emitted before QCustomPlot handles any other mechanisms like object selection. So a
  11245. slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or
  11246. \ref QCPAbstractPlottable::setSelectable.
  11247. */
  11248. /*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event)
  11249. This signal is emitted when the QCustomPlot receives a mouse wheel event.
  11250. It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot
  11251. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref
  11252. QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor.
  11253. */
  11254. /*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event)
  11255. This signal is emitted when a plottable is clicked.
  11256. \a event is the mouse event that caused the click and \a plottable is the plottable that received
  11257. the click. The parameter \a dataIndex indicates the data point that was closest to the click
  11258. position.
  11259. \see plottableDoubleClick
  11260. */
  11261. /*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event)
  11262. This signal is emitted when a plottable is double clicked.
  11263. \a event is the mouse event that caused the click and \a plottable is the plottable that received
  11264. the click. The parameter \a dataIndex indicates the data point that was closest to the click
  11265. position.
  11266. \see plottableClick
  11267. */
  11268. /*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event)
  11269. This signal is emitted when an item is clicked.
  11270. \a event is the mouse event that caused the click and \a item is the item that received the
  11271. click.
  11272. \see itemDoubleClick
  11273. */
  11274. /*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event)
  11275. This signal is emitted when an item is double clicked.
  11276. \a event is the mouse event that caused the click and \a item is the item that received the
  11277. click.
  11278. \see itemClick
  11279. */
  11280. /*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
  11281. This signal is emitted when an axis is clicked.
  11282. \a event is the mouse event that caused the click, \a axis is the axis that received the click and
  11283. \a part indicates the part of the axis that was clicked.
  11284. \see axisDoubleClick
  11285. */
  11286. /*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
  11287. This signal is emitted when an axis is double clicked.
  11288. \a event is the mouse event that caused the click, \a axis is the axis that received the click and
  11289. \a part indicates the part of the axis that was clicked.
  11290. \see axisClick
  11291. */
  11292. /*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
  11293. This signal is emitted when a legend (item) is clicked.
  11294. \a event is the mouse event that caused the click, \a legend is the legend that received the
  11295. click and \a item is the legend item that received the click. If only the legend and no item is
  11296. clicked, \a item is \c nullptr. This happens for a click inside the legend padding or the space
  11297. between two items.
  11298. \see legendDoubleClick
  11299. */
  11300. /*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
  11301. This signal is emitted when a legend (item) is double clicked.
  11302. \a event is the mouse event that caused the click, \a legend is the legend that received the
  11303. click and \a item is the legend item that received the click. If only the legend and no item is
  11304. clicked, \a item is \c nullptr. This happens for a click inside the legend padding or the space
  11305. between two items.
  11306. \see legendClick
  11307. */
  11308. /*! \fn void QCustomPlot::selectionChangedByUser()
  11309. This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by
  11310. clicking. It is not emitted when the selection state of an object has changed programmatically by
  11311. a direct call to <tt>setSelected()</tt>/<tt>setSelection()</tt> on an object or by calling \ref
  11312. deselectAll.
  11313. In addition to this signal, selectable objects also provide individual signals, for example \ref
  11314. QCPAxis::selectionChanged or \ref QCPAbstractPlottable::selectionChanged. Note that those signals
  11315. are emitted even if the selection state is changed programmatically.
  11316. See the documentation of \ref setInteractions for details about the selection mechanism.
  11317. \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends
  11318. */
  11319. /*! \fn void QCustomPlot::beforeReplot()
  11320. This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref
  11321. replot).
  11322. It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
  11323. replot synchronously, it won't cause an infinite recursion.
  11324. \see replot, afterReplot, afterLayout
  11325. */
  11326. /*! \fn void QCustomPlot::afterLayout()
  11327. This signal is emitted immediately after the layout step has been completed, which occurs right
  11328. before drawing the plot. This is typically during a call to \ref replot, and in such cases this
  11329. signal is emitted in between the signals \ref beforeReplot and \ref afterReplot. Unlike those
  11330. signals however, this signal is also emitted during off-screen painting, such as when calling
  11331. \ref toPixmap or \ref savePdf.
  11332. The layout step queries all layouts and layout elements in the plot for their proposed size and
  11333. arranges the objects accordingly as preparation for the subsequent drawing step. Through this
  11334. signal, you have the opportunity to update certain things in your plot that depend crucially on
  11335. the exact dimensions/positioning of layout elements such as axes and axis rects.
  11336. \warning However, changing any parameters of this QCustomPlot instance which would normally
  11337. affect the layouting (e.g. axis range order of magnitudes, tick label sizes, etc.) will not issue
  11338. a second run of the layout step. It will propagate directly to the draw step and may cause
  11339. graphical inconsistencies such as overlapping objects, if sizes or positions have changed.
  11340. \see updateLayout, beforeReplot, afterReplot
  11341. */
  11342. /*! \fn void QCustomPlot::afterReplot()
  11343. This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref
  11344. replot).
  11345. It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
  11346. replot synchronously, it won't cause an infinite recursion.
  11347. \see replot, beforeReplot, afterLayout
  11348. */
  11349. /* end of documentation of signals */
  11350. /* start of documentation of public members */
  11351. /*! \var QCPAxis *QCustomPlot::xAxis
  11352. A pointer to the primary x Axis (bottom) of the main axis rect of the plot.
  11353. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11354. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11355. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11356. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  11357. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  11358. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11359. axis rect), the corresponding pointers become \c nullptr.
  11360. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11361. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11362. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11363. is added after the main legend was removed before.
  11364. */
  11365. /*! \var QCPAxis *QCustomPlot::yAxis
  11366. A pointer to the primary y Axis (left) of the main axis rect of the plot.
  11367. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11368. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11369. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11370. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  11371. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  11372. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11373. axis rect), the corresponding pointers become \c nullptr.
  11374. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11375. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11376. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11377. is added after the main legend was removed before.
  11378. */
  11379. /*! \var QCPAxis *QCustomPlot::xAxis2
  11380. A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are
  11381. invisible by default. Use QCPAxis::setVisible to change this (or use \ref
  11382. QCPAxisRect::setupFullAxesBox).
  11383. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11384. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11385. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11386. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  11387. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  11388. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11389. axis rect), the corresponding pointers become \c nullptr.
  11390. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11391. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11392. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11393. is added after the main legend was removed before.
  11394. */
  11395. /*! \var QCPAxis *QCustomPlot::yAxis2
  11396. A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are
  11397. invisible by default. Use QCPAxis::setVisible to change this (or use \ref
  11398. QCPAxisRect::setupFullAxesBox).
  11399. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11400. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11401. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11402. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  11403. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  11404. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11405. axis rect), the corresponding pointers become \c nullptr.
  11406. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11407. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11408. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11409. is added after the main legend was removed before.
  11410. */
  11411. /*! \var QCPLegend *QCustomPlot::legend
  11412. A pointer to the default legend of the main axis rect. The legend is invisible by default. Use
  11413. QCPLegend::setVisible to change this.
  11414. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11415. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11416. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11417. layout system\endlink to add multiple legends to the plot, use the layout system interface to
  11418. access the new legend. For example, legends can be placed inside an axis rect's \ref
  11419. QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If
  11420. the default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11421. axis rect), the corresponding pointer becomes \c nullptr.
  11422. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11423. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11424. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11425. is added after the main legend was removed before.
  11426. */
  11427. /* end of documentation of public members */
  11428. /*!
  11429. Constructs a QCustomPlot and sets reasonable default values.
  11430. */
  11431. QCustomPlot::QCustomPlot(QWidget *parent) :
  11432. QWidget(parent),
  11433. xAxis(nullptr),
  11434. yAxis(nullptr),
  11435. xAxis2(nullptr),
  11436. yAxis2(nullptr),
  11437. legend(nullptr),
  11438. mBufferDevicePixelRatio(1.0), // will be adapted to true value below
  11439. mPlotLayout(nullptr),
  11440. mAutoAddPlottableToLegend(true),
  11441. mAntialiasedElements(QCP::aeNone),
  11442. mNotAntialiasedElements(QCP::aeNone),
  11443. mInteractions(QCP::iNone),
  11444. mSelectionTolerance(8),
  11445. mNoAntialiasingOnDrag(false),
  11446. mBackgroundBrush(Qt::white, Qt::SolidPattern),
  11447. mBackgroundScaled(true),
  11448. mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
  11449. mCurrentLayer(nullptr),
  11450. mPlottingHints(QCP::phCacheLabels|QCP::phImmediateRefresh),
  11451. mMultiSelectModifier(Qt::ControlModifier),
  11452. mSelectionRectMode(QCP::srmNone),
  11453. mSelectionRect(nullptr),
  11454. mOpenGl(false),
  11455. mMouseHasMoved(false),
  11456. mMouseEventLayerable(nullptr),
  11457. mMouseSignalLayerable(nullptr),
  11458. mReplotting(false),
  11459. mReplotQueued(false),
  11460. mReplotTime(0),
  11461. mReplotTimeAverage(0),
  11462. mOpenGlMultisamples(16),
  11463. mOpenGlAntialiasedElementsBackup(QCP::aeNone),
  11464. mOpenGlCacheLabelsBackup(true)
  11465. {
  11466. setAttribute(Qt::WA_NoMousePropagation);
  11467. setFocusPolicy(Qt::ClickFocus);
  11468. setMouseTracking(true);
  11469. QLocale currentLocale = locale();
  11470. currentLocale.setNumberOptions(QLocale::OmitGroupSeparator);
  11471. setLocale(currentLocale);
  11472. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  11473. # ifdef QCP_DEVICEPIXELRATIO_FLOAT
  11474. setBufferDevicePixelRatio(QWidget::devicePixelRatioF());
  11475. # else
  11476. setBufferDevicePixelRatio(QWidget::devicePixelRatio());
  11477. # endif
  11478. #endif
  11479. mOpenGlAntialiasedElementsBackup = mAntialiasedElements;
  11480. mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels);
  11481. // create initial layers:
  11482. mLayers.append(new QCPLayer(this, QLatin1String("background")));
  11483. mLayers.append(new QCPLayer(this, QLatin1String("grid")));
  11484. mLayers.append(new QCPLayer(this, QLatin1String("main")));
  11485. mLayers.append(new QCPLayer(this, QLatin1String("axes")));
  11486. mLayers.append(new QCPLayer(this, QLatin1String("legend")));
  11487. mLayers.append(new QCPLayer(this, QLatin1String("overlay")));
  11488. updateLayerIndices();
  11489. setCurrentLayer(QLatin1String("main"));
  11490. layer(QLatin1String("overlay"))->setMode(QCPLayer::lmBuffered);
  11491. // create initial layout, axis rect and legend:
  11492. mPlotLayout = new QCPLayoutGrid;
  11493. mPlotLayout->initializeParentPlot(this);
  11494. mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry
  11495. mPlotLayout->setLayer(QLatin1String("main"));
  11496. QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true);
  11497. mPlotLayout->addElement(0, 0, defaultAxisRect);
  11498. xAxis = defaultAxisRect->axis(QCPAxis::atBottom);
  11499. yAxis = defaultAxisRect->axis(QCPAxis::atLeft);
  11500. xAxis2 = defaultAxisRect->axis(QCPAxis::atTop);
  11501. yAxis2 = defaultAxisRect->axis(QCPAxis::atRight);
  11502. legend = new QCPLegend;
  11503. legend->setVisible(false);
  11504. defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop);
  11505. defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12));
  11506. defaultAxisRect->setLayer(QLatin1String("background"));
  11507. xAxis->setLayer(QLatin1String("axes"));
  11508. yAxis->setLayer(QLatin1String("axes"));
  11509. xAxis2->setLayer(QLatin1String("axes"));
  11510. yAxis2->setLayer(QLatin1String("axes"));
  11511. xAxis->grid()->setLayer(QLatin1String("grid"));
  11512. yAxis->grid()->setLayer(QLatin1String("grid"));
  11513. xAxis2->grid()->setLayer(QLatin1String("grid"));
  11514. yAxis2->grid()->setLayer(QLatin1String("grid"));
  11515. legend->setLayer(QLatin1String("legend"));
  11516. // create selection rect instance:
  11517. mSelectionRect = new QCPSelectionRect(this);
  11518. mSelectionRect->setLayer(QLatin1String("overlay"));
  11519. setViewport(rect()); // needs to be called after mPlotLayout has been created
  11520. replot(rpQueuedReplot);
  11521. }
  11522. QCustomPlot::~QCustomPlot()
  11523. {
  11524. clearPlottables();
  11525. clearItems();
  11526. if (mPlotLayout)
  11527. {
  11528. delete mPlotLayout;
  11529. mPlotLayout = nullptr;
  11530. }
  11531. mCurrentLayer = nullptr;
  11532. qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed
  11533. mLayers.clear();
  11534. }
  11535. /*!
  11536. Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement.
  11537. This overrides the antialiasing settings for whole element groups, normally controlled with the
  11538. \a setAntialiasing function on the individual elements. If an element is neither specified in
  11539. \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
  11540. each individual element instance is used.
  11541. For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be
  11542. drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
  11543. to.
  11544. if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is
  11545. removed from there.
  11546. \see setNotAntialiasedElements
  11547. */
  11548. void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements)
  11549. {
  11550. mAntialiasedElements = antialiasedElements;
  11551. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  11552. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  11553. mNotAntialiasedElements |= ~mAntialiasedElements;
  11554. }
  11555. /*!
  11556. Sets whether the specified \a antialiasedElement is forcibly drawn antialiased.
  11557. See \ref setAntialiasedElements for details.
  11558. \see setNotAntialiasedElement
  11559. */
  11560. void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled)
  11561. {
  11562. if (!enabled && mAntialiasedElements.testFlag(antialiasedElement))
  11563. mAntialiasedElements &= ~antialiasedElement;
  11564. else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement))
  11565. mAntialiasedElements |= antialiasedElement;
  11566. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  11567. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  11568. mNotAntialiasedElements |= ~mAntialiasedElements;
  11569. }
  11570. /*!
  11571. Sets which elements are forcibly drawn not antialiased as an \a or combination of
  11572. QCP::AntialiasedElement.
  11573. This overrides the antialiasing settings for whole element groups, normally controlled with the
  11574. \a setAntialiasing function on the individual elements. If an element is neither specified in
  11575. \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
  11576. each individual element instance is used.
  11577. For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be
  11578. drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
  11579. to.
  11580. if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is
  11581. removed from there.
  11582. \see setAntialiasedElements
  11583. */
  11584. void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements &notAntialiasedElements)
  11585. {
  11586. mNotAntialiasedElements = notAntialiasedElements;
  11587. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  11588. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  11589. mAntialiasedElements |= ~mNotAntialiasedElements;
  11590. }
  11591. /*!
  11592. Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased.
  11593. See \ref setNotAntialiasedElements for details.
  11594. \see setAntialiasedElement
  11595. */
  11596. void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled)
  11597. {
  11598. if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement))
  11599. mNotAntialiasedElements &= ~notAntialiasedElement;
  11600. else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement))
  11601. mNotAntialiasedElements |= notAntialiasedElement;
  11602. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  11603. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  11604. mAntialiasedElements |= ~mNotAntialiasedElements;
  11605. }
  11606. /*!
  11607. If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the
  11608. plottable to the legend (QCustomPlot::legend).
  11609. \see addGraph, QCPLegend::addItem
  11610. */
  11611. void QCustomPlot::setAutoAddPlottableToLegend(bool on)
  11612. {
  11613. mAutoAddPlottableToLegend = on;
  11614. }
  11615. /*!
  11616. Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction
  11617. enums. There are the following types of interactions:
  11618. <b>Axis range manipulation</b> is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the
  11619. respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel.
  11620. For details how to control which axes the user may drag/zoom and in what orientations, see \ref
  11621. QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes,
  11622. \ref QCPAxisRect::setRangeZoomAxes.
  11623. <b>Plottable data selection</b> is controlled by \ref QCP::iSelectPlottables. If \ref
  11624. QCP::iSelectPlottables is set, the user may select plottables (graphs, curves, bars,...) and
  11625. their data by clicking on them or in their vicinity (\ref setSelectionTolerance). Whether the
  11626. user can actually select a plottable and its data can further be restricted with the \ref
  11627. QCPAbstractPlottable::setSelectable method on the specific plottable. For details, see the
  11628. special page about the \ref dataselection "data selection mechanism". To retrieve a list of all
  11629. currently selected plottables, call \ref selectedPlottables. If you're only interested in
  11630. QCPGraphs, you may use the convenience function \ref selectedGraphs.
  11631. <b>Item selection</b> is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user
  11632. may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find
  11633. out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of
  11634. all currently selected items, call \ref selectedItems.
  11635. <b>Axis selection</b> is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user
  11636. may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick
  11637. labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for
  11638. each axis. To retrieve a list of all axes that currently contain selected parts, call \ref
  11639. selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts().
  11640. <b>Legend selection</b> is controlled with \ref QCP::iSelectLegend. If this is set, the user may
  11641. select the legend itself or individual items by clicking on them. What parts exactly are
  11642. selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the
  11643. legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To
  11644. find out which child items are selected, call \ref QCPLegend::selectedItems.
  11645. <b>All other selectable elements</b> The selection of all other selectable objects (e.g.
  11646. QCPTextElement, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the
  11647. user may select those objects by clicking on them. To find out which are currently selected, you
  11648. need to check their selected state explicitly.
  11649. If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is
  11650. emitted. Each selectable object additionally emits an individual selectionChanged signal whenever
  11651. their selection state has changed, i.e. not only by user interaction.
  11652. To allow multiple objects to be selected by holding the selection modifier (\ref
  11653. setMultiSelectModifier), set the flag \ref QCP::iMultiSelect.
  11654. \note In addition to the selection mechanism presented here, QCustomPlot always emits
  11655. corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and
  11656. \ref plottableDoubleClick for example.
  11657. \see setInteraction, setSelectionTolerance
  11658. */
  11659. void QCustomPlot::setInteractions(const QCP::Interactions &interactions)
  11660. {
  11661. mInteractions = interactions;
  11662. }
  11663. /*!
  11664. Sets the single \a interaction of this QCustomPlot to \a enabled.
  11665. For details about the interaction system, see \ref setInteractions.
  11666. \see setInteractions
  11667. */
  11668. void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled)
  11669. {
  11670. if (!enabled && mInteractions.testFlag(interaction))
  11671. mInteractions &= ~interaction;
  11672. else if (enabled && !mInteractions.testFlag(interaction))
  11673. mInteractions |= interaction;
  11674. }
  11675. /*!
  11676. Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or
  11677. not.
  11678. If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a
  11679. potential selection when the minimum distance between the click position and the graph line is
  11680. smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks
  11681. directly inside the area and ignore this selection tolerance. In other words, it only has meaning
  11682. for parts of objects that are too thin to exactly hit with a click and thus need such a
  11683. tolerance.
  11684. \see setInteractions, QCPLayerable::selectTest
  11685. */
  11686. void QCustomPlot::setSelectionTolerance(int pixels)
  11687. {
  11688. mSelectionTolerance = pixels;
  11689. }
  11690. /*!
  11691. Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes
  11692. ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves
  11693. performance during dragging. Thus it creates a more responsive user experience. As soon as the
  11694. user stops dragging, the last replot is done with normal antialiasing, to restore high image
  11695. quality.
  11696. \see setAntialiasedElements, setNotAntialiasedElements
  11697. */
  11698. void QCustomPlot::setNoAntialiasingOnDrag(bool enabled)
  11699. {
  11700. mNoAntialiasingOnDrag = enabled;
  11701. }
  11702. /*!
  11703. Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint.
  11704. \see setPlottingHint
  11705. */
  11706. void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints)
  11707. {
  11708. mPlottingHints = hints;
  11709. }
  11710. /*!
  11711. Sets the specified plotting \a hint to \a enabled.
  11712. \see setPlottingHints
  11713. */
  11714. void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled)
  11715. {
  11716. QCP::PlottingHints newHints = mPlottingHints;
  11717. if (!enabled)
  11718. newHints &= ~hint;
  11719. else
  11720. newHints |= hint;
  11721. if (newHints != mPlottingHints)
  11722. setPlottingHints(newHints);
  11723. }
  11724. /*!
  11725. Sets the keyboard modifier that will be recognized as multi-select-modifier.
  11726. If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple
  11727. objects (or data points) by clicking on them one after the other while holding down \a modifier.
  11728. By default the multi-select-modifier is set to Qt::ControlModifier.
  11729. \see setInteractions
  11730. */
  11731. void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier)
  11732. {
  11733. mMultiSelectModifier = modifier;
  11734. }
  11735. /*!
  11736. Sets how QCustomPlot processes mouse click-and-drag interactions by the user.
  11737. If \a mode is \ref QCP::srmNone, the mouse drag is forwarded to the underlying objects. For
  11738. example, QCPAxisRect may process a mouse drag by dragging axis ranges, see \ref
  11739. QCPAxisRect::setRangeDrag. If \a mode is not \ref QCP::srmNone, the current selection rect (\ref
  11740. selectionRect) becomes activated and allows e.g. rect zooming and data point selection.
  11741. If you wish to provide your user both with axis range dragging and data selection/range zooming,
  11742. use this method to switch between the modes just before the interaction is processed, e.g. in
  11743. reaction to the \ref mousePress or \ref mouseMove signals. For example you could check whether
  11744. the user is holding a certain keyboard modifier, and then decide which \a mode shall be set.
  11745. If a selection rect interaction is currently active, and \a mode is set to \ref QCP::srmNone, the
  11746. interaction is canceled (\ref QCPSelectionRect::cancel). Switching between any of the other modes
  11747. will keep the selection rect active. Upon completion of the interaction, the behaviour is as
  11748. defined by the currently set \a mode, not the mode that was set when the interaction started.
  11749. \see setInteractions, setSelectionRect, QCPSelectionRect
  11750. */
  11751. void QCustomPlot::setSelectionRectMode(QCP::SelectionRectMode mode)
  11752. {
  11753. if (mSelectionRect)
  11754. {
  11755. if (mode == QCP::srmNone)
  11756. mSelectionRect->cancel(); // when switching to none, we immediately want to abort a potentially active selection rect
  11757. // disconnect old connections:
  11758. if (mSelectionRectMode == QCP::srmSelect)
  11759. disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
  11760. else if (mSelectionRectMode == QCP::srmZoom)
  11761. disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
  11762. // establish new ones:
  11763. if (mode == QCP::srmSelect)
  11764. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
  11765. else if (mode == QCP::srmZoom)
  11766. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
  11767. }
  11768. mSelectionRectMode = mode;
  11769. }
  11770. /*!
  11771. Sets the \ref QCPSelectionRect instance that QCustomPlot will use if \a mode is not \ref
  11772. QCP::srmNone and the user performs a click-and-drag interaction. QCustomPlot takes ownership of
  11773. the passed \a selectionRect. It can be accessed later via \ref selectionRect.
  11774. This method is useful if you wish to replace the default QCPSelectionRect instance with an
  11775. instance of a QCPSelectionRect subclass, to introduce custom behaviour of the selection rect.
  11776. \see setSelectionRectMode
  11777. */
  11778. void QCustomPlot::setSelectionRect(QCPSelectionRect *selectionRect)
  11779. {
  11780. delete mSelectionRect;
  11781. mSelectionRect = selectionRect;
  11782. if (mSelectionRect)
  11783. {
  11784. // establish connections with new selection rect:
  11785. if (mSelectionRectMode == QCP::srmSelect)
  11786. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
  11787. else if (mSelectionRectMode == QCP::srmZoom)
  11788. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
  11789. }
  11790. }
  11791. /*!
  11792. \warning This is still an experimental feature and its performance depends on the system that it
  11793. runs on. Having multiple QCustomPlot widgets in one application with enabled OpenGL rendering
  11794. might cause context conflicts on some systems.
  11795. This method allows to enable OpenGL plot rendering, for increased plotting performance of
  11796. graphically demanding plots (thick lines, translucent fills, etc.).
  11797. If \a enabled is set to true, QCustomPlot will try to initialize OpenGL and, if successful,
  11798. continue plotting with hardware acceleration. The parameter \a multisampling controls how many
  11799. samples will be used per pixel, it essentially controls the antialiasing quality. If \a
  11800. multisampling is set too high for the current graphics hardware, the maximum allowed value will
  11801. be used.
  11802. You can test whether switching to OpenGL rendering was successful by checking whether the
  11803. according getter \a QCustomPlot::openGl() returns true. If the OpenGL initialization fails,
  11804. rendering continues with the regular software rasterizer, and an according qDebug output is
  11805. generated.
  11806. If switching to OpenGL was successful, this method disables label caching (\ref setPlottingHint
  11807. "setPlottingHint(QCP::phCacheLabels, false)") and turns on QCustomPlot's antialiasing override
  11808. for all elements (\ref setAntialiasedElements "setAntialiasedElements(QCP::aeAll)"), leading to a
  11809. higher quality output. The antialiasing override allows for pixel-grid aligned drawing in the
  11810. OpenGL paint device. As stated before, in OpenGL rendering the actual antialiasing of the plot is
  11811. controlled with \a multisampling. If \a enabled is set to false, the antialiasing/label caching
  11812. settings are restored to what they were before OpenGL was enabled, if they weren't altered in the
  11813. meantime.
  11814. \note OpenGL support is only enabled if QCustomPlot is compiled with the macro \c QCUSTOMPLOT_USE_OPENGL
  11815. defined. This define must be set before including the QCustomPlot header both during compilation
  11816. of the QCustomPlot library as well as when compiling your application. It is best to just include
  11817. the line <tt>DEFINES += QCUSTOMPLOT_USE_OPENGL</tt> in the respective qmake project files.
  11818. \note If you are using a Qt version before 5.0, you must also add the module "opengl" to your \c
  11819. QT variable in the qmake project files. For Qt versions 5.0 and higher, QCustomPlot switches to a
  11820. newer OpenGL interface which is already in the "gui" module.
  11821. */
  11822. void QCustomPlot::setOpenGl(bool enabled, int multisampling)
  11823. {
  11824. mOpenGlMultisamples = qMax(0, multisampling);
  11825. #ifdef QCUSTOMPLOT_USE_OPENGL
  11826. mOpenGl = enabled;
  11827. if (mOpenGl)
  11828. {
  11829. if (setupOpenGl())
  11830. {
  11831. // backup antialiasing override and labelcaching setting so we can restore upon disabling OpenGL
  11832. mOpenGlAntialiasedElementsBackup = mAntialiasedElements;
  11833. mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels);
  11834. // set antialiasing override to antialias all (aligns gl pixel grid properly), and disable label caching (would use software rasterizer for pixmap caches):
  11835. setAntialiasedElements(QCP::aeAll);
  11836. setPlottingHint(QCP::phCacheLabels, false);
  11837. } else
  11838. {
  11839. qDebug() << Q_FUNC_INFO << "Failed to enable OpenGL, continuing plotting without hardware acceleration.";
  11840. mOpenGl = false;
  11841. }
  11842. } else
  11843. {
  11844. // restore antialiasing override and labelcaching to what it was before enabling OpenGL, if nobody changed it in the meantime:
  11845. if (mAntialiasedElements == QCP::aeAll)
  11846. setAntialiasedElements(mOpenGlAntialiasedElementsBackup);
  11847. if (!mPlottingHints.testFlag(QCP::phCacheLabels))
  11848. setPlottingHint(QCP::phCacheLabels, mOpenGlCacheLabelsBackup);
  11849. freeOpenGl();
  11850. }
  11851. // recreate all paint buffers:
  11852. mPaintBuffers.clear();
  11853. setupPaintBuffers();
  11854. #else
  11855. Q_UNUSED(enabled)
  11856. 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)";
  11857. #endif
  11858. }
  11859. /*!
  11860. Sets the viewport of this QCustomPlot. Usually users of QCustomPlot don't need to change the
  11861. viewport manually.
  11862. The viewport is the area in which the plot is drawn. All mechanisms, e.g. margin calculation take
  11863. the viewport to be the outer border of the plot. The viewport normally is the rect() of the
  11864. QCustomPlot widget, i.e. a rect with top left (0, 0) and size of the QCustomPlot widget.
  11865. Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically
  11866. an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger
  11867. and contains also the axes themselves, their tick numbers, their labels, or even additional axis
  11868. rects, color scales and other layout elements.
  11869. This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref
  11870. savePdf, etc. by temporarily changing the viewport size.
  11871. */
  11872. void QCustomPlot::setViewport(const QRect &rect)
  11873. {
  11874. mViewport = rect;
  11875. if (mPlotLayout)
  11876. mPlotLayout->setOuterRect(mViewport);
  11877. }
  11878. /*!
  11879. Sets the device pixel ratio used by the paint buffers of this QCustomPlot instance.
  11880. Normally, this doesn't need to be set manually, because it is initialized with the regular \a
  11881. QWidget::devicePixelRatio which is configured by Qt to fit the display device (e.g. 1 for normal
  11882. displays, 2 for High-DPI displays).
  11883. Device pixel ratios are supported by Qt only for Qt versions since 5.4. If this method is called
  11884. when QCustomPlot is being used with older Qt versions, outputs an according qDebug message and
  11885. leaves the internal buffer device pixel ratio at 1.0.
  11886. */
  11887. void QCustomPlot::setBufferDevicePixelRatio(double ratio)
  11888. {
  11889. if (!qFuzzyCompare(ratio, mBufferDevicePixelRatio))
  11890. {
  11891. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  11892. mBufferDevicePixelRatio = ratio;
  11893. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  11894. buffer->setDevicePixelRatio(mBufferDevicePixelRatio);
  11895. // Note: axis label cache has devicePixelRatio as part of cache hash, so no need to manually clear cache here
  11896. #else
  11897. qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
  11898. mBufferDevicePixelRatio = 1.0;
  11899. #endif
  11900. }
  11901. }
  11902. /*!
  11903. Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn
  11904. below all other objects in the plot.
  11905. For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be
  11906. enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is
  11907. preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  11908. consider using the overloaded version of this function.
  11909. If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will
  11910. first be filled with that brush, before drawing the background pixmap. This can be useful for
  11911. background pixmaps with translucent areas.
  11912. \see setBackgroundScaled, setBackgroundScaledMode
  11913. */
  11914. void QCustomPlot::setBackground(const QPixmap &pm)
  11915. {
  11916. mBackgroundPixmap = pm;
  11917. mScaledBackgroundPixmap = QPixmap();
  11918. }
  11919. /*!
  11920. Sets the background brush of the viewport (see \ref setViewport).
  11921. Before drawing everything else, the background is filled with \a brush. If a background pixmap
  11922. was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport
  11923. before the background pixmap is drawn. This can be useful for background pixmaps with translucent
  11924. areas.
  11925. Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be
  11926. useful for exporting to image formats which support transparency, e.g. \ref savePng.
  11927. \see setBackgroundScaled, setBackgroundScaledMode
  11928. */
  11929. void QCustomPlot::setBackground(const QBrush &brush)
  11930. {
  11931. mBackgroundBrush = brush;
  11932. }
  11933. /*! \overload
  11934. Allows setting the background pixmap of the viewport, whether it shall be scaled and how it
  11935. shall be scaled in one call.
  11936. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  11937. */
  11938. void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
  11939. {
  11940. mBackgroundPixmap = pm;
  11941. mScaledBackgroundPixmap = QPixmap();
  11942. mBackgroundScaled = scaled;
  11943. mBackgroundScaledMode = mode;
  11944. }
  11945. /*!
  11946. Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is
  11947. set to true, control whether and how the aspect ratio of the original pixmap is preserved with
  11948. \ref setBackgroundScaledMode.
  11949. Note that the scaled version of the original pixmap is buffered, so there is no performance
  11950. penalty on replots. (Except when the viewport dimensions are changed continuously.)
  11951. \see setBackground, setBackgroundScaledMode
  11952. */
  11953. void QCustomPlot::setBackgroundScaled(bool scaled)
  11954. {
  11955. mBackgroundScaled = scaled;
  11956. }
  11957. /*!
  11958. If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this
  11959. function to define whether and how the aspect ratio of the original pixmap is preserved.
  11960. \see setBackground, setBackgroundScaled
  11961. */
  11962. void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  11963. {
  11964. mBackgroundScaledMode = mode;
  11965. }
  11966. /*!
  11967. Returns the plottable with \a index. If the index is invalid, returns \c nullptr.
  11968. There is an overloaded version of this function with no parameter which returns the last added
  11969. plottable, see QCustomPlot::plottable()
  11970. \see plottableCount
  11971. */
  11972. QCPAbstractPlottable *QCustomPlot::plottable(int index)
  11973. {
  11974. if (index >= 0 && index < mPlottables.size())
  11975. {
  11976. return mPlottables.at(index);
  11977. } else
  11978. {
  11979. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  11980. return nullptr;
  11981. }
  11982. }
  11983. /*! \overload
  11984. Returns the last plottable that was added to the plot. If there are no plottables in the plot,
  11985. returns \c nullptr.
  11986. \see plottableCount
  11987. */
  11988. QCPAbstractPlottable *QCustomPlot::plottable()
  11989. {
  11990. if (!mPlottables.isEmpty())
  11991. {
  11992. return mPlottables.last();
  11993. } else
  11994. return nullptr;
  11995. }
  11996. /*!
  11997. Removes the specified plottable from the plot and deletes it. If necessary, the corresponding
  11998. legend item is also removed from the default legend (QCustomPlot::legend).
  11999. Returns true on success.
  12000. \see clearPlottables
  12001. */
  12002. bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable)
  12003. {
  12004. if (!mPlottables.contains(plottable))
  12005. {
  12006. qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast<quintptr>(plottable);
  12007. return false;
  12008. }
  12009. // remove plottable from legend:
  12010. plottable->removeFromLegend();
  12011. // special handling for QCPGraphs to maintain the simple graph interface:
  12012. if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable))
  12013. mGraphs.removeOne(graph);
  12014. // remove plottable:
  12015. delete plottable;
  12016. mPlottables.removeOne(plottable);
  12017. return true;
  12018. }
  12019. /*! \overload
  12020. Removes and deletes the plottable by its \a index.
  12021. */
  12022. bool QCustomPlot::removePlottable(int index)
  12023. {
  12024. if (index >= 0 && index < mPlottables.size())
  12025. return removePlottable(mPlottables[index]);
  12026. else
  12027. {
  12028. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12029. return false;
  12030. }
  12031. }
  12032. /*!
  12033. Removes all plottables from the plot and deletes them. Corresponding legend items are also
  12034. removed from the default legend (QCustomPlot::legend).
  12035. Returns the number of plottables removed.
  12036. \see removePlottable
  12037. */
  12038. int QCustomPlot::clearPlottables()
  12039. {
  12040. int c = mPlottables.size();
  12041. for (int i=c-1; i >= 0; --i)
  12042. removePlottable(mPlottables[i]);
  12043. return c;
  12044. }
  12045. /*!
  12046. Returns the number of currently existing plottables in the plot
  12047. \see plottable
  12048. */
  12049. int QCustomPlot::plottableCount() const
  12050. {
  12051. return mPlottables.size();
  12052. }
  12053. /*!
  12054. Returns a list of the selected plottables. If no plottables are currently selected, the list is empty.
  12055. There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs.
  12056. \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection
  12057. */
  12058. QList<QCPAbstractPlottable*> QCustomPlot::selectedPlottables() const
  12059. {
  12060. QList<QCPAbstractPlottable*> result;
  12061. foreach (QCPAbstractPlottable *plottable, mPlottables)
  12062. {
  12063. if (plottable->selected())
  12064. result.append(plottable);
  12065. }
  12066. return result;
  12067. }
  12068. /*!
  12069. Returns any plottable at the pixel position \a pos. Since it can capture all plottables, the
  12070. return type is the abstract base class of all plottables, QCPAbstractPlottable.
  12071. For details, and if you wish to specify a certain plottable type (e.g. QCPGraph), see the
  12072. template method plottableAt<PlottableType>()
  12073. \see plottableAt<PlottableType>(), itemAt, layoutElementAt
  12074. */
  12075. QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable, int *dataIndex) const
  12076. {
  12077. return plottableAt<QCPAbstractPlottable>(pos, onlySelectable, dataIndex);
  12078. }
  12079. /*!
  12080. Returns whether this QCustomPlot instance contains the \a plottable.
  12081. */
  12082. bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const
  12083. {
  12084. return mPlottables.contains(plottable);
  12085. }
  12086. /*!
  12087. Returns the graph with \a index. If the index is invalid, returns \c nullptr.
  12088. There is an overloaded version of this function with no parameter which returns the last created
  12089. graph, see QCustomPlot::graph()
  12090. \see graphCount, addGraph
  12091. */
  12092. QCPGraph *QCustomPlot::graph(int index) const
  12093. {
  12094. if (index >= 0 && index < mGraphs.size())
  12095. {
  12096. return mGraphs.at(index);
  12097. } else
  12098. {
  12099. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12100. return nullptr;
  12101. }
  12102. }
  12103. /*! \overload
  12104. Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot,
  12105. returns \c nullptr.
  12106. \see graphCount, addGraph
  12107. */
  12108. QCPGraph *QCustomPlot::graph() const
  12109. {
  12110. if (!mGraphs.isEmpty())
  12111. {
  12112. return mGraphs.last();
  12113. } else
  12114. return nullptr;
  12115. }
  12116. /*!
  12117. Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the
  12118. bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a
  12119. keyAxis and \a valueAxis must reside in this QCustomPlot.
  12120. \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically
  12121. "y") for the graph.
  12122. Returns a pointer to the newly created graph, or \c nullptr if adding the graph failed.
  12123. \see graph, graphCount, removeGraph, clearGraphs
  12124. */
  12125. QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis)
  12126. {
  12127. if (!keyAxis) keyAxis = xAxis;
  12128. if (!valueAxis) valueAxis = yAxis;
  12129. if (!keyAxis || !valueAxis)
  12130. {
  12131. qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)";
  12132. return nullptr;
  12133. }
  12134. if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this)
  12135. {
  12136. qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent";
  12137. return nullptr;
  12138. }
  12139. QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis);
  12140. newGraph->setName(QLatin1String("Graph ")+QString::number(mGraphs.size()));
  12141. return newGraph;
  12142. }
  12143. /*!
  12144. Removes the specified \a graph from the plot and deletes it. If necessary, the corresponding
  12145. legend item is also removed from the default legend (QCustomPlot::legend). If any other graphs in
  12146. the plot have a channel fill set towards the removed graph, the channel fill property of those
  12147. graphs is reset to \c nullptr (no channel fill).
  12148. Returns true on success.
  12149. \see clearGraphs
  12150. */
  12151. bool QCustomPlot::removeGraph(QCPGraph *graph)
  12152. {
  12153. return removePlottable(graph);
  12154. }
  12155. /*! \overload
  12156. Removes and deletes the graph by its \a index.
  12157. */
  12158. bool QCustomPlot::removeGraph(int index)
  12159. {
  12160. if (index >= 0 && index < mGraphs.size())
  12161. return removeGraph(mGraphs[index]);
  12162. else
  12163. return false;
  12164. }
  12165. /*!
  12166. Removes all graphs from the plot and deletes them. Corresponding legend items are also removed
  12167. from the default legend (QCustomPlot::legend).
  12168. Returns the number of graphs removed.
  12169. \see removeGraph
  12170. */
  12171. int QCustomPlot::clearGraphs()
  12172. {
  12173. int c = mGraphs.size();
  12174. for (int i=c-1; i >= 0; --i)
  12175. removeGraph(mGraphs[i]);
  12176. return c;
  12177. }
  12178. /*!
  12179. Returns the number of currently existing graphs in the plot
  12180. \see graph, addGraph
  12181. */
  12182. int QCustomPlot::graphCount() const
  12183. {
  12184. return mGraphs.size();
  12185. }
  12186. /*!
  12187. Returns a list of the selected graphs. If no graphs are currently selected, the list is empty.
  12188. If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars,
  12189. etc., use \ref selectedPlottables.
  12190. \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection
  12191. */
  12192. QList<QCPGraph*> QCustomPlot::selectedGraphs() const
  12193. {
  12194. QList<QCPGraph*> result;
  12195. foreach (QCPGraph *graph, mGraphs)
  12196. {
  12197. if (graph->selected())
  12198. result.append(graph);
  12199. }
  12200. return result;
  12201. }
  12202. /*!
  12203. Returns the item with \a index. If the index is invalid, returns \c nullptr.
  12204. There is an overloaded version of this function with no parameter which returns the last added
  12205. item, see QCustomPlot::item()
  12206. \see itemCount
  12207. */
  12208. QCPAbstractItem *QCustomPlot::item(int index) const
  12209. {
  12210. if (index >= 0 && index < mItems.size())
  12211. {
  12212. return mItems.at(index);
  12213. } else
  12214. {
  12215. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12216. return nullptr;
  12217. }
  12218. }
  12219. /*! \overload
  12220. Returns the last item that was added to this plot. If there are no items in the plot,
  12221. returns \c nullptr.
  12222. \see itemCount
  12223. */
  12224. QCPAbstractItem *QCustomPlot::item() const
  12225. {
  12226. if (!mItems.isEmpty())
  12227. {
  12228. return mItems.last();
  12229. } else
  12230. return nullptr;
  12231. }
  12232. /*!
  12233. Removes the specified item from the plot and deletes it.
  12234. Returns true on success.
  12235. \see clearItems
  12236. */
  12237. bool QCustomPlot::removeItem(QCPAbstractItem *item)
  12238. {
  12239. if (mItems.contains(item))
  12240. {
  12241. delete item;
  12242. mItems.removeOne(item);
  12243. return true;
  12244. } else
  12245. {
  12246. qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast<quintptr>(item);
  12247. return false;
  12248. }
  12249. }
  12250. /*! \overload
  12251. Removes and deletes the item by its \a index.
  12252. */
  12253. bool QCustomPlot::removeItem(int index)
  12254. {
  12255. if (index >= 0 && index < mItems.size())
  12256. return removeItem(mItems[index]);
  12257. else
  12258. {
  12259. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12260. return false;
  12261. }
  12262. }
  12263. /*!
  12264. Removes all items from the plot and deletes them.
  12265. Returns the number of items removed.
  12266. \see removeItem
  12267. */
  12268. int QCustomPlot::clearItems()
  12269. {
  12270. int c = mItems.size();
  12271. for (int i=c-1; i >= 0; --i)
  12272. removeItem(mItems[i]);
  12273. return c;
  12274. }
  12275. /*!
  12276. Returns the number of currently existing items in the plot
  12277. \see item
  12278. */
  12279. int QCustomPlot::itemCount() const
  12280. {
  12281. return mItems.size();
  12282. }
  12283. /*!
  12284. Returns a list of the selected items. If no items are currently selected, the list is empty.
  12285. \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected
  12286. */
  12287. QList<QCPAbstractItem*> QCustomPlot::selectedItems() const
  12288. {
  12289. QList<QCPAbstractItem*> result;
  12290. foreach (QCPAbstractItem *item, mItems)
  12291. {
  12292. if (item->selected())
  12293. result.append(item);
  12294. }
  12295. return result;
  12296. }
  12297. /*!
  12298. Returns the item at the pixel position \a pos. Since it can capture all items, the
  12299. return type is the abstract base class of all items, QCPAbstractItem.
  12300. For details, and if you wish to specify a certain item type (e.g. QCPItemLine), see the
  12301. template method itemAt<ItemType>()
  12302. \see itemAt<ItemType>(), plottableAt, layoutElementAt
  12303. */
  12304. QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const
  12305. {
  12306. return itemAt<QCPAbstractItem>(pos, onlySelectable);
  12307. }
  12308. /*!
  12309. Returns whether this QCustomPlot contains the \a item.
  12310. \see item
  12311. */
  12312. bool QCustomPlot::hasItem(QCPAbstractItem *item) const
  12313. {
  12314. return mItems.contains(item);
  12315. }
  12316. /*!
  12317. Returns the layer with the specified \a name. If there is no layer with the specified name, \c
  12318. nullptr is returned.
  12319. Layer names are case-sensitive.
  12320. \see addLayer, moveLayer, removeLayer
  12321. */
  12322. QCPLayer *QCustomPlot::layer(const QString &name) const
  12323. {
  12324. foreach (QCPLayer *layer, mLayers)
  12325. {
  12326. if (layer->name() == name)
  12327. return layer;
  12328. }
  12329. return nullptr;
  12330. }
  12331. /*! \overload
  12332. Returns the layer by \a index. If the index is invalid, \c nullptr is returned.
  12333. \see addLayer, moveLayer, removeLayer
  12334. */
  12335. QCPLayer *QCustomPlot::layer(int index) const
  12336. {
  12337. if (index >= 0 && index < mLayers.size())
  12338. {
  12339. return mLayers.at(index);
  12340. } else
  12341. {
  12342. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12343. return nullptr;
  12344. }
  12345. }
  12346. /*!
  12347. Returns the layer that is set as current layer (see \ref setCurrentLayer).
  12348. */
  12349. QCPLayer *QCustomPlot::currentLayer() const
  12350. {
  12351. return mCurrentLayer;
  12352. }
  12353. /*!
  12354. Sets the layer with the specified \a name to be the current layer. All layerables (\ref
  12355. QCPLayerable), e.g. plottables and items, are created on the current layer.
  12356. Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot.
  12357. Layer names are case-sensitive.
  12358. \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer
  12359. */
  12360. bool QCustomPlot::setCurrentLayer(const QString &name)
  12361. {
  12362. if (QCPLayer *newCurrentLayer = layer(name))
  12363. {
  12364. return setCurrentLayer(newCurrentLayer);
  12365. } else
  12366. {
  12367. qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name;
  12368. return false;
  12369. }
  12370. }
  12371. /*! \overload
  12372. Sets the provided \a layer to be the current layer.
  12373. Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot.
  12374. \see addLayer, moveLayer, removeLayer
  12375. */
  12376. bool QCustomPlot::setCurrentLayer(QCPLayer *layer)
  12377. {
  12378. if (!mLayers.contains(layer))
  12379. {
  12380. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  12381. return false;
  12382. }
  12383. mCurrentLayer = layer;
  12384. return true;
  12385. }
  12386. /*!
  12387. Returns the number of currently existing layers in the plot
  12388. \see layer, addLayer
  12389. */
  12390. int QCustomPlot::layerCount() const
  12391. {
  12392. return mLayers.size();
  12393. }
  12394. /*!
  12395. Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which
  12396. must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer.
  12397. Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a
  12398. valid layer inside this QCustomPlot.
  12399. If \a otherLayer is 0, the highest layer in the QCustomPlot will be used.
  12400. For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer.
  12401. \see layer, moveLayer, removeLayer
  12402. */
  12403. bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
  12404. {
  12405. if (!otherLayer)
  12406. otherLayer = mLayers.last();
  12407. if (!mLayers.contains(otherLayer))
  12408. {
  12409. qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
  12410. return false;
  12411. }
  12412. if (layer(name))
  12413. {
  12414. qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name;
  12415. return false;
  12416. }
  12417. QCPLayer *newLayer = new QCPLayer(this, name);
  12418. mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer);
  12419. updateLayerIndices();
  12420. setupPaintBuffers(); // associates new layer with the appropriate paint buffer
  12421. return true;
  12422. }
  12423. /*!
  12424. Removes the specified \a layer and returns true on success.
  12425. All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below
  12426. \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both
  12427. cases, the total rendering order of all layerables in the QCustomPlot is preserved.
  12428. If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom
  12429. layer) becomes the new current layer.
  12430. It is not possible to remove the last layer of the plot.
  12431. \see layer, addLayer, moveLayer
  12432. */
  12433. bool QCustomPlot::removeLayer(QCPLayer *layer)
  12434. {
  12435. if (!mLayers.contains(layer))
  12436. {
  12437. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  12438. return false;
  12439. }
  12440. if (mLayers.size() < 2)
  12441. {
  12442. qDebug() << Q_FUNC_INFO << "can't remove last layer";
  12443. return false;
  12444. }
  12445. // append all children of this layer to layer below (if this is lowest layer, prepend to layer above)
  12446. int removedIndex = layer->index();
  12447. bool isFirstLayer = removedIndex==0;
  12448. QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1);
  12449. QList<QCPLayerable*> children = layer->children();
  12450. if (isFirstLayer) // prepend in reverse order (such that relative order stays the same)
  12451. std::reverse(children.begin(), children.end());
  12452. foreach (QCPLayerable *child, children)
  12453. child->moveToLayer(targetLayer, isFirstLayer); // prepend if isFirstLayer, otherwise append
  12454. // if removed layer is current layer, change current layer to layer below/above:
  12455. if (layer == mCurrentLayer)
  12456. setCurrentLayer(targetLayer);
  12457. // invalidate the paint buffer that was responsible for this layer:
  12458. if (QSharedPointer<QCPAbstractPaintBuffer> pb = layer->mPaintBuffer.toStrongRef())
  12459. pb->setInvalidated();
  12460. // remove layer:
  12461. delete layer;
  12462. mLayers.removeOne(layer);
  12463. updateLayerIndices();
  12464. return true;
  12465. }
  12466. /*!
  12467. Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or
  12468. below is controlled with \a insertMode.
  12469. Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the
  12470. QCustomPlot.
  12471. \see layer, addLayer, moveLayer
  12472. */
  12473. bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
  12474. {
  12475. if (!mLayers.contains(layer))
  12476. {
  12477. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  12478. return false;
  12479. }
  12480. if (!mLayers.contains(otherLayer))
  12481. {
  12482. qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
  12483. return false;
  12484. }
  12485. if (layer->index() > otherLayer->index())
  12486. mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0));
  12487. else if (layer->index() < otherLayer->index())
  12488. mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 0:-1));
  12489. // invalidate the paint buffers that are responsible for the layers:
  12490. if (QSharedPointer<QCPAbstractPaintBuffer> pb = layer->mPaintBuffer.toStrongRef())
  12491. pb->setInvalidated();
  12492. if (QSharedPointer<QCPAbstractPaintBuffer> pb = otherLayer->mPaintBuffer.toStrongRef())
  12493. pb->setInvalidated();
  12494. updateLayerIndices();
  12495. return true;
  12496. }
  12497. /*!
  12498. Returns the number of axis rects in the plot.
  12499. All axis rects can be accessed via QCustomPlot::axisRect().
  12500. Initially, only one axis rect exists in the plot.
  12501. \see axisRect, axisRects
  12502. */
  12503. int QCustomPlot::axisRectCount() const
  12504. {
  12505. return axisRects().size();
  12506. }
  12507. /*!
  12508. Returns the axis rect with \a index.
  12509. Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were
  12510. added, all of them may be accessed with this function in a linear fashion (even when they are
  12511. nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout).
  12512. The order of the axis rects is given by the fill order of the \ref QCPLayout that is holding
  12513. them. For example, if the axis rects are in the top level grid layout (accessible via \ref
  12514. QCustomPlot::plotLayout), they are ordered from left to right, top to bottom, if the layout's
  12515. default \ref QCPLayoutGrid::setFillOrder "setFillOrder" of \ref QCPLayoutGrid::foColumnsFirst
  12516. "foColumnsFirst" wasn't changed.
  12517. If you want to access axis rects by their row and column index, use the layout interface. For
  12518. example, use \ref QCPLayoutGrid::element of the top level grid layout, and \c qobject_cast the
  12519. returned layout element to \ref QCPAxisRect. (See also \ref thelayoutsystem.)
  12520. \see axisRectCount, axisRects, QCPLayoutGrid::setFillOrder
  12521. */
  12522. QCPAxisRect *QCustomPlot::axisRect(int index) const
  12523. {
  12524. const QList<QCPAxisRect*> rectList = axisRects();
  12525. if (index >= 0 && index < rectList.size())
  12526. {
  12527. return rectList.at(index);
  12528. } else
  12529. {
  12530. qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index;
  12531. return nullptr;
  12532. }
  12533. }
  12534. /*!
  12535. Returns all axis rects in the plot.
  12536. The order of the axis rects is given by the fill order of the \ref QCPLayout that is holding
  12537. them. For example, if the axis rects are in the top level grid layout (accessible via \ref
  12538. QCustomPlot::plotLayout), they are ordered from left to right, top to bottom, if the layout's
  12539. default \ref QCPLayoutGrid::setFillOrder "setFillOrder" of \ref QCPLayoutGrid::foColumnsFirst
  12540. "foColumnsFirst" wasn't changed.
  12541. \see axisRectCount, axisRect, QCPLayoutGrid::setFillOrder
  12542. */
  12543. QList<QCPAxisRect*> QCustomPlot::axisRects() const
  12544. {
  12545. QList<QCPAxisRect*> result;
  12546. QStack<QCPLayoutElement*> elementStack;
  12547. if (mPlotLayout)
  12548. elementStack.push(mPlotLayout);
  12549. while (!elementStack.isEmpty())
  12550. {
  12551. foreach (QCPLayoutElement *element, elementStack.pop()->elements(false))
  12552. {
  12553. if (element)
  12554. {
  12555. elementStack.push(element);
  12556. if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(element))
  12557. result.append(ar);
  12558. }
  12559. }
  12560. }
  12561. return result;
  12562. }
  12563. /*!
  12564. Returns the layout element at pixel position \a pos. If there is no element at that position,
  12565. returns \c nullptr.
  12566. Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on
  12567. any of its parent elements is set to false, it will not be considered.
  12568. \see itemAt, plottableAt
  12569. */
  12570. QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const
  12571. {
  12572. QCPLayoutElement *currentElement = mPlotLayout;
  12573. bool searchSubElements = true;
  12574. while (searchSubElements && currentElement)
  12575. {
  12576. searchSubElements = false;
  12577. foreach (QCPLayoutElement *subElement, currentElement->elements(false))
  12578. {
  12579. if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
  12580. {
  12581. currentElement = subElement;
  12582. searchSubElements = true;
  12583. break;
  12584. }
  12585. }
  12586. }
  12587. return currentElement;
  12588. }
  12589. /*!
  12590. Returns the layout element of type \ref QCPAxisRect at pixel position \a pos. This method ignores
  12591. other layout elements even if they are visually in front of the axis rect (e.g. a \ref
  12592. QCPLegend). If there is no axis rect at that position, returns \c nullptr.
  12593. Only visible axis rects are used. If \ref QCPLayoutElement::setVisible on the axis rect itself or
  12594. on any of its parent elements is set to false, it will not be considered.
  12595. \see layoutElementAt
  12596. */
  12597. QCPAxisRect *QCustomPlot::axisRectAt(const QPointF &pos) const
  12598. {
  12599. QCPAxisRect *result = nullptr;
  12600. QCPLayoutElement *currentElement = mPlotLayout;
  12601. bool searchSubElements = true;
  12602. while (searchSubElements && currentElement)
  12603. {
  12604. searchSubElements = false;
  12605. foreach (QCPLayoutElement *subElement, currentElement->elements(false))
  12606. {
  12607. if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
  12608. {
  12609. currentElement = subElement;
  12610. searchSubElements = true;
  12611. if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(currentElement))
  12612. result = ar;
  12613. break;
  12614. }
  12615. }
  12616. }
  12617. return result;
  12618. }
  12619. /*!
  12620. Returns the axes that currently have selected parts, i.e. whose selection state is not \ref
  12621. QCPAxis::spNone.
  12622. \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts,
  12623. QCPAxis::setSelectableParts
  12624. */
  12625. QList<QCPAxis*> QCustomPlot::selectedAxes() const
  12626. {
  12627. QList<QCPAxis*> result, allAxes;
  12628. foreach (QCPAxisRect *rect, axisRects())
  12629. allAxes << rect->axes();
  12630. foreach (QCPAxis *axis, allAxes)
  12631. {
  12632. if (axis->selectedParts() != QCPAxis::spNone)
  12633. result.append(axis);
  12634. }
  12635. return result;
  12636. }
  12637. /*!
  12638. Returns the legends that currently have selected parts, i.e. whose selection state is not \ref
  12639. QCPLegend::spNone.
  12640. \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts,
  12641. QCPLegend::setSelectableParts, QCPLegend::selectedItems
  12642. */
  12643. QList<QCPLegend*> QCustomPlot::selectedLegends() const
  12644. {
  12645. QList<QCPLegend*> result;
  12646. QStack<QCPLayoutElement*> elementStack;
  12647. if (mPlotLayout)
  12648. elementStack.push(mPlotLayout);
  12649. while (!elementStack.isEmpty())
  12650. {
  12651. foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false))
  12652. {
  12653. if (subElement)
  12654. {
  12655. elementStack.push(subElement);
  12656. if (QCPLegend *leg = qobject_cast<QCPLegend*>(subElement))
  12657. {
  12658. if (leg->selectedParts() != QCPLegend::spNone)
  12659. result.append(leg);
  12660. }
  12661. }
  12662. }
  12663. }
  12664. return result;
  12665. }
  12666. /*!
  12667. Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot.
  12668. Since calling this function is not a user interaction, this does not emit the \ref
  12669. selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the
  12670. objects were previously selected.
  12671. \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends
  12672. */
  12673. void QCustomPlot::deselectAll()
  12674. {
  12675. foreach (QCPLayer *layer, mLayers)
  12676. {
  12677. foreach (QCPLayerable *layerable, layer->children())
  12678. layerable->deselectEvent(nullptr);
  12679. }
  12680. }
  12681. /*!
  12682. Causes a complete replot into the internal paint buffer(s). Finally, the widget surface is
  12683. refreshed with the new buffer contents. This is the method that must be called to make changes to
  12684. the plot, e.g. on the axis ranges or data points of graphs, visible.
  12685. The parameter \a refreshPriority can be used to fine-tune the timing of the replot. For example
  12686. if your application calls \ref replot very quickly in succession (e.g. multiple independent
  12687. functions change some aspects of the plot and each wants to make sure the change gets replotted),
  12688. it is advisable to set \a refreshPriority to \ref QCustomPlot::rpQueuedReplot. This way, the
  12689. actual replotting is deferred to the next event loop iteration. Multiple successive calls of \ref
  12690. replot with this priority will only cause a single replot, avoiding redundant replots and
  12691. improving performance.
  12692. Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the
  12693. QCustomPlot widget and user interactions (object selection and range dragging/zooming).
  12694. Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref
  12695. afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two
  12696. signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite
  12697. recursion.
  12698. If a layer is in mode \ref QCPLayer::lmBuffered (\ref QCPLayer::setMode), it is also possible to
  12699. replot only that specific layer via \ref QCPLayer::replot. See the documentation there for
  12700. details.
  12701. \see replotTime
  12702. */
  12703. void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority)
  12704. {
  12705. if (refreshPriority == QCustomPlot::rpQueuedReplot)
  12706. {
  12707. if (!mReplotQueued)
  12708. {
  12709. mReplotQueued = true;
  12710. QTimer::singleShot(0, this, SLOT(replot()));
  12711. }
  12712. return;
  12713. }
  12714. if (mReplotting) // incase signals loop back to replot slot
  12715. return;
  12716. mReplotting = true;
  12717. mReplotQueued = false;
  12718. emit beforeReplot();
  12719. # if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
  12720. QTime replotTimer;
  12721. replotTimer.start();
  12722. # else
  12723. QElapsedTimer replotTimer;
  12724. replotTimer.start();
  12725. # endif
  12726. updateLayout();
  12727. // draw all layered objects (grid, axes, plottables, items, legend,...) into their buffers:
  12728. setupPaintBuffers();
  12729. foreach (QCPLayer *layer, mLayers)
  12730. layer->drawToPaintBuffer();
  12731. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  12732. buffer->setInvalidated(false);
  12733. if ((refreshPriority == rpRefreshHint && mPlottingHints.testFlag(QCP::phImmediateRefresh)) || refreshPriority==rpImmediateRefresh)
  12734. repaint();
  12735. else
  12736. update();
  12737. # if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
  12738. mReplotTime = replotTimer.elapsed();
  12739. # else
  12740. mReplotTime = replotTimer.nsecsElapsed()*1e-6;
  12741. # endif
  12742. if (!qFuzzyIsNull(mReplotTimeAverage))
  12743. mReplotTimeAverage = mReplotTimeAverage*0.9 + mReplotTime*0.1; // exponential moving average with a time constant of 10 last replots
  12744. else
  12745. mReplotTimeAverage = mReplotTime; // no previous replots to average with, so initialize with replot time
  12746. emit afterReplot();
  12747. mReplotting = false;
  12748. }
  12749. /*!
  12750. Returns the time in milliseconds that the last replot took. If \a average is set to true, an
  12751. exponential moving average over the last couple of replots is returned.
  12752. \see replot
  12753. */
  12754. double QCustomPlot::replotTime(bool average) const
  12755. {
  12756. return average ? mReplotTimeAverage : mReplotTime;
  12757. }
  12758. /*!
  12759. Rescales the axes such that all plottables (like graphs) in the plot are fully visible.
  12760. if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true
  12761. (QCPLayerable::setVisible), will be used to rescale the axes.
  12762. \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale
  12763. */
  12764. void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables)
  12765. {
  12766. QList<QCPAxis*> allAxes;
  12767. foreach (QCPAxisRect *rect, axisRects())
  12768. allAxes << rect->axes();
  12769. foreach (QCPAxis *axis, allAxes)
  12770. axis->rescale(onlyVisiblePlottables);
  12771. }
  12772. /*!
  12773. Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale
  12774. of texts and lines will be derived from the specified \a width and \a height. This means, the
  12775. output will look like the normal on-screen output of a QCustomPlot widget with the corresponding
  12776. pixel width and height. If either \a width or \a height is zero, the exported image will have the
  12777. same dimensions as the QCustomPlot widget currently has.
  12778. Setting \a exportPen to \ref QCP::epNoCosmetic allows to disable the use of cosmetic pens when
  12779. drawing to the PDF file. Cosmetic pens are pens with numerical width 0, which are always drawn as
  12780. a one pixel wide line, no matter what zoom factor is set in the PDF-Viewer. For more information
  12781. about cosmetic pens, see the QPainter and QPen documentation.
  12782. The objects of the plot will appear in the current selection state. If you don't want any
  12783. selected objects to be painted in their selected look, deselect everything with \ref deselectAll
  12784. before calling this function.
  12785. Returns true on success.
  12786. \warning
  12787. \li If you plan on editing the exported PDF file with a vector graphics editor like Inkscape, it
  12788. is advised to set \a exportPen to \ref QCP::epNoCosmetic to avoid losing those cosmetic lines
  12789. (which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks).
  12790. \li If calling this function inside the constructor of the parent of the QCustomPlot widget
  12791. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12792. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12793. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12794. aren't defined yet inside the constructor, so you would get an image that has strange
  12795. widths/heights.
  12796. \a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting
  12797. PDF file.
  12798. \note On Android systems, this method does nothing and issues an according qDebug warning
  12799. message. This is also the case if for other reasons the define flag \c QT_NO_PRINTER is set.
  12800. \see savePng, saveBmp, saveJpg, saveRastered
  12801. */
  12802. bool QCustomPlot::savePdf(const QString &fileName, int width, int height, QCP::ExportPen exportPen, const QString &pdfCreator, const QString &pdfTitle)
  12803. {
  12804. bool success = false;
  12805. #ifdef QT_NO_PRINTER
  12806. Q_UNUSED(fileName)
  12807. Q_UNUSED(exportPen)
  12808. Q_UNUSED(width)
  12809. Q_UNUSED(height)
  12810. Q_UNUSED(pdfCreator)
  12811. Q_UNUSED(pdfTitle)
  12812. qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created.";
  12813. #else
  12814. int newWidth, newHeight;
  12815. if (width == 0 || height == 0)
  12816. {
  12817. newWidth = this->width();
  12818. newHeight = this->height();
  12819. } else
  12820. {
  12821. newWidth = width;
  12822. newHeight = height;
  12823. }
  12824. QPrinter printer(QPrinter::ScreenResolution);
  12825. printer.setOutputFileName(fileName);
  12826. printer.setOutputFormat(QPrinter::PdfFormat);
  12827. printer.setColorMode(QPrinter::Color);
  12828. printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator);
  12829. printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle);
  12830. QRect oldViewport = viewport();
  12831. setViewport(QRect(0, 0, newWidth, newHeight));
  12832. #if QT_VERSION < QT_VERSION_CHECK(5, 3, 0)
  12833. printer.setFullPage(true);
  12834. printer.setPaperSize(viewport().size(), QPrinter::DevicePixel);
  12835. #else
  12836. QPageLayout pageLayout;
  12837. pageLayout.setMode(QPageLayout::FullPageMode);
  12838. pageLayout.setOrientation(QPageLayout::Portrait);
  12839. pageLayout.setMargins(QMarginsF(0, 0, 0, 0));
  12840. pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch));
  12841. printer.setPageLayout(pageLayout);
  12842. #endif
  12843. QCPPainter printpainter;
  12844. if (printpainter.begin(&printer))
  12845. {
  12846. printpainter.setMode(QCPPainter::pmVectorized);
  12847. printpainter.setMode(QCPPainter::pmNoCaching);
  12848. printpainter.setMode(QCPPainter::pmNonCosmetic, exportPen==QCP::epNoCosmetic);
  12849. printpainter.setWindow(mViewport);
  12850. if (mBackgroundBrush.style() != Qt::NoBrush &&
  12851. mBackgroundBrush.color() != Qt::white &&
  12852. mBackgroundBrush.color() != Qt::transparent &&
  12853. mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent
  12854. printpainter.fillRect(viewport(), mBackgroundBrush);
  12855. draw(&printpainter);
  12856. printpainter.end();
  12857. success = true;
  12858. }
  12859. setViewport(oldViewport);
  12860. #endif // QT_NO_PRINTER
  12861. return success;
  12862. }
  12863. /*!
  12864. Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width
  12865. and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
  12866. current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
  12867. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
  12868. parameter.
  12869. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  12870. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  12871. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  12872. 200*200 pixel resolution.
  12873. If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
  12874. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  12875. QCustomPlot to place objects with sub-pixel accuracy.
  12876. image compression can be controlled with the \a quality parameter which must be between 0 and 100
  12877. or -1 to use the default setting.
  12878. The \a resolution will be written to the image file header and has no direct consequence for the
  12879. quality or the pixel size. However, if opening the image with a tool which respects the metadata,
  12880. it will be able to scale the image to match either a given size in real units of length (inch,
  12881. centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
  12882. given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
  12883. resolution unit internally.
  12884. Returns true on success. If this function fails, most likely the PNG format isn't supported by
  12885. the system, see Qt docs about QImageWriter::supportedImageFormats().
  12886. The objects of the plot will appear in the current selection state. If you don't want any selected
  12887. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  12888. this function.
  12889. If you want the PNG to have a transparent background, call \ref setBackground(const QBrush &brush)
  12890. with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving.
  12891. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  12892. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12893. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12894. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12895. aren't defined yet inside the constructor, so you would get an image that has strange
  12896. widths/heights.
  12897. \see savePdf, saveBmp, saveJpg, saveRastered
  12898. */
  12899. bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
  12900. {
  12901. return saveRastered(fileName, width, height, scale, "PNG", quality, resolution, resolutionUnit);
  12902. }
  12903. /*!
  12904. Saves a JPEG image file to \a fileName on disc. The output plot will have the dimensions \a width
  12905. and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
  12906. current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
  12907. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
  12908. parameter.
  12909. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  12910. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  12911. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  12912. 200*200 pixel resolution.
  12913. If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
  12914. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  12915. QCustomPlot to place objects with sub-pixel accuracy.
  12916. image compression can be controlled with the \a quality parameter which must be between 0 and 100
  12917. or -1 to use the default setting.
  12918. The \a resolution will be written to the image file header and has no direct consequence for the
  12919. quality or the pixel size. However, if opening the image with a tool which respects the metadata,
  12920. it will be able to scale the image to match either a given size in real units of length (inch,
  12921. centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
  12922. given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
  12923. resolution unit internally.
  12924. Returns true on success. If this function fails, most likely the JPEG format isn't supported by
  12925. the system, see Qt docs about QImageWriter::supportedImageFormats().
  12926. The objects of the plot will appear in the current selection state. If you don't want any selected
  12927. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  12928. this function.
  12929. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  12930. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12931. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12932. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12933. aren't defined yet inside the constructor, so you would get an image that has strange
  12934. widths/heights.
  12935. \see savePdf, savePng, saveBmp, saveRastered
  12936. */
  12937. bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
  12938. {
  12939. return saveRastered(fileName, width, height, scale, "JPG", quality, resolution, resolutionUnit);
  12940. }
  12941. /*!
  12942. Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width
  12943. and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
  12944. current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
  12945. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
  12946. parameter.
  12947. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  12948. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  12949. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  12950. 200*200 pixel resolution.
  12951. If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
  12952. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  12953. QCustomPlot to place objects with sub-pixel accuracy.
  12954. The \a resolution will be written to the image file header and has no direct consequence for the
  12955. quality or the pixel size. However, if opening the image with a tool which respects the metadata,
  12956. it will be able to scale the image to match either a given size in real units of length (inch,
  12957. centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
  12958. given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
  12959. resolution unit internally.
  12960. Returns true on success. If this function fails, most likely the BMP format isn't supported by
  12961. the system, see Qt docs about QImageWriter::supportedImageFormats().
  12962. The objects of the plot will appear in the current selection state. If you don't want any selected
  12963. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  12964. this function.
  12965. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  12966. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12967. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12968. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12969. aren't defined yet inside the constructor, so you would get an image that has strange
  12970. widths/heights.
  12971. \see savePdf, savePng, saveJpg, saveRastered
  12972. */
  12973. bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale, int resolution, QCP::ResolutionUnit resolutionUnit)
  12974. {
  12975. return saveRastered(fileName, width, height, scale, "BMP", -1, resolution, resolutionUnit);
  12976. }
  12977. /*! \internal
  12978. Returns a minimum size hint that corresponds to the minimum size of the top level layout
  12979. (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum
  12980. size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot.
  12981. This is especially important, when placed in a QLayout where other components try to take in as
  12982. much space as possible (e.g. QMdiArea).
  12983. */
  12984. QSize QCustomPlot::minimumSizeHint() const
  12985. {
  12986. return mPlotLayout->minimumOuterSizeHint();
  12987. }
  12988. /*! \internal
  12989. Returns a size hint that is the same as \ref minimumSizeHint.
  12990. */
  12991. QSize QCustomPlot::sizeHint() const
  12992. {
  12993. return mPlotLayout->minimumOuterSizeHint();
  12994. }
  12995. /*! \internal
  12996. Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but
  12997. draws the internal buffer on the widget surface.
  12998. */
  12999. void QCustomPlot::paintEvent(QPaintEvent *event)
  13000. {
  13001. Q_UNUSED(event)
  13002. // detect if the device pixel ratio has changed (e.g. moving window between different DPI screens), and adapt buffers if necessary:
  13003. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  13004. # ifdef QCP_DEVICEPIXELRATIO_FLOAT
  13005. double newDpr = devicePixelRatioF();
  13006. # else
  13007. double newDpr = devicePixelRatio();
  13008. # endif
  13009. if (!qFuzzyCompare(mBufferDevicePixelRatio, newDpr))
  13010. {
  13011. setBufferDevicePixelRatio(newDpr);
  13012. replot(QCustomPlot::rpQueuedRefresh);
  13013. return;
  13014. }
  13015. #endif
  13016. QCPPainter painter(this);
  13017. if (painter.isActive())
  13018. {
  13019. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  13020. painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem
  13021. #endif
  13022. if (mBackgroundBrush.style() != Qt::NoBrush)
  13023. painter.fillRect(mViewport, mBackgroundBrush);
  13024. drawBackground(&painter);
  13025. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  13026. buffer->draw(&painter);
  13027. }
  13028. }
  13029. /*! \internal
  13030. Event handler for a resize of the QCustomPlot widget. The viewport (which becomes the outer rect
  13031. of mPlotLayout) is resized appropriately. Finally a \ref replot is performed.
  13032. */
  13033. void QCustomPlot::resizeEvent(QResizeEvent *event)
  13034. {
  13035. Q_UNUSED(event)
  13036. // resize and repaint the buffer:
  13037. setViewport(rect());
  13038. replot(rpQueuedRefresh); // queued refresh is important here, to prevent painting issues in some contexts (e.g. MDI subwindow)
  13039. }
  13040. /*! \internal
  13041. Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then
  13042. determines the layerable under the cursor and forwards the event to it. Finally, emits the
  13043. specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref
  13044. axisDoubleClick, etc.).
  13045. \see mousePressEvent, mouseReleaseEvent
  13046. */
  13047. void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event)
  13048. {
  13049. emit mouseDoubleClick(event);
  13050. mMouseHasMoved = false;
  13051. mMousePressPos = event->pos();
  13052. // determine layerable under the cursor (this event is called instead of the second press event in a double-click):
  13053. QList<QVariant> details;
  13054. QList<QCPLayerable*> candidates = layerableListAt(mMousePressPos, false, &details);
  13055. for (int i=0; i<candidates.size(); ++i)
  13056. {
  13057. event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
  13058. candidates.at(i)->mouseDoubleClickEvent(event, details.at(i));
  13059. if (event->isAccepted())
  13060. {
  13061. mMouseEventLayerable = candidates.at(i);
  13062. mMouseEventLayerableDetails = details.at(i);
  13063. break;
  13064. }
  13065. }
  13066. // emit specialized object double click signals:
  13067. if (!candidates.isEmpty())
  13068. {
  13069. if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(candidates.first()))
  13070. {
  13071. int dataIndex = 0;
  13072. if (!details.first().value<QCPDataSelection>().isEmpty())
  13073. dataIndex = details.first().value<QCPDataSelection>().dataRange().begin();
  13074. emit plottableDoubleClick(ap, dataIndex, event);
  13075. } else if (QCPAxis *ax = qobject_cast<QCPAxis*>(candidates.first()))
  13076. emit axisDoubleClick(ax, details.first().value<QCPAxis::SelectablePart>(), event);
  13077. else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(candidates.first()))
  13078. emit itemDoubleClick(ai, event);
  13079. else if (QCPLegend *lg = qobject_cast<QCPLegend*>(candidates.first()))
  13080. emit legendDoubleClick(lg, nullptr, event);
  13081. else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(candidates.first()))
  13082. emit legendDoubleClick(li->parentLegend(), li, event);
  13083. }
  13084. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13085. }
  13086. /*! \internal
  13087. Event handler for when a mouse button is pressed. Emits the mousePress signal.
  13088. If the current \ref setSelectionRectMode is not \ref QCP::srmNone, passes the event to the
  13089. selection rect. Otherwise determines the layerable under the cursor and forwards the event to it.
  13090. \see mouseMoveEvent, mouseReleaseEvent
  13091. */
  13092. void QCustomPlot::mousePressEvent(QMouseEvent *event)
  13093. {
  13094. emit mousePress(event);
  13095. // save some state to tell in releaseEvent whether it was a click:
  13096. mMouseHasMoved = false;
  13097. mMousePressPos = event->pos();
  13098. if (mSelectionRect && mSelectionRectMode != QCP::srmNone)
  13099. {
  13100. if (mSelectionRectMode != QCP::srmZoom || qobject_cast<QCPAxisRect*>(axisRectAt(mMousePressPos))) // in zoom mode only activate selection rect if on an axis rect
  13101. mSelectionRect->startSelection(event);
  13102. } else
  13103. {
  13104. // no selection rect interaction, prepare for click signal emission and forward event to layerable under the cursor:
  13105. QList<QVariant> details;
  13106. QList<QCPLayerable*> candidates = layerableListAt(mMousePressPos, false, &details);
  13107. if (!candidates.isEmpty())
  13108. {
  13109. mMouseSignalLayerable = candidates.first(); // candidate for signal emission is always topmost hit layerable (signal emitted in release event)
  13110. mMouseSignalLayerableDetails = details.first();
  13111. }
  13112. // forward event to topmost candidate which accepts the event:
  13113. for (int i=0; i<candidates.size(); ++i)
  13114. {
  13115. event->accept(); // default impl of QCPLayerable's mouse events call ignore() on the event, in that case propagate to next candidate in list
  13116. candidates.at(i)->mousePressEvent(event, details.at(i));
  13117. if (event->isAccepted())
  13118. {
  13119. mMouseEventLayerable = candidates.at(i);
  13120. mMouseEventLayerableDetails = details.at(i);
  13121. break;
  13122. }
  13123. }
  13124. }
  13125. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13126. }
  13127. /*! \internal
  13128. Event handler for when the cursor is moved. Emits the \ref mouseMove signal.
  13129. If the selection rect (\ref setSelectionRect) is currently active, the event is forwarded to it
  13130. in order to update the rect geometry.
  13131. Otherwise, if a layout element has mouse capture focus (a mousePressEvent happened on top of the
  13132. layout element before), the mouseMoveEvent is forwarded to that element.
  13133. \see mousePressEvent, mouseReleaseEvent
  13134. */
  13135. void QCustomPlot::mouseMoveEvent(QMouseEvent *event)
  13136. {
  13137. emit mouseMove(event);
  13138. if (!mMouseHasMoved && (mMousePressPos-event->pos()).manhattanLength() > 3)
  13139. mMouseHasMoved = true; // moved too far from mouse press position, don't handle as click on mouse release
  13140. if (mSelectionRect && mSelectionRect->isActive())
  13141. mSelectionRect->moveSelection(event);
  13142. else if (mMouseEventLayerable) // call event of affected layerable:
  13143. mMouseEventLayerable->mouseMoveEvent(event, mMousePressPos);
  13144. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13145. }
  13146. /*! \internal
  13147. Event handler for when a mouse button is released. Emits the \ref mouseRelease signal.
  13148. If the mouse was moved less than a certain threshold in any direction since the \ref
  13149. mousePressEvent, it is considered a click which causes the selection mechanism (if activated via
  13150. \ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse
  13151. click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.)
  13152. If a layerable is the mouse capturer (a \ref mousePressEvent happened on top of the layerable
  13153. before), the \ref mouseReleaseEvent is forwarded to that element.
  13154. \see mousePressEvent, mouseMoveEvent
  13155. */
  13156. void QCustomPlot::mouseReleaseEvent(QMouseEvent *event)
  13157. {
  13158. emit mouseRelease(event);
  13159. if (!mMouseHasMoved) // mouse hasn't moved (much) between press and release, so handle as click
  13160. {
  13161. if (mSelectionRect && mSelectionRect->isActive()) // a simple click shouldn't successfully finish a selection rect, so cancel it here
  13162. mSelectionRect->cancel();
  13163. if (event->button() == Qt::LeftButton)
  13164. processPointSelection(event);
  13165. // emit specialized click signals of QCustomPlot instance:
  13166. if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(mMouseSignalLayerable))
  13167. {
  13168. int dataIndex = 0;
  13169. if (!mMouseSignalLayerableDetails.value<QCPDataSelection>().isEmpty())
  13170. dataIndex = mMouseSignalLayerableDetails.value<QCPDataSelection>().dataRange().begin();
  13171. emit plottableClick(ap, dataIndex, event);
  13172. } else if (QCPAxis *ax = qobject_cast<QCPAxis*>(mMouseSignalLayerable))
  13173. emit axisClick(ax, mMouseSignalLayerableDetails.value<QCPAxis::SelectablePart>(), event);
  13174. else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(mMouseSignalLayerable))
  13175. emit itemClick(ai, event);
  13176. else if (QCPLegend *lg = qobject_cast<QCPLegend*>(mMouseSignalLayerable))
  13177. emit legendClick(lg, nullptr, event);
  13178. else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(mMouseSignalLayerable))
  13179. emit legendClick(li->parentLegend(), li, event);
  13180. mMouseSignalLayerable = nullptr;
  13181. }
  13182. if (mSelectionRect && mSelectionRect->isActive()) // Note: if a click was detected above, the selection rect is canceled there
  13183. {
  13184. // finish selection rect, the appropriate action will be taken via signal-slot connection:
  13185. mSelectionRect->endSelection(event);
  13186. } else
  13187. {
  13188. // call event of affected layerable:
  13189. if (mMouseEventLayerable)
  13190. {
  13191. mMouseEventLayerable->mouseReleaseEvent(event, mMousePressPos);
  13192. mMouseEventLayerable = nullptr;
  13193. }
  13194. }
  13195. if (noAntialiasingOnDrag())
  13196. replot(rpQueuedReplot);
  13197. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13198. }
  13199. /*! \internal
  13200. Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then
  13201. determines the affected layerable and forwards the event to it.
  13202. */
  13203. void QCustomPlot::wheelEvent(QWheelEvent *event)
  13204. {
  13205. emit mouseWheel(event);
  13206. #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  13207. const QPointF pos = event->pos();
  13208. #else
  13209. const QPointF pos = event->position();
  13210. #endif
  13211. // forward event to layerable under cursor:
  13212. foreach (QCPLayerable *candidate, layerableListAt(pos, false))
  13213. {
  13214. event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
  13215. candidate->wheelEvent(event);
  13216. if (event->isAccepted())
  13217. break;
  13218. }
  13219. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13220. }
  13221. /*! \internal
  13222. This function draws the entire plot, including background pixmap, with the specified \a painter.
  13223. It does not make use of the paint buffers like \ref replot, so this is the function typically
  13224. used by saving/exporting methods such as \ref savePdf or \ref toPainter.
  13225. Note that it does not fill the background with the background brush (as the user may specify with
  13226. \ref setBackground(const QBrush &brush)), this is up to the respective functions calling this
  13227. method.
  13228. */
  13229. void QCustomPlot::draw(QCPPainter *painter)
  13230. {
  13231. updateLayout();
  13232. // draw viewport background pixmap:
  13233. drawBackground(painter);
  13234. // draw all layered objects (grid, axes, plottables, items, legend,...):
  13235. foreach (QCPLayer *layer, mLayers)
  13236. layer->draw(painter);
  13237. /* Debug code to draw all layout element rects
  13238. foreach (QCPLayoutElement *el, findChildren<QCPLayoutElement*>())
  13239. {
  13240. painter->setBrush(Qt::NoBrush);
  13241. painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine));
  13242. painter->drawRect(el->rect());
  13243. painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine));
  13244. painter->drawRect(el->outerRect());
  13245. }
  13246. */
  13247. }
  13248. /*! \internal
  13249. Performs the layout update steps defined by \ref QCPLayoutElement::UpdatePhase, by calling \ref
  13250. QCPLayoutElement::update on the main plot layout.
  13251. Here, the layout elements calculate their positions and margins, and prepare for the following
  13252. draw call.
  13253. */
  13254. void QCustomPlot::updateLayout()
  13255. {
  13256. // run through layout phases:
  13257. mPlotLayout->update(QCPLayoutElement::upPreparation);
  13258. mPlotLayout->update(QCPLayoutElement::upMargins);
  13259. mPlotLayout->update(QCPLayoutElement::upLayout);
  13260. emit afterLayout();
  13261. }
  13262. /*! \internal
  13263. Draws the viewport background pixmap of the plot.
  13264. If a pixmap was provided via \ref setBackground, this function buffers the scaled version
  13265. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  13266. the viewport with the provided \a painter. The scaled version is buffered in
  13267. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  13268. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  13269. dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
  13270. set.
  13271. Note that this function does not draw a fill with the background brush
  13272. (\ref setBackground(const QBrush &brush)) beneath the pixmap.
  13273. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  13274. */
  13275. void QCustomPlot::drawBackground(QCPPainter *painter)
  13276. {
  13277. // Note: background color is handled in individual replot/save functions
  13278. // draw background pixmap (on top of fill, if brush specified):
  13279. if (!mBackgroundPixmap.isNull())
  13280. {
  13281. if (mBackgroundScaled)
  13282. {
  13283. // check whether mScaledBackground needs to be updated:
  13284. QSize scaledSize(mBackgroundPixmap.size());
  13285. scaledSize.scale(mViewport.size(), mBackgroundScaledMode);
  13286. if (mScaledBackgroundPixmap.size() != scaledSize)
  13287. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
  13288. painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect());
  13289. } else
  13290. {
  13291. painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()));
  13292. }
  13293. }
  13294. }
  13295. /*! \internal
  13296. Goes through the layers and makes sure this QCustomPlot instance holds the correct number of
  13297. paint buffers and that they have the correct configuration (size, pixel ratio, etc.).
  13298. Allocations, reallocations and deletions of paint buffers are performed as necessary. It also
  13299. associates the paint buffers with the layers, so they draw themselves into the right buffer when
  13300. \ref QCPLayer::drawToPaintBuffer is called. This means it associates adjacent \ref
  13301. QCPLayer::lmLogical layers to a mutual paint buffer and creates dedicated paint buffers for
  13302. layers in \ref QCPLayer::lmBuffered mode.
  13303. This method uses \ref createPaintBuffer to create new paint buffers.
  13304. After this method, the paint buffers are empty (filled with \c Qt::transparent) and invalidated
  13305. (so an attempt to replot only a single buffered layer causes a full replot).
  13306. This method is called in every \ref replot call, prior to actually drawing the layers (into their
  13307. associated paint buffer). If the paint buffers don't need changing/reallocating, this method
  13308. basically leaves them alone and thus finishes very fast.
  13309. */
  13310. void QCustomPlot::setupPaintBuffers()
  13311. {
  13312. int bufferIndex = 0;
  13313. if (mPaintBuffers.isEmpty())
  13314. mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
  13315. for (int layerIndex = 0; layerIndex < mLayers.size(); ++layerIndex)
  13316. {
  13317. QCPLayer *layer = mLayers.at(layerIndex);
  13318. if (layer->mode() == QCPLayer::lmLogical)
  13319. {
  13320. layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef();
  13321. } else if (layer->mode() == QCPLayer::lmBuffered)
  13322. {
  13323. ++bufferIndex;
  13324. if (bufferIndex >= mPaintBuffers.size())
  13325. mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
  13326. layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef();
  13327. 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
  13328. {
  13329. ++bufferIndex;
  13330. if (bufferIndex >= mPaintBuffers.size())
  13331. mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
  13332. }
  13333. }
  13334. }
  13335. // remove unneeded buffers:
  13336. while (mPaintBuffers.size()-1 > bufferIndex)
  13337. mPaintBuffers.removeLast();
  13338. // resize buffers to viewport size and clear contents:
  13339. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  13340. {
  13341. buffer->setSize(viewport().size()); // won't do anything if already correct size
  13342. buffer->clear(Qt::transparent);
  13343. buffer->setInvalidated();
  13344. }
  13345. }
  13346. /*! \internal
  13347. This method is used by \ref setupPaintBuffers when it needs to create new paint buffers.
  13348. Depending on the current setting of \ref setOpenGl, and the current Qt version, different
  13349. backends (subclasses of \ref QCPAbstractPaintBuffer) are created, initialized with the proper
  13350. size and device pixel ratio, and returned.
  13351. */
  13352. QCPAbstractPaintBuffer *QCustomPlot::createPaintBuffer()
  13353. {
  13354. if (mOpenGl)
  13355. {
  13356. #if defined(QCP_OPENGL_FBO)
  13357. return new QCPPaintBufferGlFbo(viewport().size(), mBufferDevicePixelRatio, mGlContext, mGlPaintDevice);
  13358. #elif defined(QCP_OPENGL_PBUFFER)
  13359. return new QCPPaintBufferGlPbuffer(viewport().size(), mBufferDevicePixelRatio, mOpenGlMultisamples);
  13360. #else
  13361. 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.";
  13362. return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio);
  13363. #endif
  13364. } else
  13365. return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio);
  13366. }
  13367. /*!
  13368. This method returns whether any of the paint buffers held by this QCustomPlot instance are
  13369. invalidated.
  13370. If any buffer is invalidated, a partial replot (\ref QCPLayer::replot) is not allowed and always
  13371. causes a full replot (\ref QCustomPlot::replot) of all layers. This is the case when for example
  13372. the layer order has changed, new layers were added or removed, layer modes were changed (\ref
  13373. QCPLayer::setMode), or layerables were added or removed.
  13374. \see QCPAbstractPaintBuffer::setInvalidated
  13375. */
  13376. bool QCustomPlot::hasInvalidatedPaintBuffers()
  13377. {
  13378. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  13379. {
  13380. if (buffer->invalidated())
  13381. return true;
  13382. }
  13383. return false;
  13384. }
  13385. /*! \internal
  13386. When \ref setOpenGl is set to true, this method is used to initialize OpenGL (create a context,
  13387. surface, paint device).
  13388. Returns true on success.
  13389. If this method is successful, all paint buffers should be deleted and then reallocated by calling
  13390. \ref setupPaintBuffers, so the OpenGL-based paint buffer subclasses (\ref
  13391. QCPPaintBufferGlPbuffer, \ref QCPPaintBufferGlFbo) are used for subsequent replots.
  13392. \see freeOpenGl
  13393. */
  13394. bool QCustomPlot::setupOpenGl()
  13395. {
  13396. #ifdef QCP_OPENGL_FBO
  13397. freeOpenGl();
  13398. QSurfaceFormat proposedSurfaceFormat;
  13399. proposedSurfaceFormat.setSamples(mOpenGlMultisamples);
  13400. #ifdef QCP_OPENGL_OFFSCREENSURFACE
  13401. QOffscreenSurface *surface = new QOffscreenSurface;
  13402. #else
  13403. QWindow *surface = new QWindow;
  13404. surface->setSurfaceType(QSurface::OpenGLSurface);
  13405. #endif
  13406. surface->setFormat(proposedSurfaceFormat);
  13407. surface->create();
  13408. mGlSurface = QSharedPointer<QSurface>(surface);
  13409. mGlContext = QSharedPointer<QOpenGLContext>(new QOpenGLContext);
  13410. mGlContext->setFormat(mGlSurface->format());
  13411. if (!mGlContext->create())
  13412. {
  13413. qDebug() << Q_FUNC_INFO << "Failed to create OpenGL context";
  13414. mGlContext.clear();
  13415. mGlSurface.clear();
  13416. return false;
  13417. }
  13418. if (!mGlContext->makeCurrent(mGlSurface.data())) // context needs to be current to create paint device
  13419. {
  13420. qDebug() << Q_FUNC_INFO << "Failed to make opengl context current";
  13421. mGlContext.clear();
  13422. mGlSurface.clear();
  13423. return false;
  13424. }
  13425. if (!QOpenGLFramebufferObject::hasOpenGLFramebufferObjects())
  13426. {
  13427. qDebug() << Q_FUNC_INFO << "OpenGL of this system doesn't support frame buffer objects";
  13428. mGlContext.clear();
  13429. mGlSurface.clear();
  13430. return false;
  13431. }
  13432. mGlPaintDevice = QSharedPointer<QOpenGLPaintDevice>(new QOpenGLPaintDevice);
  13433. return true;
  13434. #elif defined(QCP_OPENGL_PBUFFER)
  13435. return QGLFormat::hasOpenGL();
  13436. #else
  13437. return false;
  13438. #endif
  13439. }
  13440. /*! \internal
  13441. When \ref setOpenGl is set to false, this method is used to deinitialize OpenGL (releases the
  13442. context and frees resources).
  13443. After OpenGL is disabled, all paint buffers should be deleted and then reallocated by calling
  13444. \ref setupPaintBuffers, so the standard software rendering paint buffer subclass (\ref
  13445. QCPPaintBufferPixmap) is used for subsequent replots.
  13446. \see setupOpenGl
  13447. */
  13448. void QCustomPlot::freeOpenGl()
  13449. {
  13450. #ifdef QCP_OPENGL_FBO
  13451. mGlPaintDevice.clear();
  13452. mGlContext.clear();
  13453. mGlSurface.clear();
  13454. #endif
  13455. }
  13456. /*! \internal
  13457. This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot
  13458. so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly.
  13459. */
  13460. void QCustomPlot::axisRemoved(QCPAxis *axis)
  13461. {
  13462. if (xAxis == axis)
  13463. xAxis = nullptr;
  13464. if (xAxis2 == axis)
  13465. xAxis2 = nullptr;
  13466. if (yAxis == axis)
  13467. yAxis = nullptr;
  13468. if (yAxis2 == axis)
  13469. yAxis2 = nullptr;
  13470. // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers
  13471. }
  13472. /*! \internal
  13473. This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so
  13474. it may clear its QCustomPlot::legend member accordingly.
  13475. */
  13476. void QCustomPlot::legendRemoved(QCPLegend *legend)
  13477. {
  13478. if (this->legend == legend)
  13479. this->legend = nullptr;
  13480. }
  13481. /*! \internal
  13482. This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref
  13483. setSelectionRectMode is set to \ref QCP::srmSelect.
  13484. First, it determines which axis rect was the origin of the selection rect judging by the starting
  13485. point of the selection. Then it goes through the plottables (\ref QCPAbstractPlottable1D to be
  13486. precise) associated with that axis rect and finds the data points that are in \a rect. It does
  13487. this by querying their \ref QCPAbstractPlottable1D::selectTestRect method.
  13488. Then, the actual selection is done by calling the plottables' \ref
  13489. QCPAbstractPlottable::selectEvent, placing the found selected data points in the \a details
  13490. parameter as <tt>QVariant(\ref QCPDataSelection)</tt>. All plottables that weren't touched by \a
  13491. rect receive a \ref QCPAbstractPlottable::deselectEvent.
  13492. \see processRectZoom
  13493. */
  13494. void QCustomPlot::processRectSelection(QRect rect, QMouseEvent *event)
  13495. {
  13496. typedef QPair<QCPAbstractPlottable*, QCPDataSelection> SelectionCandidate;
  13497. typedef QMultiMap<int, SelectionCandidate> SelectionCandidates; // map key is number of selected data points, so we have selections sorted by size
  13498. bool selectionStateChanged = false;
  13499. if (mInteractions.testFlag(QCP::iSelectPlottables))
  13500. {
  13501. SelectionCandidates potentialSelections;
  13502. QRectF rectF(rect.normalized());
  13503. if (QCPAxisRect *affectedAxisRect = axisRectAt(rectF.topLeft()))
  13504. {
  13505. // determine plottables that were hit by the rect and thus are candidates for selection:
  13506. foreach (QCPAbstractPlottable *plottable, affectedAxisRect->plottables())
  13507. {
  13508. if (QCPPlottableInterface1D *plottableInterface = plottable->interface1D())
  13509. {
  13510. QCPDataSelection dataSel = plottableInterface->selectTestRect(rectF, true);
  13511. if (!dataSel.isEmpty())
  13512. potentialSelections.insert(dataSel.dataPointCount(), SelectionCandidate(plottable, dataSel));
  13513. }
  13514. }
  13515. if (!mInteractions.testFlag(QCP::iMultiSelect))
  13516. {
  13517. // only leave plottable with most selected points in map, since we will only select a single plottable:
  13518. if (!potentialSelections.isEmpty())
  13519. {
  13520. SelectionCandidates::iterator it = potentialSelections.begin();
  13521. while (it != std::prev(potentialSelections.end())) // erase all except last element
  13522. it = potentialSelections.erase(it);
  13523. }
  13524. }
  13525. bool additive = event->modifiers().testFlag(mMultiSelectModifier);
  13526. // deselect all other layerables if not additive selection:
  13527. if (!additive)
  13528. {
  13529. // emit deselection except to those plottables who will be selected afterwards:
  13530. foreach (QCPLayer *layer, mLayers)
  13531. {
  13532. foreach (QCPLayerable *layerable, layer->children())
  13533. {
  13534. if ((potentialSelections.isEmpty() || potentialSelections.constBegin()->first != layerable) && mInteractions.testFlag(layerable->selectionCategory()))
  13535. {
  13536. bool selChanged = false;
  13537. layerable->deselectEvent(&selChanged);
  13538. selectionStateChanged |= selChanged;
  13539. }
  13540. }
  13541. }
  13542. }
  13543. // go through selections in reverse (largest selection first) and emit select events:
  13544. SelectionCandidates::const_iterator it = potentialSelections.constEnd();
  13545. while (it != potentialSelections.constBegin())
  13546. {
  13547. --it;
  13548. if (mInteractions.testFlag(it.value().first->selectionCategory()))
  13549. {
  13550. bool selChanged = false;
  13551. it.value().first->selectEvent(event, additive, QVariant::fromValue(it.value().second), &selChanged);
  13552. selectionStateChanged |= selChanged;
  13553. }
  13554. }
  13555. }
  13556. }
  13557. if (selectionStateChanged)
  13558. {
  13559. emit selectionChangedByUser();
  13560. replot(rpQueuedReplot);
  13561. } else if (mSelectionRect)
  13562. mSelectionRect->layer()->replot();
  13563. }
  13564. /*! \internal
  13565. This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref
  13566. setSelectionRectMode is set to \ref QCP::srmZoom.
  13567. It determines which axis rect was the origin of the selection rect judging by the starting point
  13568. of the selection, and then zooms the axes defined via \ref QCPAxisRect::setRangeZoomAxes to the
  13569. provided \a rect (see \ref QCPAxisRect::zoom).
  13570. \see processRectSelection
  13571. */
  13572. void QCustomPlot::processRectZoom(QRect rect, QMouseEvent *event)
  13573. {
  13574. Q_UNUSED(event)
  13575. if (QCPAxisRect *axisRect = axisRectAt(rect.topLeft()))
  13576. {
  13577. QList<QCPAxis*> affectedAxes = QList<QCPAxis*>() << axisRect->rangeZoomAxes(Qt::Horizontal) << axisRect->rangeZoomAxes(Qt::Vertical);
  13578. affectedAxes.removeAll(static_cast<QCPAxis*>(nullptr));
  13579. axisRect->zoom(QRectF(rect), affectedAxes);
  13580. }
  13581. replot(rpQueuedReplot); // always replot to make selection rect disappear
  13582. }
  13583. /*! \internal
  13584. This method is called when a simple left mouse click was detected on the QCustomPlot surface.
  13585. It first determines the layerable that was hit by the click, and then calls its \ref
  13586. QCPLayerable::selectEvent. All other layerables receive a QCPLayerable::deselectEvent (unless the
  13587. multi-select modifier was pressed, see \ref setMultiSelectModifier).
  13588. In this method the hit layerable is determined a second time using \ref layerableAt (after the
  13589. one in \ref mousePressEvent), because we want \a onlySelectable set to true this time. This
  13590. implies that the mouse event grabber (mMouseEventLayerable) may be a different one from the
  13591. clicked layerable determined here. For example, if a non-selectable layerable is in front of a
  13592. selectable layerable at the click position, the front layerable will receive mouse events but the
  13593. selectable one in the back will receive the \ref QCPLayerable::selectEvent.
  13594. \see processRectSelection, QCPLayerable::selectTest
  13595. */
  13596. void QCustomPlot::processPointSelection(QMouseEvent *event)
  13597. {
  13598. QVariant details;
  13599. QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details);
  13600. bool selectionStateChanged = false;
  13601. bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier);
  13602. // deselect all other layerables if not additive selection:
  13603. if (!additive)
  13604. {
  13605. foreach (QCPLayer *layer, mLayers)
  13606. {
  13607. foreach (QCPLayerable *layerable, layer->children())
  13608. {
  13609. if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory()))
  13610. {
  13611. bool selChanged = false;
  13612. layerable->deselectEvent(&selChanged);
  13613. selectionStateChanged |= selChanged;
  13614. }
  13615. }
  13616. }
  13617. }
  13618. if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory()))
  13619. {
  13620. // a layerable was actually clicked, call its selectEvent:
  13621. bool selChanged = false;
  13622. clickedLayerable->selectEvent(event, additive, details, &selChanged);
  13623. selectionStateChanged |= selChanged;
  13624. }
  13625. if (selectionStateChanged)
  13626. {
  13627. emit selectionChangedByUser();
  13628. replot(rpQueuedReplot);
  13629. }
  13630. }
  13631. /*! \internal
  13632. Registers the specified plottable with this QCustomPlot and, if \ref setAutoAddPlottableToLegend
  13633. is enabled, adds it to the legend (QCustomPlot::legend). QCustomPlot takes ownership of the
  13634. plottable.
  13635. Returns true on success, i.e. when \a plottable isn't already in this plot and the parent plot of
  13636. \a plottable is this QCustomPlot.
  13637. This method is called automatically in the QCPAbstractPlottable base class constructor.
  13638. */
  13639. bool QCustomPlot::registerPlottable(QCPAbstractPlottable *plottable)
  13640. {
  13641. if (mPlottables.contains(plottable))
  13642. {
  13643. qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast<quintptr>(plottable);
  13644. return false;
  13645. }
  13646. if (plottable->parentPlot() != this)
  13647. {
  13648. qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(plottable);
  13649. return false;
  13650. }
  13651. mPlottables.append(plottable);
  13652. // possibly add plottable to legend:
  13653. if (mAutoAddPlottableToLegend)
  13654. plottable->addToLegend();
  13655. if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
  13656. plottable->setLayer(currentLayer());
  13657. return true;
  13658. }
  13659. /*! \internal
  13660. In order to maintain the simplified graph interface of QCustomPlot, this method is called by the
  13661. QCPGraph constructor to register itself with this QCustomPlot's internal graph list. Returns true
  13662. on success, i.e. if \a graph is valid and wasn't already registered with this QCustomPlot.
  13663. This graph specific registration happens in addition to the call to \ref registerPlottable by the
  13664. QCPAbstractPlottable base class.
  13665. */
  13666. bool QCustomPlot::registerGraph(QCPGraph *graph)
  13667. {
  13668. if (!graph)
  13669. {
  13670. qDebug() << Q_FUNC_INFO << "passed graph is zero";
  13671. return false;
  13672. }
  13673. if (mGraphs.contains(graph))
  13674. {
  13675. qDebug() << Q_FUNC_INFO << "graph already registered with this QCustomPlot";
  13676. return false;
  13677. }
  13678. mGraphs.append(graph);
  13679. return true;
  13680. }
  13681. /*! \internal
  13682. Registers the specified item with this QCustomPlot. QCustomPlot takes ownership of the item.
  13683. Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a
  13684. item is this QCustomPlot.
  13685. This method is called automatically in the QCPAbstractItem base class constructor.
  13686. */
  13687. bool QCustomPlot::registerItem(QCPAbstractItem *item)
  13688. {
  13689. if (mItems.contains(item))
  13690. {
  13691. qDebug() << Q_FUNC_INFO << "item already added to this QCustomPlot:" << reinterpret_cast<quintptr>(item);
  13692. return false;
  13693. }
  13694. if (item->parentPlot() != this)
  13695. {
  13696. qDebug() << Q_FUNC_INFO << "item not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(item);
  13697. return false;
  13698. }
  13699. mItems.append(item);
  13700. if (!item->layer()) // usually the layer is already set in the constructor of the item (via QCPLayerable constructor)
  13701. item->setLayer(currentLayer());
  13702. return true;
  13703. }
  13704. /*! \internal
  13705. Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called
  13706. after every operation that changes the layer indices, like layer removal, layer creation, layer
  13707. moving.
  13708. */
  13709. void QCustomPlot::updateLayerIndices() const
  13710. {
  13711. for (int i=0; i<mLayers.size(); ++i)
  13712. mLayers.at(i)->mIndex = i;
  13713. }
  13714. /*! \internal
  13715. Returns the top-most layerable at pixel position \a pos. If \a onlySelectable is set to true,
  13716. only those layerables that are selectable will be considered. (Layerable subclasses communicate
  13717. their selectability via the QCPLayerable::selectTest method, by returning -1.)
  13718. \a selectionDetails is an output parameter that contains selection specifics of the affected
  13719. layerable. This is useful if the respective layerable shall be given a subsequent
  13720. QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
  13721. information about which part of the layerable was hit, in multi-part layerables (e.g.
  13722. QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref
  13723. QCPDataSelection instance with the single data point which is closest to \a pos.
  13724. \see layerableListAt, layoutElementAt, axisRectAt
  13725. */
  13726. QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const
  13727. {
  13728. QList<QVariant> details;
  13729. QList<QCPLayerable*> candidates = layerableListAt(pos, onlySelectable, selectionDetails ? &details : nullptr);
  13730. if (selectionDetails && !details.isEmpty())
  13731. *selectionDetails = details.first();
  13732. if (!candidates.isEmpty())
  13733. return candidates.first();
  13734. else
  13735. return nullptr;
  13736. }
  13737. /*! \internal
  13738. Returns the layerables at pixel position \a pos. If \a onlySelectable is set to true, only those
  13739. layerables that are selectable will be considered. (Layerable subclasses communicate their
  13740. selectability via the QCPLayerable::selectTest method, by returning -1.)
  13741. The returned list is sorted by the layerable/drawing order such that the layerable that appears
  13742. on top in the plot is at index 0 of the returned list. If you only need to know the top
  13743. layerable, rather use \ref layerableAt.
  13744. \a selectionDetails is an output parameter that contains selection specifics of the affected
  13745. layerable. This is useful if the respective layerable shall be given a subsequent
  13746. QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
  13747. information about which part of the layerable was hit, in multi-part layerables (e.g.
  13748. QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref
  13749. QCPDataSelection instance with the single data point which is closest to \a pos.
  13750. \see layerableAt, layoutElementAt, axisRectAt
  13751. */
  13752. QList<QCPLayerable*> QCustomPlot::layerableListAt(const QPointF &pos, bool onlySelectable, QList<QVariant> *selectionDetails) const
  13753. {
  13754. QList<QCPLayerable*> result;
  13755. for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex)
  13756. {
  13757. const QList<QCPLayerable*> layerables = mLayers.at(layerIndex)->children();
  13758. for (int i=layerables.size()-1; i>=0; --i)
  13759. {
  13760. if (!layerables.at(i)->realVisibility())
  13761. continue;
  13762. QVariant details;
  13763. double dist = layerables.at(i)->selectTest(pos, onlySelectable, selectionDetails ? &details : nullptr);
  13764. if (dist >= 0 && dist < selectionTolerance())
  13765. {
  13766. result.append(layerables.at(i));
  13767. if (selectionDetails)
  13768. selectionDetails->append(details);
  13769. }
  13770. }
  13771. }
  13772. return result;
  13773. }
  13774. /*!
  13775. Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is
  13776. sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead
  13777. to a full resolution file with width 200.) If the \a format supports compression, \a quality may
  13778. be between 0 and 100 to control it.
  13779. Returns true on success. If this function fails, most likely the given \a format isn't supported
  13780. by the system, see Qt docs about QImageWriter::supportedImageFormats().
  13781. The \a resolution will be written to the image file header (if the file format supports this) and
  13782. has no direct consequence for the quality or the pixel size. However, if opening the image with a
  13783. tool which respects the metadata, it will be able to scale the image to match either a given size
  13784. in real units of length (inch, centimeters, etc.), or the target display DPI. You can specify in
  13785. which units \a resolution is given, by setting \a resolutionUnit. The \a resolution is converted
  13786. to the format's expected resolution unit internally.
  13787. \see saveBmp, saveJpg, savePng, savePdf
  13788. */
  13789. bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
  13790. {
  13791. QImage buffer = toPixmap(width, height, scale).toImage();
  13792. int dotsPerMeter = 0;
  13793. switch (resolutionUnit)
  13794. {
  13795. case QCP::ruDotsPerMeter: dotsPerMeter = resolution; break;
  13796. case QCP::ruDotsPerCentimeter: dotsPerMeter = resolution*100; break;
  13797. case QCP::ruDotsPerInch: dotsPerMeter = int(resolution/0.0254); break;
  13798. }
  13799. buffer.setDotsPerMeterX(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools
  13800. buffer.setDotsPerMeterY(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools
  13801. if (!buffer.isNull())
  13802. return buffer.save(fileName, format, quality);
  13803. else
  13804. return false;
  13805. }
  13806. /*!
  13807. Renders the plot to a pixmap and returns it.
  13808. The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and
  13809. scale 2.0 lead to a full resolution pixmap with width 200.)
  13810. \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf
  13811. */
  13812. QPixmap QCustomPlot::toPixmap(int width, int height, double scale)
  13813. {
  13814. // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too.
  13815. int newWidth, newHeight;
  13816. if (width == 0 || height == 0)
  13817. {
  13818. newWidth = this->width();
  13819. newHeight = this->height();
  13820. } else
  13821. {
  13822. newWidth = width;
  13823. newHeight = height;
  13824. }
  13825. int scaledWidth = qRound(scale*newWidth);
  13826. int scaledHeight = qRound(scale*newHeight);
  13827. QPixmap result(scaledWidth, scaledHeight);
  13828. result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later
  13829. QCPPainter painter;
  13830. painter.begin(&result);
  13831. if (painter.isActive())
  13832. {
  13833. QRect oldViewport = viewport();
  13834. setViewport(QRect(0, 0, newWidth, newHeight));
  13835. painter.setMode(QCPPainter::pmNoCaching);
  13836. if (!qFuzzyCompare(scale, 1.0))
  13837. {
  13838. if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales
  13839. painter.setMode(QCPPainter::pmNonCosmetic);
  13840. painter.scale(scale, scale);
  13841. }
  13842. if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) // solid fills were done a few lines above with QPixmap::fill
  13843. painter.fillRect(mViewport, mBackgroundBrush);
  13844. draw(&painter);
  13845. setViewport(oldViewport);
  13846. painter.end();
  13847. } else // might happen if pixmap has width or height zero
  13848. {
  13849. qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap";
  13850. return QPixmap();
  13851. }
  13852. return result;
  13853. }
  13854. /*!
  13855. Renders the plot using the passed \a painter.
  13856. 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
  13857. appear scaled accordingly.
  13858. \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter
  13859. on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with
  13860. the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter.
  13861. \see toPixmap
  13862. */
  13863. void QCustomPlot::toPainter(QCPPainter *painter, int width, int height)
  13864. {
  13865. // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too.
  13866. int newWidth, newHeight;
  13867. if (width == 0 || height == 0)
  13868. {
  13869. newWidth = this->width();
  13870. newHeight = this->height();
  13871. } else
  13872. {
  13873. newWidth = width;
  13874. newHeight = height;
  13875. }
  13876. if (painter->isActive())
  13877. {
  13878. QRect oldViewport = viewport();
  13879. setViewport(QRect(0, 0, newWidth, newHeight));
  13880. painter->setMode(QCPPainter::pmNoCaching);
  13881. 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
  13882. painter->fillRect(mViewport, mBackgroundBrush);
  13883. draw(painter);
  13884. setViewport(oldViewport);
  13885. } else
  13886. qDebug() << Q_FUNC_INFO << "Passed painter is not active";
  13887. }
  13888. /* end of 'src/core.cpp' */
  13889. /* including file 'src/colorgradient.cpp' */
  13890. /* modified 2022-11-06T12:45:56, size 25408 */
  13891. ////////////////////////////////////////////////////////////////////////////////////////////////////
  13892. //////////////////// QCPColorGradient
  13893. ////////////////////////////////////////////////////////////////////////////////////////////////////
  13894. /*! \class QCPColorGradient
  13895. \brief Defines a color gradient for use with e.g. \ref QCPColorMap
  13896. This class describes a color gradient which can be used to encode data with color. For example,
  13897. QCPColorMap and QCPColorScale have \ref QCPColorMap::setGradient "setGradient" methods which
  13898. take an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color)
  13899. with a \a position from 0 to 1. In between these defined color positions, the
  13900. color will be interpolated linearly either in RGB or HSV space, see \ref setColorInterpolation.
  13901. Alternatively, load one of the preset color gradients shown in the image below, with \ref
  13902. loadPreset, or by directly specifying the preset in the constructor.
  13903. Apart from red, green and blue components, the gradient also interpolates the alpha values of the
  13904. configured color stops. This allows to display some portions of the data range as transparent in
  13905. the plot.
  13906. How NaN values are interpreted can be configured with \ref setNanHandling.
  13907. \image html QCPColorGradient.png
  13908. The constructor \ref QCPColorGradient(GradientPreset preset) allows directly converting a \ref
  13909. GradientPreset to a QCPColorGradient. This means that you can directly pass \ref GradientPreset
  13910. to all the \a setGradient methods, e.g.:
  13911. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorgradient-setgradient
  13912. The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the
  13913. color gradient shall be applied periodically (wrapping around) to data values that lie outside
  13914. the data range specified on the plottable instance can be controlled with \ref setPeriodic.
  13915. */
  13916. /*!
  13917. Constructs a new, empty QCPColorGradient with no predefined color stops. You can add own color
  13918. stops with \ref setColorStopAt.
  13919. The color level count is initialized to 350.
  13920. */
  13921. QCPColorGradient::QCPColorGradient() :
  13922. mLevelCount(350),
  13923. mColorInterpolation(ciRGB),
  13924. mNanHandling(nhNone),
  13925. mNanColor(Qt::black),
  13926. mPeriodic(false),
  13927. mColorBufferInvalidated(true)
  13928. {
  13929. mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
  13930. }
  13931. /*!
  13932. Constructs a new QCPColorGradient initialized with the colors and color interpolation according
  13933. to \a preset.
  13934. The color level count is initialized to 350.
  13935. */
  13936. QCPColorGradient::QCPColorGradient(GradientPreset preset) :
  13937. mLevelCount(350),
  13938. mColorInterpolation(ciRGB),
  13939. mNanHandling(nhNone),
  13940. mNanColor(Qt::black),
  13941. mPeriodic(false),
  13942. mColorBufferInvalidated(true)
  13943. {
  13944. mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
  13945. loadPreset(preset);
  13946. }
  13947. /* undocumented operator */
  13948. bool QCPColorGradient::operator==(const QCPColorGradient &other) const
  13949. {
  13950. return ((other.mLevelCount == this->mLevelCount) &&
  13951. (other.mColorInterpolation == this->mColorInterpolation) &&
  13952. (other.mNanHandling == this ->mNanHandling) &&
  13953. (other.mNanColor == this->mNanColor) &&
  13954. (other.mPeriodic == this->mPeriodic) &&
  13955. (other.mColorStops == this->mColorStops));
  13956. }
  13957. /*!
  13958. Sets the number of discretization levels of the color gradient to \a n. The default is 350 which
  13959. is typically enough to create a smooth appearance. The minimum number of levels is 2.
  13960. \image html QCPColorGradient-levelcount.png
  13961. */
  13962. void QCPColorGradient::setLevelCount(int n)
  13963. {
  13964. if (n < 2)
  13965. {
  13966. qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n;
  13967. n = 2;
  13968. }
  13969. if (n != mLevelCount)
  13970. {
  13971. mLevelCount = n;
  13972. mColorBufferInvalidated = true;
  13973. }
  13974. }
  13975. /*!
  13976. Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the
  13977. colors are the values of the passed QMap \a colorStops. In between these color stops, the color
  13978. is interpolated according to \ref setColorInterpolation.
  13979. A more convenient way to create a custom gradient may be to clear all color stops with \ref
  13980. clearColorStops (or creating a new, empty QCPColorGradient) and then adding them one by one with
  13981. \ref setColorStopAt.
  13982. \see clearColorStops
  13983. */
  13984. void QCPColorGradient::setColorStops(const QMap<double, QColor> &colorStops)
  13985. {
  13986. mColorStops = colorStops;
  13987. mColorBufferInvalidated = true;
  13988. }
  13989. /*!
  13990. Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between
  13991. these color stops, the color is interpolated according to \ref setColorInterpolation.
  13992. \see setColorStops, clearColorStops
  13993. */
  13994. void QCPColorGradient::setColorStopAt(double position, const QColor &color)
  13995. {
  13996. mColorStops.insert(position, color);
  13997. mColorBufferInvalidated = true;
  13998. }
  13999. /*!
  14000. Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be
  14001. interpolated linearly in RGB or in HSV color space.
  14002. For example, a sweep in RGB space from red to green will have a muddy brown intermediate color,
  14003. whereas in HSV space the intermediate color is yellow.
  14004. */
  14005. void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation)
  14006. {
  14007. if (interpolation != mColorInterpolation)
  14008. {
  14009. mColorInterpolation = interpolation;
  14010. mColorBufferInvalidated = true;
  14011. }
  14012. }
  14013. /*!
  14014. Sets how NaNs in the data are displayed in the plot.
  14015. \see setNanColor
  14016. */
  14017. void QCPColorGradient::setNanHandling(QCPColorGradient::NanHandling handling)
  14018. {
  14019. mNanHandling = handling;
  14020. }
  14021. /*!
  14022. Sets the color that NaN data is represented by, if \ref setNanHandling is set
  14023. to ref nhNanColor.
  14024. \see setNanHandling
  14025. */
  14026. void QCPColorGradient::setNanColor(const QColor &color)
  14027. {
  14028. mNanColor = color;
  14029. }
  14030. /*!
  14031. Sets whether data points that are outside the configured data range (e.g. \ref
  14032. QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether
  14033. they all have the same color, corresponding to the respective gradient boundary color.
  14034. \image html QCPColorGradient-periodic.png
  14035. As shown in the image above, gradients that have the same start and end color are especially
  14036. suitable for a periodic gradient mapping, since they produce smooth color transitions throughout
  14037. the color map. A preset that has this property is \ref gpHues.
  14038. In practice, using periodic color gradients makes sense when the data corresponds to a periodic
  14039. dimension, such as an angle or a phase. If this is not the case, the color encoding might become
  14040. ambiguous, because multiple different data values are shown as the same color.
  14041. */
  14042. void QCPColorGradient::setPeriodic(bool enabled)
  14043. {
  14044. mPeriodic = enabled;
  14045. }
  14046. /*! \overload
  14047. This method is used to quickly convert a \a data array to colors. The colors will be output in
  14048. the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this
  14049. function. The data range that shall be used for mapping the data value to the gradient is passed
  14050. in \a range. \a logarithmic indicates whether the data values shall be mapped to colors
  14051. logarithmically.
  14052. if \a data actually contains 2D-data linearized via <tt>[row*columnCount + column]</tt>, you can
  14053. set \a dataIndexFactor to <tt>columnCount</tt> to convert a column instead of a row of the data
  14054. array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data
  14055. is addressed <tt>data[i*dataIndexFactor]</tt>.
  14056. Use the overloaded method to additionally provide alpha map data.
  14057. The QRgb values that are placed in \a scanLine have their r, g, and b components premultiplied
  14058. with alpha (see QImage::Format_ARGB32_Premultiplied).
  14059. */
  14060. void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
  14061. {
  14062. // If you change something here, make sure to also adapt color() and the other colorize() overload
  14063. if (!data)
  14064. {
  14065. qDebug() << Q_FUNC_INFO << "null pointer given as data";
  14066. return;
  14067. }
  14068. if (!scanLine)
  14069. {
  14070. qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
  14071. return;
  14072. }
  14073. if (mColorBufferInvalidated)
  14074. updateColorBuffer();
  14075. const bool skipNanCheck = mNanHandling == nhNone;
  14076. const double posToIndexFactor = !logarithmic ? (mLevelCount-1)/range.size() : (mLevelCount-1)/qLn(range.upper/range.lower);
  14077. for (int i=0; i<n; ++i)
  14078. {
  14079. const double value = data[dataIndexFactor*i];
  14080. if (skipNanCheck || !std::isnan(value))
  14081. {
  14082. qint64 index = qint64((!logarithmic ? value-range.lower : qLn(value/range.lower)) * posToIndexFactor);
  14083. if (!mPeriodic)
  14084. {
  14085. index = qBound(qint64(0), index, qint64(mLevelCount-1));
  14086. } else
  14087. {
  14088. index %= mLevelCount;
  14089. if (index < 0)
  14090. index += mLevelCount;
  14091. }
  14092. scanLine[i] = mColorBuffer.at(index);
  14093. } else
  14094. {
  14095. switch(mNanHandling)
  14096. {
  14097. case nhLowestColor: scanLine[i] = mColorBuffer.first(); break;
  14098. case nhHighestColor: scanLine[i] = mColorBuffer.last(); break;
  14099. case nhTransparent: scanLine[i] = qRgba(0, 0, 0, 0); break;
  14100. case nhNanColor: scanLine[i] = mNanColor.rgba(); break;
  14101. case nhNone: break; // shouldn't happen
  14102. }
  14103. }
  14104. }
  14105. }
  14106. /*! \overload
  14107. Additionally to the other overload of \ref colorize, this method takes the array \a alpha, which
  14108. has the same size and structure as \a data and encodes the alpha information per data point.
  14109. The QRgb values that are placed in \a scanLine have their r, g and b components premultiplied
  14110. with alpha (see QImage::Format_ARGB32_Premultiplied).
  14111. */
  14112. void QCPColorGradient::colorize(const double *data, const unsigned char *alpha, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
  14113. {
  14114. // If you change something here, make sure to also adapt color() and the other colorize() overload
  14115. if (!data)
  14116. {
  14117. qDebug() << Q_FUNC_INFO << "null pointer given as data";
  14118. return;
  14119. }
  14120. if (!alpha)
  14121. {
  14122. qDebug() << Q_FUNC_INFO << "null pointer given as alpha";
  14123. return;
  14124. }
  14125. if (!scanLine)
  14126. {
  14127. qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
  14128. return;
  14129. }
  14130. if (mColorBufferInvalidated)
  14131. updateColorBuffer();
  14132. const bool skipNanCheck = mNanHandling == nhNone;
  14133. const double posToIndexFactor = !logarithmic ? (mLevelCount-1)/range.size() : (mLevelCount-1)/qLn(range.upper/range.lower);
  14134. for (int i=0; i<n; ++i)
  14135. {
  14136. const double value = data[dataIndexFactor*i];
  14137. if (skipNanCheck || !std::isnan(value))
  14138. {
  14139. qint64 index = qint64((!logarithmic ? value-range.lower : qLn(value/range.lower)) * posToIndexFactor);
  14140. if (!mPeriodic)
  14141. {
  14142. index = qBound(qint64(0), index, qint64(mLevelCount-1));
  14143. } else
  14144. {
  14145. index %= mLevelCount;
  14146. if (index < 0)
  14147. index += mLevelCount;
  14148. }
  14149. if (alpha[dataIndexFactor*i] == 255)
  14150. {
  14151. scanLine[i] = mColorBuffer.at(index);
  14152. } else
  14153. {
  14154. const QRgb rgb = mColorBuffer.at(index);
  14155. const float alphaF = alpha[dataIndexFactor*i]/255.0f;
  14156. 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
  14157. }
  14158. } else
  14159. {
  14160. switch(mNanHandling)
  14161. {
  14162. case nhLowestColor: scanLine[i] = mColorBuffer.first(); break;
  14163. case nhHighestColor: scanLine[i] = mColorBuffer.last(); break;
  14164. case nhTransparent: scanLine[i] = qRgba(0, 0, 0, 0); break;
  14165. case nhNanColor: scanLine[i] = mNanColor.rgba(); break;
  14166. case nhNone: break; // shouldn't happen
  14167. }
  14168. }
  14169. }
  14170. }
  14171. /*! \internal
  14172. This method is used to colorize a single data value given in \a position, to colors. The data
  14173. range that shall be used for mapping the data value to the gradient is passed in \a range. \a
  14174. logarithmic indicates whether the data value shall be mapped to a color logarithmically.
  14175. If an entire array of data values shall be converted, rather use \ref colorize, for better
  14176. performance.
  14177. The returned QRgb has its r, g and b components premultiplied with alpha (see
  14178. QImage::Format_ARGB32_Premultiplied).
  14179. */
  14180. QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic)
  14181. {
  14182. // If you change something here, make sure to also adapt ::colorize()
  14183. if (mColorBufferInvalidated)
  14184. updateColorBuffer();
  14185. const bool skipNanCheck = mNanHandling == nhNone;
  14186. if (!skipNanCheck && std::isnan(position))
  14187. {
  14188. switch(mNanHandling)
  14189. {
  14190. case nhLowestColor: return mColorBuffer.first();
  14191. case nhHighestColor: return mColorBuffer.last();
  14192. case nhTransparent: return qRgba(0, 0, 0, 0);
  14193. case nhNanColor: return mNanColor.rgba();
  14194. case nhNone: return qRgba(0, 0, 0, 0); // shouldn't happen
  14195. }
  14196. }
  14197. const double posToIndexFactor = !logarithmic ? (mLevelCount-1)/range.size() : (mLevelCount-1)/qLn(range.upper/range.lower);
  14198. int index = int((!logarithmic ? position-range.lower : qLn(position/range.lower)) * posToIndexFactor);
  14199. if (!mPeriodic)
  14200. {
  14201. index = qBound(0, index, mLevelCount-1);
  14202. } else
  14203. {
  14204. index %= mLevelCount;
  14205. if (index < 0)
  14206. index += mLevelCount;
  14207. }
  14208. return mColorBuffer.at(index);
  14209. }
  14210. /*!
  14211. Clears the current color stops and loads the specified \a preset. A preset consists of predefined
  14212. color stops and the corresponding color interpolation method.
  14213. The available presets are:
  14214. \image html QCPColorGradient.png
  14215. */
  14216. void QCPColorGradient::loadPreset(GradientPreset preset)
  14217. {
  14218. clearColorStops();
  14219. switch (preset)
  14220. {
  14221. case gpGrayscale:
  14222. setColorInterpolation(ciRGB);
  14223. setColorStopAt(0, Qt::black);
  14224. setColorStopAt(1, Qt::white);
  14225. break;
  14226. case gpHot:
  14227. setColorInterpolation(ciRGB);
  14228. setColorStopAt(0, QColor(50, 0, 0));
  14229. setColorStopAt(0.2, QColor(180, 10, 0));
  14230. setColorStopAt(0.4, QColor(245, 50, 0));
  14231. setColorStopAt(0.6, QColor(255, 150, 10));
  14232. setColorStopAt(0.8, QColor(255, 255, 50));
  14233. setColorStopAt(1, QColor(255, 255, 255));
  14234. break;
  14235. case gpCold:
  14236. setColorInterpolation(ciRGB);
  14237. setColorStopAt(0, QColor(0, 0, 50));
  14238. setColorStopAt(0.2, QColor(0, 10, 180));
  14239. setColorStopAt(0.4, QColor(0, 50, 245));
  14240. setColorStopAt(0.6, QColor(10, 150, 255));
  14241. setColorStopAt(0.8, QColor(50, 255, 255));
  14242. setColorStopAt(1, QColor(255, 255, 255));
  14243. break;
  14244. case gpNight:
  14245. setColorInterpolation(ciHSV);
  14246. setColorStopAt(0, QColor(10, 20, 30));
  14247. setColorStopAt(1, QColor(250, 255, 250));
  14248. break;
  14249. case gpCandy:
  14250. setColorInterpolation(ciHSV);
  14251. setColorStopAt(0, QColor(0, 0, 255));
  14252. setColorStopAt(1, QColor(255, 250, 250));
  14253. break;
  14254. case gpGeography:
  14255. setColorInterpolation(ciRGB);
  14256. setColorStopAt(0, QColor(70, 170, 210));
  14257. setColorStopAt(0.20, QColor(90, 160, 180));
  14258. setColorStopAt(0.25, QColor(45, 130, 175));
  14259. setColorStopAt(0.30, QColor(100, 140, 125));
  14260. setColorStopAt(0.5, QColor(100, 140, 100));
  14261. setColorStopAt(0.6, QColor(130, 145, 120));
  14262. setColorStopAt(0.7, QColor(140, 130, 120));
  14263. setColorStopAt(0.9, QColor(180, 190, 190));
  14264. setColorStopAt(1, QColor(210, 210, 230));
  14265. break;
  14266. case gpIon:
  14267. setColorInterpolation(ciHSV);
  14268. setColorStopAt(0, QColor(50, 10, 10));
  14269. setColorStopAt(0.45, QColor(0, 0, 255));
  14270. setColorStopAt(0.8, QColor(0, 255, 255));
  14271. setColorStopAt(1, QColor(0, 255, 0));
  14272. break;
  14273. case gpThermal:
  14274. setColorInterpolation(ciRGB);
  14275. setColorStopAt(0, QColor(0, 0, 50));
  14276. setColorStopAt(0.15, QColor(20, 0, 120));
  14277. setColorStopAt(0.33, QColor(200, 30, 140));
  14278. setColorStopAt(0.6, QColor(255, 100, 0));
  14279. setColorStopAt(0.85, QColor(255, 255, 40));
  14280. setColorStopAt(1, QColor(255, 255, 255));
  14281. break;
  14282. case gpPolar:
  14283. setColorInterpolation(ciRGB);
  14284. setColorStopAt(0, QColor(50, 255, 255));
  14285. setColorStopAt(0.18, QColor(10, 70, 255));
  14286. setColorStopAt(0.28, QColor(10, 10, 190));
  14287. setColorStopAt(0.5, QColor(0, 0, 0));
  14288. setColorStopAt(0.72, QColor(190, 10, 10));
  14289. setColorStopAt(0.82, QColor(255, 70, 10));
  14290. setColorStopAt(1, QColor(255, 255, 50));
  14291. break;
  14292. case gpSpectrum:
  14293. setColorInterpolation(ciHSV);
  14294. setColorStopAt(0, QColor(50, 0, 50));
  14295. setColorStopAt(0.15, QColor(0, 0, 255));
  14296. setColorStopAt(0.35, QColor(0, 255, 255));
  14297. setColorStopAt(0.6, QColor(255, 255, 0));
  14298. setColorStopAt(0.75, QColor(255, 30, 0));
  14299. setColorStopAt(1, QColor(50, 0, 0));
  14300. break;
  14301. case gpJet:
  14302. setColorInterpolation(ciRGB);
  14303. setColorStopAt(0, QColor(0, 0, 100));
  14304. setColorStopAt(0.15, QColor(0, 50, 255));
  14305. setColorStopAt(0.35, QColor(0, 255, 255));
  14306. setColorStopAt(0.65, QColor(255, 255, 0));
  14307. setColorStopAt(0.85, QColor(255, 30, 0));
  14308. setColorStopAt(1, QColor(100, 0, 0));
  14309. break;
  14310. case gpHues:
  14311. setColorInterpolation(ciHSV);
  14312. setColorStopAt(0, QColor(255, 0, 0));
  14313. setColorStopAt(1.0/3.0, QColor(0, 0, 255));
  14314. setColorStopAt(2.0/3.0, QColor(0, 255, 0));
  14315. setColorStopAt(1, QColor(255, 0, 0));
  14316. break;
  14317. }
  14318. }
  14319. /*!
  14320. Clears all color stops.
  14321. \see setColorStops, setColorStopAt
  14322. */
  14323. void QCPColorGradient::clearColorStops()
  14324. {
  14325. mColorStops.clear();
  14326. mColorBufferInvalidated = true;
  14327. }
  14328. /*!
  14329. Returns an inverted gradient. The inverted gradient has all properties as this \ref
  14330. QCPColorGradient, but the order of the color stops is inverted.
  14331. \see setColorStops, setColorStopAt
  14332. */
  14333. QCPColorGradient QCPColorGradient::inverted() const
  14334. {
  14335. QCPColorGradient result(*this);
  14336. result.clearColorStops();
  14337. for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
  14338. result.setColorStopAt(1.0-it.key(), it.value());
  14339. return result;
  14340. }
  14341. /*! \internal
  14342. Returns true if the color gradient uses transparency, i.e. if any of the configured color stops
  14343. has an alpha value below 255.
  14344. */
  14345. bool QCPColorGradient::stopsUseAlpha() const
  14346. {
  14347. for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
  14348. {
  14349. if (it.value().alpha() < 255)
  14350. return true;
  14351. }
  14352. return false;
  14353. }
  14354. /*! \internal
  14355. Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly
  14356. convert positions to colors. This is where the interpolation between color stops is calculated.
  14357. */
  14358. void QCPColorGradient::updateColorBuffer()
  14359. {
  14360. if (mColorBuffer.size() != mLevelCount)
  14361. mColorBuffer.resize(mLevelCount);
  14362. if (mColorStops.size() > 1)
  14363. {
  14364. double indexToPosFactor = 1.0/double(mLevelCount-1);
  14365. const bool useAlpha = stopsUseAlpha();
  14366. for (int i=0; i<mLevelCount; ++i)
  14367. {
  14368. double position = i*indexToPosFactor;
  14369. QMap<double, QColor>::const_iterator it = const_cast<const QMap<double, QColor>*>(&mColorStops)->lowerBound(position); // force using the const lowerBound method
  14370. if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop
  14371. {
  14372. if (useAlpha)
  14373. {
  14374. const QColor col = std::prev(it).value();
  14375. const double alphaPremultiplier = col.alpha()/255.0; // since we use QImage::Format_ARGB32_Premultiplied
  14376. mColorBuffer[i] = qRgba(int(col.red()*alphaPremultiplier),
  14377. int(col.green()*alphaPremultiplier),
  14378. int(col.blue()*alphaPremultiplier),
  14379. col.alpha());
  14380. } else
  14381. mColorBuffer[i] = std::prev(it).value().rgba();
  14382. } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop
  14383. {
  14384. if (useAlpha)
  14385. {
  14386. const QColor &col = it.value();
  14387. const double alphaPremultiplier = col.alpha()/255.0; // since we use QImage::Format_ARGB32_Premultiplied
  14388. mColorBuffer[i] = qRgba(int(col.red()*alphaPremultiplier),
  14389. int(col.green()*alphaPremultiplier),
  14390. int(col.blue()*alphaPremultiplier),
  14391. col.alpha());
  14392. } else
  14393. mColorBuffer[i] = it.value().rgba();
  14394. } else // position is in between stops (or on an intermediate stop), interpolate color
  14395. {
  14396. QMap<double, QColor>::const_iterator high = it;
  14397. QMap<double, QColor>::const_iterator low = std::prev(it);
  14398. double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1
  14399. switch (mColorInterpolation)
  14400. {
  14401. case ciRGB:
  14402. {
  14403. if (useAlpha)
  14404. {
  14405. const int alpha = int((1-t)*low.value().alpha() + t*high.value().alpha());
  14406. const double alphaPremultiplier = alpha/255.0; // since we use QImage::Format_ARGB32_Premultiplied
  14407. mColorBuffer[i] = qRgba(int( ((1-t)*low.value().red() + t*high.value().red())*alphaPremultiplier ),
  14408. int( ((1-t)*low.value().green() + t*high.value().green())*alphaPremultiplier ),
  14409. int( ((1-t)*low.value().blue() + t*high.value().blue())*alphaPremultiplier ),
  14410. alpha);
  14411. } else
  14412. {
  14413. mColorBuffer[i] = qRgb(int( ((1-t)*low.value().red() + t*high.value().red()) ),
  14414. int( ((1-t)*low.value().green() + t*high.value().green()) ),
  14415. int( ((1-t)*low.value().blue() + t*high.value().blue())) );
  14416. }
  14417. break;
  14418. }
  14419. case ciHSV:
  14420. {
  14421. QColor lowHsv = low.value().toHsv();
  14422. QColor highHsv = high.value().toHsv();
  14423. double hue = 0;
  14424. double hueDiff = highHsv.hueF()-lowHsv.hueF();
  14425. if (hueDiff > 0.5)
  14426. hue = lowHsv.hueF() - t*(1.0-hueDiff);
  14427. else if (hueDiff < -0.5)
  14428. hue = lowHsv.hueF() + t*(1.0+hueDiff);
  14429. else
  14430. hue = lowHsv.hueF() + t*hueDiff;
  14431. if (hue < 0) hue += 1.0;
  14432. else if (hue >= 1.0) hue -= 1.0;
  14433. if (useAlpha)
  14434. {
  14435. const QRgb rgb = QColor::fromHsvF(hue,
  14436. (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(),
  14437. (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
  14438. const double alpha = (1-t)*lowHsv.alphaF() + t*highHsv.alphaF();
  14439. mColorBuffer[i] = qRgba(int(qRed(rgb)*alpha), int(qGreen(rgb)*alpha), int(qBlue(rgb)*alpha), int(255*alpha));
  14440. }
  14441. else
  14442. {
  14443. mColorBuffer[i] = QColor::fromHsvF(hue,
  14444. (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(),
  14445. (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
  14446. }
  14447. break;
  14448. }
  14449. }
  14450. }
  14451. }
  14452. } else if (mColorStops.size() == 1)
  14453. {
  14454. const QRgb rgb = mColorStops.constBegin().value().rgb();
  14455. const double alpha = mColorStops.constBegin().value().alphaF();
  14456. mColorBuffer.fill(qRgba(int(qRed(rgb)*alpha), int(qGreen(rgb)*alpha), int(qBlue(rgb)*alpha), int(255*alpha)));
  14457. } else // mColorStops is empty, fill color buffer with black
  14458. {
  14459. mColorBuffer.fill(qRgb(0, 0, 0));
  14460. }
  14461. mColorBufferInvalidated = false;
  14462. }
  14463. /* end of 'src/colorgradient.cpp' */
  14464. /* including file 'src/selectiondecorator-bracket.cpp' */
  14465. /* modified 2022-11-06T12:45:56, size 12308 */
  14466. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14467. //////////////////// QCPSelectionDecoratorBracket
  14468. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14469. /*! \class QCPSelectionDecoratorBracket
  14470. \brief A selection decorator which draws brackets around each selected data segment
  14471. Additionally to the regular highlighting of selected segments via color, fill and scatter style,
  14472. this \ref QCPSelectionDecorator subclass draws markers at the begin and end of each selected data
  14473. segment of the plottable.
  14474. The shape of the markers can be controlled with \ref setBracketStyle, \ref setBracketWidth and
  14475. \ref setBracketHeight. The color/fill can be controlled with \ref setBracketPen and \ref
  14476. setBracketBrush.
  14477. To introduce custom bracket styles, it is only necessary to sublcass \ref
  14478. QCPSelectionDecoratorBracket and reimplement \ref drawBracket. The rest will be managed by the
  14479. base class.
  14480. */
  14481. /*!
  14482. Creates a new QCPSelectionDecoratorBracket instance with default values.
  14483. */
  14484. QCPSelectionDecoratorBracket::QCPSelectionDecoratorBracket() :
  14485. mBracketPen(QPen(Qt::black)),
  14486. mBracketBrush(Qt::NoBrush),
  14487. mBracketWidth(5),
  14488. mBracketHeight(50),
  14489. mBracketStyle(bsSquareBracket),
  14490. mTangentToData(false),
  14491. mTangentAverage(2)
  14492. {
  14493. }
  14494. QCPSelectionDecoratorBracket::~QCPSelectionDecoratorBracket()
  14495. {
  14496. }
  14497. /*!
  14498. Sets the pen that will be used to draw the brackets at the beginning and end of each selected
  14499. data segment.
  14500. */
  14501. void QCPSelectionDecoratorBracket::setBracketPen(const QPen &pen)
  14502. {
  14503. mBracketPen = pen;
  14504. }
  14505. /*!
  14506. Sets the brush that will be used to draw the brackets at the beginning and end of each selected
  14507. data segment.
  14508. */
  14509. void QCPSelectionDecoratorBracket::setBracketBrush(const QBrush &brush)
  14510. {
  14511. mBracketBrush = brush;
  14512. }
  14513. /*!
  14514. Sets the width of the drawn bracket. The width dimension is always parallel to the key axis of
  14515. the data, or the tangent direction of the current data slope, if \ref setTangentToData is
  14516. enabled.
  14517. */
  14518. void QCPSelectionDecoratorBracket::setBracketWidth(int width)
  14519. {
  14520. mBracketWidth = width;
  14521. }
  14522. /*!
  14523. Sets the height of the drawn bracket. The height dimension is always perpendicular to the key axis
  14524. of the data, or the tangent direction of the current data slope, if \ref setTangentToData is
  14525. enabled.
  14526. */
  14527. void QCPSelectionDecoratorBracket::setBracketHeight(int height)
  14528. {
  14529. mBracketHeight = height;
  14530. }
  14531. /*!
  14532. Sets the shape that the bracket/marker will have.
  14533. \see setBracketWidth, setBracketHeight
  14534. */
  14535. void QCPSelectionDecoratorBracket::setBracketStyle(QCPSelectionDecoratorBracket::BracketStyle style)
  14536. {
  14537. mBracketStyle = style;
  14538. }
  14539. /*!
  14540. Sets whether the brackets will be rotated such that they align with the slope of the data at the
  14541. position that they appear in.
  14542. For noisy data, it might be more visually appealing to average the slope over multiple data
  14543. points. This can be configured via \ref setTangentAverage.
  14544. */
  14545. void QCPSelectionDecoratorBracket::setTangentToData(bool enabled)
  14546. {
  14547. mTangentToData = enabled;
  14548. }
  14549. /*!
  14550. Controls over how many data points the slope shall be averaged, when brackets shall be aligned
  14551. with the data (if \ref setTangentToData is true).
  14552. From the position of the bracket, \a pointCount points towards the selected data range will be
  14553. taken into account. The smallest value of \a pointCount is 1, which is effectively equivalent to
  14554. disabling \ref setTangentToData.
  14555. */
  14556. void QCPSelectionDecoratorBracket::setTangentAverage(int pointCount)
  14557. {
  14558. mTangentAverage = pointCount;
  14559. if (mTangentAverage < 1)
  14560. mTangentAverage = 1;
  14561. }
  14562. /*!
  14563. Draws the bracket shape with \a painter. The parameter \a direction is either -1 or 1 and
  14564. indicates whether the bracket shall point to the left or the right (i.e. is a closing or opening
  14565. bracket, respectively).
  14566. The passed \a painter already contains all transformations that are necessary to position and
  14567. rotate the bracket appropriately. Painting operations can be performed as if drawing upright
  14568. brackets on flat data with horizontal key axis, with (0, 0) being the center of the bracket.
  14569. If you wish to sublcass \ref QCPSelectionDecoratorBracket in order to provide custom bracket
  14570. shapes (see \ref QCPSelectionDecoratorBracket::bsUserStyle), this is the method you should
  14571. reimplement.
  14572. */
  14573. void QCPSelectionDecoratorBracket::drawBracket(QCPPainter *painter, int direction) const
  14574. {
  14575. switch (mBracketStyle)
  14576. {
  14577. case bsSquareBracket:
  14578. {
  14579. painter->drawLine(QLineF(mBracketWidth*direction, -mBracketHeight*0.5, 0, -mBracketHeight*0.5));
  14580. painter->drawLine(QLineF(mBracketWidth*direction, mBracketHeight*0.5, 0, mBracketHeight*0.5));
  14581. painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5));
  14582. break;
  14583. }
  14584. case bsHalfEllipse:
  14585. {
  14586. painter->drawArc(QRectF(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight), -90*16, -180*16*direction);
  14587. break;
  14588. }
  14589. case bsEllipse:
  14590. {
  14591. painter->drawEllipse(QRectF(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight));
  14592. break;
  14593. }
  14594. case bsPlus:
  14595. {
  14596. painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5));
  14597. painter->drawLine(QLineF(-mBracketWidth*0.5, 0, mBracketWidth*0.5, 0));
  14598. break;
  14599. }
  14600. default:
  14601. {
  14602. qDebug() << Q_FUNC_INFO << "unknown/custom bracket style can't be handeld by default implementation:" << static_cast<int>(mBracketStyle);
  14603. break;
  14604. }
  14605. }
  14606. }
  14607. /*!
  14608. Draws the bracket decoration on the data points at the begin and end of each selected data
  14609. segment given in \a seletion.
  14610. It uses the method \ref drawBracket to actually draw the shapes.
  14611. \seebaseclassmethod
  14612. */
  14613. void QCPSelectionDecoratorBracket::drawDecoration(QCPPainter *painter, QCPDataSelection selection)
  14614. {
  14615. if (!mPlottable || selection.isEmpty()) return;
  14616. if (QCPPlottableInterface1D *interface1d = mPlottable->interface1D())
  14617. {
  14618. foreach (const QCPDataRange &dataRange, selection.dataRanges())
  14619. {
  14620. // determine position and (if tangent mode is enabled) angle of brackets:
  14621. int openBracketDir = (mPlottable->keyAxis() && !mPlottable->keyAxis()->rangeReversed()) ? 1 : -1;
  14622. int closeBracketDir = -openBracketDir;
  14623. QPointF openBracketPos = getPixelCoordinates(interface1d, dataRange.begin());
  14624. QPointF closeBracketPos = getPixelCoordinates(interface1d, dataRange.end()-1);
  14625. double openBracketAngle = 0;
  14626. double closeBracketAngle = 0;
  14627. if (mTangentToData)
  14628. {
  14629. openBracketAngle = getTangentAngle(interface1d, dataRange.begin(), openBracketDir);
  14630. closeBracketAngle = getTangentAngle(interface1d, dataRange.end()-1, closeBracketDir);
  14631. }
  14632. // draw opening bracket:
  14633. QTransform oldTransform = painter->transform();
  14634. painter->setPen(mBracketPen);
  14635. painter->setBrush(mBracketBrush);
  14636. painter->translate(openBracketPos);
  14637. painter->rotate(openBracketAngle/M_PI*180.0);
  14638. drawBracket(painter, openBracketDir);
  14639. painter->setTransform(oldTransform);
  14640. // draw closing bracket:
  14641. painter->setPen(mBracketPen);
  14642. painter->setBrush(mBracketBrush);
  14643. painter->translate(closeBracketPos);
  14644. painter->rotate(closeBracketAngle/M_PI*180.0);
  14645. drawBracket(painter, closeBracketDir);
  14646. painter->setTransform(oldTransform);
  14647. }
  14648. }
  14649. }
  14650. /*! \internal
  14651. If \ref setTangentToData is enabled, brackets need to be rotated according to the data slope.
  14652. This method returns the angle in radians by which a bracket at the given \a dataIndex must be
  14653. rotated.
  14654. The parameter \a direction must be set to either -1 or 1, representing whether it is an opening
  14655. or closing bracket. Since for slope calculation multiple data points are required, this defines
  14656. the direction in which the algorithm walks, starting at \a dataIndex, to average those data
  14657. points. (see \ref setTangentToData and \ref setTangentAverage)
  14658. \a interface1d is the interface to the plottable's data which is used to query data coordinates.
  14659. */
  14660. double QCPSelectionDecoratorBracket::getTangentAngle(const QCPPlottableInterface1D *interface1d, int dataIndex, int direction) const
  14661. {
  14662. if (!interface1d || dataIndex < 0 || dataIndex >= interface1d->dataCount())
  14663. return 0;
  14664. direction = direction < 0 ? -1 : 1; // enforce direction is either -1 or 1
  14665. // how many steps we can actually go from index in the given direction without exceeding data bounds:
  14666. int averageCount;
  14667. if (direction < 0)
  14668. averageCount = qMin(mTangentAverage, dataIndex);
  14669. else
  14670. averageCount = qMin(mTangentAverage, interface1d->dataCount()-1-dataIndex);
  14671. qDebug() << averageCount;
  14672. // calculate point average of averageCount points:
  14673. QVector<QPointF> points(averageCount);
  14674. QPointF pointsAverage;
  14675. int currentIndex = dataIndex;
  14676. for (int i=0; i<averageCount; ++i)
  14677. {
  14678. points[i] = getPixelCoordinates(interface1d, currentIndex);
  14679. pointsAverage += points[i];
  14680. currentIndex += direction;
  14681. }
  14682. pointsAverage /= double(averageCount);
  14683. // calculate slope of linear regression through points:
  14684. double numSum = 0;
  14685. double denomSum = 0;
  14686. for (int i=0; i<averageCount; ++i)
  14687. {
  14688. const double dx = points.at(i).x()-pointsAverage.x();
  14689. const double dy = points.at(i).y()-pointsAverage.y();
  14690. numSum += dx*dy;
  14691. denomSum += dx*dx;
  14692. }
  14693. if (!qFuzzyIsNull(denomSum) && !qFuzzyIsNull(numSum))
  14694. {
  14695. return qAtan2(numSum, denomSum);
  14696. } else // undetermined angle, probably mTangentAverage == 1, so using only one data point
  14697. return 0;
  14698. }
  14699. /*! \internal
  14700. Returns the pixel coordinates of the data point at \a dataIndex, using \a interface1d to access
  14701. the data points.
  14702. */
  14703. QPointF QCPSelectionDecoratorBracket::getPixelCoordinates(const QCPPlottableInterface1D *interface1d, int dataIndex) const
  14704. {
  14705. QCPAxis *keyAxis = mPlottable->keyAxis();
  14706. QCPAxis *valueAxis = mPlottable->valueAxis();
  14707. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {0, 0}; }
  14708. if (keyAxis->orientation() == Qt::Horizontal)
  14709. return {keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex)), valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex))};
  14710. else
  14711. return {valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex)), keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex))};
  14712. }
  14713. /* end of 'src/selectiondecorator-bracket.cpp' */
  14714. /* including file 'src/layoutelements/layoutelement-axisrect.cpp' */
  14715. /* modified 2022-11-06T12:45:56, size 47193 */
  14716. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14717. //////////////////// QCPAxisRect
  14718. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14719. /*! \class QCPAxisRect
  14720. \brief Holds multiple axes and arranges them in a rectangular shape.
  14721. This class represents an axis rect, a rectangular area that is bounded on all sides with an
  14722. arbitrary number of axes.
  14723. Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the
  14724. layout system allows to have multiple axis rects, e.g. arranged in a grid layout
  14725. (QCustomPlot::plotLayout).
  14726. By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be
  14727. accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index.
  14728. If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be
  14729. invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref
  14730. addAxes. To remove an axis, use \ref removeAxis.
  14731. The axis rect layerable itself only draws a background pixmap or color, if specified (\ref
  14732. setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an
  14733. explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be
  14734. placed on other layers, independently of the axis rect.
  14735. Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref
  14736. insetLayout and can be used to have other layout elements (or even other layouts with multiple
  14737. elements) hovering inside the axis rect.
  14738. If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The
  14739. behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel
  14740. is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable
  14741. via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are
  14742. only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref
  14743. QCP::iRangeZoom.
  14744. \image html AxisRectSpacingOverview.png
  14745. <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed
  14746. line on the far left indicates the viewport/widget border.</center>
  14747. */
  14748. /* start documentation of inline functions */
  14749. /*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const
  14750. Returns the inset layout of this axis rect. It can be used to place other layout elements (or
  14751. even layouts with multiple other elements) inside/on top of an axis rect.
  14752. \see QCPLayoutInset
  14753. */
  14754. /*! \fn int QCPAxisRect::left() const
  14755. Returns the pixel position of the left border of this axis rect. Margins are not taken into
  14756. account here, so the returned value is with respect to the inner \ref rect.
  14757. */
  14758. /*! \fn int QCPAxisRect::right() const
  14759. Returns the pixel position of the right border of this axis rect. Margins are not taken into
  14760. account here, so the returned value is with respect to the inner \ref rect.
  14761. */
  14762. /*! \fn int QCPAxisRect::top() const
  14763. Returns the pixel position of the top border of this axis rect. Margins are not taken into
  14764. account here, so the returned value is with respect to the inner \ref rect.
  14765. */
  14766. /*! \fn int QCPAxisRect::bottom() const
  14767. Returns the pixel position of the bottom border of this axis rect. Margins are not taken into
  14768. account here, so the returned value is with respect to the inner \ref rect.
  14769. */
  14770. /*! \fn int QCPAxisRect::width() const
  14771. Returns the pixel width of this axis rect. Margins are not taken into account here, so the
  14772. returned value is with respect to the inner \ref rect.
  14773. */
  14774. /*! \fn int QCPAxisRect::height() const
  14775. Returns the pixel height of this axis rect. Margins are not taken into account here, so the
  14776. returned value is with respect to the inner \ref rect.
  14777. */
  14778. /*! \fn QSize QCPAxisRect::size() const
  14779. Returns the pixel size of this axis rect. Margins are not taken into account here, so the
  14780. returned value is with respect to the inner \ref rect.
  14781. */
  14782. /*! \fn QPoint QCPAxisRect::topLeft() const
  14783. Returns the top left corner of this axis rect in pixels. Margins are not taken into account here,
  14784. so the returned value is with respect to the inner \ref rect.
  14785. */
  14786. /*! \fn QPoint QCPAxisRect::topRight() const
  14787. Returns the top right corner of this axis rect in pixels. Margins are not taken into account
  14788. here, so the returned value is with respect to the inner \ref rect.
  14789. */
  14790. /*! \fn QPoint QCPAxisRect::bottomLeft() const
  14791. Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account
  14792. here, so the returned value is with respect to the inner \ref rect.
  14793. */
  14794. /*! \fn QPoint QCPAxisRect::bottomRight() const
  14795. Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account
  14796. here, so the returned value is with respect to the inner \ref rect.
  14797. */
  14798. /*! \fn QPoint QCPAxisRect::center() const
  14799. Returns the center of this axis rect in pixels. Margins are not taken into account here, so the
  14800. returned value is with respect to the inner \ref rect.
  14801. */
  14802. /* end documentation of inline functions */
  14803. /*!
  14804. Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four
  14805. sides, the top and right axes are set invisible initially.
  14806. */
  14807. QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) :
  14808. QCPLayoutElement(parentPlot),
  14809. mBackgroundBrush(Qt::NoBrush),
  14810. mBackgroundScaled(true),
  14811. mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
  14812. mInsetLayout(new QCPLayoutInset),
  14813. mRangeDrag(Qt::Horizontal|Qt::Vertical),
  14814. mRangeZoom(Qt::Horizontal|Qt::Vertical),
  14815. mRangeZoomFactorHorz(0.85),
  14816. mRangeZoomFactorVert(0.85),
  14817. mDragging(false)
  14818. {
  14819. mInsetLayout->initializeParentPlot(mParentPlot);
  14820. mInsetLayout->setParentLayerable(this);
  14821. mInsetLayout->setParent(this);
  14822. setMinimumSize(50, 50);
  14823. setMinimumMargins(QMargins(15, 15, 15, 15));
  14824. mAxes.insert(QCPAxis::atLeft, QList<QCPAxis*>());
  14825. mAxes.insert(QCPAxis::atRight, QList<QCPAxis*>());
  14826. mAxes.insert(QCPAxis::atTop, QList<QCPAxis*>());
  14827. mAxes.insert(QCPAxis::atBottom, QList<QCPAxis*>());
  14828. if (setupDefaultAxes)
  14829. {
  14830. QCPAxis *xAxis = addAxis(QCPAxis::atBottom);
  14831. QCPAxis *yAxis = addAxis(QCPAxis::atLeft);
  14832. QCPAxis *xAxis2 = addAxis(QCPAxis::atTop);
  14833. QCPAxis *yAxis2 = addAxis(QCPAxis::atRight);
  14834. setRangeDragAxes(xAxis, yAxis);
  14835. setRangeZoomAxes(xAxis, yAxis);
  14836. xAxis2->setVisible(false);
  14837. yAxis2->setVisible(false);
  14838. xAxis->grid()->setVisible(true);
  14839. yAxis->grid()->setVisible(true);
  14840. xAxis2->grid()->setVisible(false);
  14841. yAxis2->grid()->setVisible(false);
  14842. xAxis2->grid()->setZeroLinePen(Qt::NoPen);
  14843. yAxis2->grid()->setZeroLinePen(Qt::NoPen);
  14844. xAxis2->grid()->setVisible(false);
  14845. yAxis2->grid()->setVisible(false);
  14846. }
  14847. }
  14848. QCPAxisRect::~QCPAxisRect()
  14849. {
  14850. delete mInsetLayout;
  14851. mInsetLayout = nullptr;
  14852. foreach (QCPAxis *axis, axes())
  14853. removeAxis(axis);
  14854. }
  14855. /*!
  14856. Returns the number of axes on the axis rect side specified with \a type.
  14857. \see axis
  14858. */
  14859. int QCPAxisRect::axisCount(QCPAxis::AxisType type) const
  14860. {
  14861. return mAxes.value(type).size();
  14862. }
  14863. /*!
  14864. Returns the axis with the given \a index on the axis rect side specified with \a type.
  14865. \see axisCount, axes
  14866. */
  14867. QCPAxis *QCPAxisRect::axis(QCPAxis::AxisType type, int index) const
  14868. {
  14869. QList<QCPAxis*> ax(mAxes.value(type));
  14870. if (index >= 0 && index < ax.size())
  14871. {
  14872. return ax.at(index);
  14873. } else
  14874. {
  14875. qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index;
  14876. return nullptr;
  14877. }
  14878. }
  14879. /*!
  14880. Returns all axes on the axis rect sides specified with \a types.
  14881. \a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of
  14882. multiple sides.
  14883. \see axis
  14884. */
  14885. QList<QCPAxis*> QCPAxisRect::axes(QCPAxis::AxisTypes types) const
  14886. {
  14887. QList<QCPAxis*> result;
  14888. if (types.testFlag(QCPAxis::atLeft))
  14889. result << mAxes.value(QCPAxis::atLeft);
  14890. if (types.testFlag(QCPAxis::atRight))
  14891. result << mAxes.value(QCPAxis::atRight);
  14892. if (types.testFlag(QCPAxis::atTop))
  14893. result << mAxes.value(QCPAxis::atTop);
  14894. if (types.testFlag(QCPAxis::atBottom))
  14895. result << mAxes.value(QCPAxis::atBottom);
  14896. return result;
  14897. }
  14898. /*! \overload
  14899. Returns all axes of this axis rect.
  14900. */
  14901. QList<QCPAxis*> QCPAxisRect::axes() const
  14902. {
  14903. QList<QCPAxis*> result;
  14904. QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
  14905. while (it.hasNext())
  14906. {
  14907. it.next();
  14908. result << it.value();
  14909. }
  14910. return result;
  14911. }
  14912. /*!
  14913. Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a
  14914. new QCPAxis instance is created internally. QCustomPlot owns the returned axis, so if you want to
  14915. remove an axis, use \ref removeAxis instead of deleting it manually.
  14916. You may inject QCPAxis instances (or subclasses of QCPAxis) by setting \a axis to an axis that was
  14917. previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership
  14918. of the axis, so you may not delete it afterwards. Further, the \a axis must have been created
  14919. with this axis rect as parent and with the same axis type as specified in \a type. If this is not
  14920. the case, a debug output is generated, the axis is not added, and the method returns \c nullptr.
  14921. This method can not be used to move \a axis between axis rects. The same \a axis instance must
  14922. not be added multiple times to the same or different axis rects.
  14923. If an axis rect side already contains one or more axes, the lower and upper endings of the new
  14924. axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref
  14925. QCPLineEnding::esHalfBar.
  14926. \see addAxes, setupFullAxesBox
  14927. */
  14928. QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type, QCPAxis *axis)
  14929. {
  14930. QCPAxis *newAxis = axis;
  14931. if (!newAxis)
  14932. {
  14933. newAxis = new QCPAxis(this, type);
  14934. } else // user provided existing axis instance, do some sanity checks
  14935. {
  14936. if (newAxis->axisType() != type)
  14937. {
  14938. qDebug() << Q_FUNC_INFO << "passed axis has different axis type than specified in type parameter";
  14939. return nullptr;
  14940. }
  14941. if (newAxis->axisRect() != this)
  14942. {
  14943. qDebug() << Q_FUNC_INFO << "passed axis doesn't have this axis rect as parent axis rect";
  14944. return nullptr;
  14945. }
  14946. if (axes().contains(newAxis))
  14947. {
  14948. qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect";
  14949. return nullptr;
  14950. }
  14951. }
  14952. if (!mAxes[type].isEmpty()) // multiple axes on one side, add half-bar axis ending to additional axes with offset
  14953. {
  14954. bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom);
  14955. newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert));
  14956. newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert));
  14957. }
  14958. mAxes[type].append(newAxis);
  14959. // reset convenience axis pointers on parent QCustomPlot if they are unset:
  14960. if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this)
  14961. {
  14962. switch (type)
  14963. {
  14964. case QCPAxis::atBottom: { if (!mParentPlot->xAxis) mParentPlot->xAxis = newAxis; break; }
  14965. case QCPAxis::atLeft: { if (!mParentPlot->yAxis) mParentPlot->yAxis = newAxis; break; }
  14966. case QCPAxis::atTop: { if (!mParentPlot->xAxis2) mParentPlot->xAxis2 = newAxis; break; }
  14967. case QCPAxis::atRight: { if (!mParentPlot->yAxis2) mParentPlot->yAxis2 = newAxis; break; }
  14968. }
  14969. }
  14970. return newAxis;
  14971. }
  14972. /*!
  14973. Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an
  14974. <tt>or</tt>-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once.
  14975. Returns a list of the added axes.
  14976. \see addAxis, setupFullAxesBox
  14977. */
  14978. QList<QCPAxis*> QCPAxisRect::addAxes(QCPAxis::AxisTypes types)
  14979. {
  14980. QList<QCPAxis*> result;
  14981. if (types.testFlag(QCPAxis::atLeft))
  14982. result << addAxis(QCPAxis::atLeft);
  14983. if (types.testFlag(QCPAxis::atRight))
  14984. result << addAxis(QCPAxis::atRight);
  14985. if (types.testFlag(QCPAxis::atTop))
  14986. result << addAxis(QCPAxis::atTop);
  14987. if (types.testFlag(QCPAxis::atBottom))
  14988. result << addAxis(QCPAxis::atBottom);
  14989. return result;
  14990. }
  14991. /*!
  14992. Removes the specified \a axis from the axis rect and deletes it.
  14993. Returns true on success, i.e. if \a axis was a valid axis in this axis rect.
  14994. \see addAxis
  14995. */
  14996. bool QCPAxisRect::removeAxis(QCPAxis *axis)
  14997. {
  14998. // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers:
  14999. QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
  15000. while (it.hasNext())
  15001. {
  15002. it.next();
  15003. if (it.value().contains(axis))
  15004. {
  15005. 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)
  15006. it.value()[1]->setOffset(axis->offset());
  15007. mAxes[it.key()].removeOne(axis);
  15008. 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)
  15009. parentPlot()->axisRemoved(axis);
  15010. delete axis;
  15011. return true;
  15012. }
  15013. }
  15014. qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast<quintptr>(axis);
  15015. return false;
  15016. }
  15017. /*!
  15018. Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates.
  15019. All axes of this axis rect will have their range zoomed accordingly. If you only wish to zoom
  15020. specific axes, use the overloaded version of this method.
  15021. \see QCustomPlot::setSelectionRectMode
  15022. */
  15023. void QCPAxisRect::zoom(const QRectF &pixelRect)
  15024. {
  15025. zoom(pixelRect, axes());
  15026. }
  15027. /*! \overload
  15028. Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates.
  15029. Only the axes passed in \a affectedAxes will have their ranges zoomed accordingly.
  15030. \see QCustomPlot::setSelectionRectMode
  15031. */
  15032. void QCPAxisRect::zoom(const QRectF &pixelRect, const QList<QCPAxis*> &affectedAxes)
  15033. {
  15034. foreach (QCPAxis *axis, affectedAxes)
  15035. {
  15036. if (!axis)
  15037. {
  15038. qDebug() << Q_FUNC_INFO << "a passed axis was zero";
  15039. continue;
  15040. }
  15041. QCPRange pixelRange;
  15042. if (axis->orientation() == Qt::Horizontal)
  15043. pixelRange = QCPRange(pixelRect.left(), pixelRect.right());
  15044. else
  15045. pixelRange = QCPRange(pixelRect.top(), pixelRect.bottom());
  15046. axis->setRange(axis->pixelToCoord(pixelRange.lower), axis->pixelToCoord(pixelRange.upper));
  15047. }
  15048. }
  15049. /*!
  15050. Convenience function to create an axis on each side that doesn't have any axes yet and set their
  15051. visibility to true. Further, the top/right axes are assigned the following properties of the
  15052. bottom/left axes:
  15053. \li range (\ref QCPAxis::setRange)
  15054. \li range reversed (\ref QCPAxis::setRangeReversed)
  15055. \li scale type (\ref QCPAxis::setScaleType)
  15056. \li tick visibility (\ref QCPAxis::setTicks)
  15057. \li number format (\ref QCPAxis::setNumberFormat)
  15058. \li number precision (\ref QCPAxis::setNumberPrecision)
  15059. \li tick count of ticker (\ref QCPAxisTicker::setTickCount)
  15060. \li tick origin of ticker (\ref QCPAxisTicker::setTickOrigin)
  15061. Tick label visibility (\ref QCPAxis::setTickLabels) of the right and top axes are set to false.
  15062. If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom
  15063. and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes.
  15064. */
  15065. void QCPAxisRect::setupFullAxesBox(bool connectRanges)
  15066. {
  15067. QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2;
  15068. if (axisCount(QCPAxis::atBottom) == 0)
  15069. xAxis = addAxis(QCPAxis::atBottom);
  15070. else
  15071. xAxis = axis(QCPAxis::atBottom);
  15072. if (axisCount(QCPAxis::atLeft) == 0)
  15073. yAxis = addAxis(QCPAxis::atLeft);
  15074. else
  15075. yAxis = axis(QCPAxis::atLeft);
  15076. if (axisCount(QCPAxis::atTop) == 0)
  15077. xAxis2 = addAxis(QCPAxis::atTop);
  15078. else
  15079. xAxis2 = axis(QCPAxis::atTop);
  15080. if (axisCount(QCPAxis::atRight) == 0)
  15081. yAxis2 = addAxis(QCPAxis::atRight);
  15082. else
  15083. yAxis2 = axis(QCPAxis::atRight);
  15084. xAxis->setVisible(true);
  15085. yAxis->setVisible(true);
  15086. xAxis2->setVisible(true);
  15087. yAxis2->setVisible(true);
  15088. xAxis2->setTickLabels(false);
  15089. yAxis2->setTickLabels(false);
  15090. xAxis2->setRange(xAxis->range());
  15091. xAxis2->setRangeReversed(xAxis->rangeReversed());
  15092. xAxis2->setScaleType(xAxis->scaleType());
  15093. xAxis2->setTicks(xAxis->ticks());
  15094. xAxis2->setNumberFormat(xAxis->numberFormat());
  15095. xAxis2->setNumberPrecision(xAxis->numberPrecision());
  15096. xAxis2->ticker()->setTickCount(xAxis->ticker()->tickCount());
  15097. xAxis2->ticker()->setTickOrigin(xAxis->ticker()->tickOrigin());
  15098. yAxis2->setRange(yAxis->range());
  15099. yAxis2->setRangeReversed(yAxis->rangeReversed());
  15100. yAxis2->setScaleType(yAxis->scaleType());
  15101. yAxis2->setTicks(yAxis->ticks());
  15102. yAxis2->setNumberFormat(yAxis->numberFormat());
  15103. yAxis2->setNumberPrecision(yAxis->numberPrecision());
  15104. yAxis2->ticker()->setTickCount(yAxis->ticker()->tickCount());
  15105. yAxis2->ticker()->setTickOrigin(yAxis->ticker()->tickOrigin());
  15106. if (connectRanges)
  15107. {
  15108. connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange)));
  15109. connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange)));
  15110. }
  15111. }
  15112. /*!
  15113. Returns a list of all the plottables that are associated with this axis rect.
  15114. A plottable is considered associated with an axis rect if its key or value axis (or both) is in
  15115. this axis rect.
  15116. \see graphs, items
  15117. */
  15118. QList<QCPAbstractPlottable*> QCPAxisRect::plottables() const
  15119. {
  15120. // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries
  15121. QList<QCPAbstractPlottable*> result;
  15122. foreach (QCPAbstractPlottable *plottable, mParentPlot->mPlottables)
  15123. {
  15124. if (plottable->keyAxis()->axisRect() == this || plottable->valueAxis()->axisRect() == this)
  15125. result.append(plottable);
  15126. }
  15127. return result;
  15128. }
  15129. /*!
  15130. Returns a list of all the graphs that are associated with this axis rect.
  15131. A graph is considered associated with an axis rect if its key or value axis (or both) is in
  15132. this axis rect.
  15133. \see plottables, items
  15134. */
  15135. QList<QCPGraph*> QCPAxisRect::graphs() const
  15136. {
  15137. // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries
  15138. QList<QCPGraph*> result;
  15139. foreach (QCPGraph *graph, mParentPlot->mGraphs)
  15140. {
  15141. if (graph->keyAxis()->axisRect() == this || graph->valueAxis()->axisRect() == this)
  15142. result.append(graph);
  15143. }
  15144. return result;
  15145. }
  15146. /*!
  15147. Returns a list of all the items that are associated with this axis rect.
  15148. An item is considered associated with an axis rect if any of its positions has key or value axis
  15149. set to an axis that is in this axis rect, or if any of its positions has \ref
  15150. QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref
  15151. QCPAbstractItem::setClipAxisRect) is set to this axis rect.
  15152. \see plottables, graphs
  15153. */
  15154. QList<QCPAbstractItem *> QCPAxisRect::items() const
  15155. {
  15156. // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries
  15157. // and miss those items that have this axis rect as clipAxisRect.
  15158. QList<QCPAbstractItem*> result;
  15159. foreach (QCPAbstractItem *item, mParentPlot->mItems)
  15160. {
  15161. if (item->clipAxisRect() == this)
  15162. {
  15163. result.append(item);
  15164. continue;
  15165. }
  15166. foreach (QCPItemPosition *position, item->positions())
  15167. {
  15168. if (position->axisRect() == this ||
  15169. position->keyAxis()->axisRect() == this ||
  15170. position->valueAxis()->axisRect() == this)
  15171. {
  15172. result.append(item);
  15173. break;
  15174. }
  15175. }
  15176. }
  15177. return result;
  15178. }
  15179. /*!
  15180. This method is called automatically upon replot and doesn't need to be called by users of
  15181. QCPAxisRect.
  15182. Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
  15183. and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
  15184. QCPInsetLayout::update function.
  15185. \seebaseclassmethod
  15186. */
  15187. void QCPAxisRect::update(UpdatePhase phase)
  15188. {
  15189. QCPLayoutElement::update(phase);
  15190. switch (phase)
  15191. {
  15192. case upPreparation:
  15193. {
  15194. foreach (QCPAxis *axis, axes())
  15195. axis->setupTickVectors();
  15196. break;
  15197. }
  15198. case upLayout:
  15199. {
  15200. mInsetLayout->setOuterRect(rect());
  15201. break;
  15202. }
  15203. default: break;
  15204. }
  15205. // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout):
  15206. mInsetLayout->update(phase);
  15207. }
  15208. /* inherits documentation from base class */
  15209. QList<QCPLayoutElement*> QCPAxisRect::elements(bool recursive) const
  15210. {
  15211. QList<QCPLayoutElement*> result;
  15212. if (mInsetLayout)
  15213. {
  15214. result << mInsetLayout;
  15215. if (recursive)
  15216. result << mInsetLayout->elements(recursive);
  15217. }
  15218. return result;
  15219. }
  15220. /* inherits documentation from base class */
  15221. void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const
  15222. {
  15223. painter->setAntialiasing(false);
  15224. }
  15225. /* inherits documentation from base class */
  15226. void QCPAxisRect::draw(QCPPainter *painter)
  15227. {
  15228. drawBackground(painter);
  15229. }
  15230. /*!
  15231. Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the
  15232. axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect
  15233. backgrounds are usually drawn below everything else.
  15234. For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be
  15235. enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio
  15236. is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  15237. consider using the overloaded version of this function.
  15238. Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref
  15239. setBackground(const QBrush &brush).
  15240. \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush)
  15241. */
  15242. void QCPAxisRect::setBackground(const QPixmap &pm)
  15243. {
  15244. mBackgroundPixmap = pm;
  15245. mScaledBackgroundPixmap = QPixmap();
  15246. }
  15247. /*! \overload
  15248. Sets \a brush as the background brush. The axis rect background will be filled with this brush.
  15249. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds
  15250. are usually drawn below everything else.
  15251. The brush will be drawn before (under) any background pixmap, which may be specified with \ref
  15252. setBackground(const QPixmap &pm).
  15253. To disable drawing of a background brush, set \a brush to Qt::NoBrush.
  15254. \see setBackground(const QPixmap &pm)
  15255. */
  15256. void QCPAxisRect::setBackground(const QBrush &brush)
  15257. {
  15258. mBackgroundBrush = brush;
  15259. }
  15260. /*! \overload
  15261. Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it
  15262. shall be scaled in one call.
  15263. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  15264. */
  15265. void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
  15266. {
  15267. mBackgroundPixmap = pm;
  15268. mScaledBackgroundPixmap = QPixmap();
  15269. mBackgroundScaled = scaled;
  15270. mBackgroundScaledMode = mode;
  15271. }
  15272. /*!
  15273. Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled
  15274. is set to true, you may control whether and how the aspect ratio of the original pixmap is
  15275. preserved with \ref setBackgroundScaledMode.
  15276. Note that the scaled version of the original pixmap is buffered, so there is no performance
  15277. penalty on replots. (Except when the axis rect dimensions are changed continuously.)
  15278. \see setBackground, setBackgroundScaledMode
  15279. */
  15280. void QCPAxisRect::setBackgroundScaled(bool scaled)
  15281. {
  15282. mBackgroundScaled = scaled;
  15283. }
  15284. /*!
  15285. If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to
  15286. define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved.
  15287. \see setBackground, setBackgroundScaled
  15288. */
  15289. void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  15290. {
  15291. mBackgroundScaledMode = mode;
  15292. }
  15293. /*!
  15294. Returns the range drag axis of the \a orientation provided. If multiple axes were set, returns
  15295. the first one (use \ref rangeDragAxes to retrieve a list with all set axes).
  15296. \see setRangeDragAxes
  15297. */
  15298. QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation)
  15299. {
  15300. if (orientation == Qt::Horizontal)
  15301. return mRangeDragHorzAxis.isEmpty() ? nullptr : mRangeDragHorzAxis.first().data();
  15302. else
  15303. return mRangeDragVertAxis.isEmpty() ? nullptr : mRangeDragVertAxis.first().data();
  15304. }
  15305. /*!
  15306. Returns the range zoom axis of the \a orientation provided. If multiple axes were set, returns
  15307. the first one (use \ref rangeZoomAxes to retrieve a list with all set axes).
  15308. \see setRangeZoomAxes
  15309. */
  15310. QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation)
  15311. {
  15312. if (orientation == Qt::Horizontal)
  15313. return mRangeZoomHorzAxis.isEmpty() ? nullptr : mRangeZoomHorzAxis.first().data();
  15314. else
  15315. return mRangeZoomVertAxis.isEmpty() ? nullptr : mRangeZoomVertAxis.first().data();
  15316. }
  15317. /*!
  15318. Returns all range drag axes of the \a orientation provided.
  15319. \see rangeZoomAxis, setRangeZoomAxes
  15320. */
  15321. QList<QCPAxis*> QCPAxisRect::rangeDragAxes(Qt::Orientation orientation)
  15322. {
  15323. QList<QCPAxis*> result;
  15324. if (orientation == Qt::Horizontal)
  15325. {
  15326. foreach (QPointer<QCPAxis> axis, mRangeDragHorzAxis)
  15327. {
  15328. if (!axis.isNull())
  15329. result.append(axis.data());
  15330. }
  15331. } else
  15332. {
  15333. foreach (QPointer<QCPAxis> axis, mRangeDragVertAxis)
  15334. {
  15335. if (!axis.isNull())
  15336. result.append(axis.data());
  15337. }
  15338. }
  15339. return result;
  15340. }
  15341. /*!
  15342. Returns all range zoom axes of the \a orientation provided.
  15343. \see rangeDragAxis, setRangeDragAxes
  15344. */
  15345. QList<QCPAxis*> QCPAxisRect::rangeZoomAxes(Qt::Orientation orientation)
  15346. {
  15347. QList<QCPAxis*> result;
  15348. if (orientation == Qt::Horizontal)
  15349. {
  15350. foreach (QPointer<QCPAxis> axis, mRangeZoomHorzAxis)
  15351. {
  15352. if (!axis.isNull())
  15353. result.append(axis.data());
  15354. }
  15355. } else
  15356. {
  15357. foreach (QPointer<QCPAxis> axis, mRangeZoomVertAxis)
  15358. {
  15359. if (!axis.isNull())
  15360. result.append(axis.data());
  15361. }
  15362. }
  15363. return result;
  15364. }
  15365. /*!
  15366. Returns the range zoom factor of the \a orientation provided.
  15367. \see setRangeZoomFactor
  15368. */
  15369. double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation)
  15370. {
  15371. return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert);
  15372. }
  15373. /*!
  15374. Sets which axis orientation may be range dragged by the user with mouse interaction.
  15375. What orientation corresponds to which specific axis can be set with
  15376. \ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By
  15377. default, the horizontal axis is the bottom axis (xAxis) and the vertical axis
  15378. is the left axis (yAxis).
  15379. To disable range dragging entirely, pass \c nullptr as \a orientations or remove \ref
  15380. QCP::iRangeDrag from \ref QCustomPlot::setInteractions. To enable range dragging for both
  15381. directions, pass <tt>Qt::Horizontal | Qt::Vertical</tt> as \a orientations.
  15382. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
  15383. contains \ref QCP::iRangeDrag to enable the range dragging interaction.
  15384. \see setRangeZoom, setRangeDragAxes, QCustomPlot::setNoAntialiasingOnDrag
  15385. */
  15386. void QCPAxisRect::setRangeDrag(Qt::Orientations orientations)
  15387. {
  15388. mRangeDrag = orientations;
  15389. }
  15390. /*!
  15391. Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation
  15392. corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal,
  15393. QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical
  15394. axis is the left axis (yAxis).
  15395. To disable range zooming entirely, pass \c nullptr as \a orientations or remove \ref
  15396. QCP::iRangeZoom from \ref QCustomPlot::setInteractions. To enable range zooming for both
  15397. directions, pass <tt>Qt::Horizontal | Qt::Vertical</tt> as \a orientations.
  15398. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
  15399. contains \ref QCP::iRangeZoom to enable the range zooming interaction.
  15400. \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag
  15401. */
  15402. void QCPAxisRect::setRangeZoom(Qt::Orientations orientations)
  15403. {
  15404. mRangeZoom = orientations;
  15405. }
  15406. /*! \overload
  15407. Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging on
  15408. the QCustomPlot widget. Pass \c nullptr if no axis shall be dragged in the respective
  15409. orientation.
  15410. Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall
  15411. react to dragging interactions.
  15412. \see setRangeZoomAxes
  15413. */
  15414. void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical)
  15415. {
  15416. QList<QCPAxis*> horz, vert;
  15417. if (horizontal)
  15418. horz.append(horizontal);
  15419. if (vertical)
  15420. vert.append(vertical);
  15421. setRangeDragAxes(horz, vert);
  15422. }
  15423. /*! \overload
  15424. This method allows to set up multiple axes to react to horizontal and vertical dragging. The drag
  15425. orientation that the respective axis will react to is deduced from its orientation (\ref
  15426. QCPAxis::orientation).
  15427. In the unusual case that you wish to e.g. drag a vertically oriented axis with a horizontal drag
  15428. motion, use the overload taking two separate lists for horizontal and vertical dragging.
  15429. */
  15430. void QCPAxisRect::setRangeDragAxes(QList<QCPAxis*> axes)
  15431. {
  15432. QList<QCPAxis*> horz, vert;
  15433. foreach (QCPAxis *ax, axes)
  15434. {
  15435. if (ax->orientation() == Qt::Horizontal)
  15436. horz.append(ax);
  15437. else
  15438. vert.append(ax);
  15439. }
  15440. setRangeDragAxes(horz, vert);
  15441. }
  15442. /*! \overload
  15443. This method allows to set multiple axes up to react to horizontal and vertical dragging, and
  15444. define specifically which axis reacts to which drag orientation (irrespective of the axis
  15445. orientation).
  15446. */
  15447. void QCPAxisRect::setRangeDragAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical)
  15448. {
  15449. mRangeDragHorzAxis.clear();
  15450. foreach (QCPAxis *ax, horizontal)
  15451. {
  15452. QPointer<QCPAxis> axPointer(ax);
  15453. if (!axPointer.isNull())
  15454. mRangeDragHorzAxis.append(axPointer);
  15455. else
  15456. qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast<quintptr>(ax);
  15457. }
  15458. mRangeDragVertAxis.clear();
  15459. foreach (QCPAxis *ax, vertical)
  15460. {
  15461. QPointer<QCPAxis> axPointer(ax);
  15462. if (!axPointer.isNull())
  15463. mRangeDragVertAxis.append(axPointer);
  15464. else
  15465. qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast<quintptr>(ax);
  15466. }
  15467. }
  15468. /*!
  15469. Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on
  15470. the QCustomPlot widget. Pass \c nullptr if no axis shall be zoomed in the respective orientation.
  15471. The two axes can be zoomed with different strengths, when different factors are passed to \ref
  15472. setRangeZoomFactor(double horizontalFactor, double verticalFactor).
  15473. Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall
  15474. react to zooming interactions.
  15475. \see setRangeDragAxes
  15476. */
  15477. void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical)
  15478. {
  15479. QList<QCPAxis*> horz, vert;
  15480. if (horizontal)
  15481. horz.append(horizontal);
  15482. if (vertical)
  15483. vert.append(vertical);
  15484. setRangeZoomAxes(horz, vert);
  15485. }
  15486. /*! \overload
  15487. This method allows to set up multiple axes to react to horizontal and vertical range zooming. The
  15488. zoom orientation that the respective axis will react to is deduced from its orientation (\ref
  15489. QCPAxis::orientation).
  15490. In the unusual case that you wish to e.g. zoom a vertically oriented axis with a horizontal zoom
  15491. interaction, use the overload taking two separate lists for horizontal and vertical zooming.
  15492. */
  15493. void QCPAxisRect::setRangeZoomAxes(QList<QCPAxis*> axes)
  15494. {
  15495. QList<QCPAxis*> horz, vert;
  15496. foreach (QCPAxis *ax, axes)
  15497. {
  15498. if (ax->orientation() == Qt::Horizontal)
  15499. horz.append(ax);
  15500. else
  15501. vert.append(ax);
  15502. }
  15503. setRangeZoomAxes(horz, vert);
  15504. }
  15505. /*! \overload
  15506. This method allows to set multiple axes up to react to horizontal and vertical zooming, and
  15507. define specifically which axis reacts to which zoom orientation (irrespective of the axis
  15508. orientation).
  15509. */
  15510. void QCPAxisRect::setRangeZoomAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical)
  15511. {
  15512. mRangeZoomHorzAxis.clear();
  15513. foreach (QCPAxis *ax, horizontal)
  15514. {
  15515. QPointer<QCPAxis> axPointer(ax);
  15516. if (!axPointer.isNull())
  15517. mRangeZoomHorzAxis.append(axPointer);
  15518. else
  15519. qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast<quintptr>(ax);
  15520. }
  15521. mRangeZoomVertAxis.clear();
  15522. foreach (QCPAxis *ax, vertical)
  15523. {
  15524. QPointer<QCPAxis> axPointer(ax);
  15525. if (!axPointer.isNull())
  15526. mRangeZoomVertAxis.append(axPointer);
  15527. else
  15528. qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast<quintptr>(ax);
  15529. }
  15530. }
  15531. /*!
  15532. Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with
  15533. \ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to
  15534. let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal
  15535. and which is vertical, can be set with \ref setRangeZoomAxes.
  15536. When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user)
  15537. will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the
  15538. same scrolling direction will zoom out.
  15539. */
  15540. void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor)
  15541. {
  15542. mRangeZoomFactorHorz = horizontalFactor;
  15543. mRangeZoomFactorVert = verticalFactor;
  15544. }
  15545. /*! \overload
  15546. Sets both the horizontal and vertical zoom \a factor.
  15547. */
  15548. void QCPAxisRect::setRangeZoomFactor(double factor)
  15549. {
  15550. mRangeZoomFactorHorz = factor;
  15551. mRangeZoomFactorVert = factor;
  15552. }
  15553. /*! \internal
  15554. Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a
  15555. pixmap.
  15556. If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an
  15557. according filling inside the axis rect with the provided \a painter.
  15558. Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version
  15559. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  15560. the axis rect with the provided \a painter. The scaled version is buffered in
  15561. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  15562. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  15563. dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
  15564. set.
  15565. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  15566. */
  15567. void QCPAxisRect::drawBackground(QCPPainter *painter)
  15568. {
  15569. // draw background fill:
  15570. if (mBackgroundBrush != Qt::NoBrush)
  15571. painter->fillRect(mRect, mBackgroundBrush);
  15572. // draw background pixmap (on top of fill, if brush specified):
  15573. if (!mBackgroundPixmap.isNull())
  15574. {
  15575. if (mBackgroundScaled)
  15576. {
  15577. // check whether mScaledBackground needs to be updated:
  15578. QSize scaledSize(mBackgroundPixmap.size());
  15579. scaledSize.scale(mRect.size(), mBackgroundScaledMode);
  15580. if (mScaledBackgroundPixmap.size() != scaledSize)
  15581. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
  15582. painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect());
  15583. } else
  15584. {
  15585. painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()));
  15586. }
  15587. }
  15588. }
  15589. /*! \internal
  15590. This function makes sure multiple axes on the side specified with \a type don't collide, but are
  15591. distributed according to their respective space requirement (QCPAxis::calculateMargin).
  15592. It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the
  15593. one with index zero.
  15594. This function is called by \ref calculateAutoMargin.
  15595. */
  15596. void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type)
  15597. {
  15598. const QList<QCPAxis*> axesList = mAxes.value(type);
  15599. if (axesList.isEmpty())
  15600. return;
  15601. 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
  15602. for (int i=1; i<axesList.size(); ++i)
  15603. {
  15604. int offset = axesList.at(i-1)->offset() + axesList.at(i-1)->calculateMargin();
  15605. 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)
  15606. {
  15607. if (!isFirstVisible)
  15608. offset += axesList.at(i)->tickLengthIn();
  15609. isFirstVisible = false;
  15610. }
  15611. axesList.at(i)->setOffset(offset);
  15612. }
  15613. }
  15614. /* inherits documentation from base class */
  15615. int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side)
  15616. {
  15617. if (!mAutoMargins.testFlag(side))
  15618. qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin";
  15619. updateAxesOffset(QCPAxis::marginSideToAxisType(side));
  15620. // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call
  15621. const QList<QCPAxis*> axesList = mAxes.value(QCPAxis::marginSideToAxisType(side));
  15622. if (!axesList.isEmpty())
  15623. return axesList.last()->offset() + axesList.last()->calculateMargin();
  15624. else
  15625. return 0;
  15626. }
  15627. /*! \internal
  15628. Reacts to a change in layout to potentially set the convenience axis pointers \ref
  15629. QCustomPlot::xAxis, \ref QCustomPlot::yAxis, etc. of the parent QCustomPlot to the respective
  15630. axes of this axis rect. This is only done if the respective convenience pointer is currently zero
  15631. and if there is no QCPAxisRect at position (0, 0) of the plot layout.
  15632. This automation makes it simpler to replace the main axis rect with a newly created one, without
  15633. the need to manually reset the convenience pointers.
  15634. */
  15635. void QCPAxisRect::layoutChanged()
  15636. {
  15637. if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this)
  15638. {
  15639. if (axisCount(QCPAxis::atBottom) > 0 && !mParentPlot->xAxis)
  15640. mParentPlot->xAxis = axis(QCPAxis::atBottom);
  15641. if (axisCount(QCPAxis::atLeft) > 0 && !mParentPlot->yAxis)
  15642. mParentPlot->yAxis = axis(QCPAxis::atLeft);
  15643. if (axisCount(QCPAxis::atTop) > 0 && !mParentPlot->xAxis2)
  15644. mParentPlot->xAxis2 = axis(QCPAxis::atTop);
  15645. if (axisCount(QCPAxis::atRight) > 0 && !mParentPlot->yAxis2)
  15646. mParentPlot->yAxis2 = axis(QCPAxis::atRight);
  15647. }
  15648. }
  15649. /*! \internal
  15650. Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
  15651. pressed, the range dragging interaction is initialized (the actual range manipulation happens in
  15652. the \ref mouseMoveEvent).
  15653. The mDragging flag is set to true and some anchor points are set that are needed to determine the
  15654. distance the mouse was dragged in the mouse move/release events later.
  15655. \see mouseMoveEvent, mouseReleaseEvent
  15656. */
  15657. void QCPAxisRect::mousePressEvent(QMouseEvent *event, const QVariant &details)
  15658. {
  15659. Q_UNUSED(details)
  15660. if (event->buttons() & Qt::LeftButton)
  15661. {
  15662. mDragging = true;
  15663. // initialize antialiasing backup in case we start dragging:
  15664. if (mParentPlot->noAntialiasingOnDrag())
  15665. {
  15666. mAADragBackup = mParentPlot->antialiasedElements();
  15667. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  15668. }
  15669. // Mouse range dragging interaction:
  15670. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  15671. {
  15672. mDragStartHorzRange.clear();
  15673. foreach (QPointer<QCPAxis> axis, mRangeDragHorzAxis)
  15674. mDragStartHorzRange.append(axis.isNull() ? QCPRange() : axis->range());
  15675. mDragStartVertRange.clear();
  15676. foreach (QPointer<QCPAxis> axis, mRangeDragVertAxis)
  15677. mDragStartVertRange.append(axis.isNull() ? QCPRange() : axis->range());
  15678. }
  15679. }
  15680. }
  15681. /*! \internal
  15682. Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a
  15683. preceding \ref mousePressEvent, the range is moved accordingly.
  15684. \see mousePressEvent, mouseReleaseEvent
  15685. */
  15686. void QCPAxisRect::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  15687. {
  15688. Q_UNUSED(startPos)
  15689. // Mouse range dragging interaction:
  15690. if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  15691. {
  15692. if (mRangeDrag.testFlag(Qt::Horizontal))
  15693. {
  15694. for (int i=0; i<mRangeDragHorzAxis.size(); ++i)
  15695. {
  15696. QCPAxis *ax = mRangeDragHorzAxis.at(i).data();
  15697. if (!ax)
  15698. continue;
  15699. if (i >= mDragStartHorzRange.size())
  15700. break;
  15701. if (ax->mScaleType == QCPAxis::stLinear)
  15702. {
  15703. double diff = ax->pixelToCoord(startPos.x()) - ax->pixelToCoord(event->pos().x());
  15704. ax->setRange(mDragStartHorzRange.at(i).lower+diff, mDragStartHorzRange.at(i).upper+diff);
  15705. } else if (ax->mScaleType == QCPAxis::stLogarithmic)
  15706. {
  15707. double diff = ax->pixelToCoord(startPos.x()) / ax->pixelToCoord(event->pos().x());
  15708. ax->setRange(mDragStartHorzRange.at(i).lower*diff, mDragStartHorzRange.at(i).upper*diff);
  15709. }
  15710. }
  15711. }
  15712. if (mRangeDrag.testFlag(Qt::Vertical))
  15713. {
  15714. for (int i=0; i<mRangeDragVertAxis.size(); ++i)
  15715. {
  15716. QCPAxis *ax = mRangeDragVertAxis.at(i).data();
  15717. if (!ax)
  15718. continue;
  15719. if (i >= mDragStartVertRange.size())
  15720. break;
  15721. if (ax->mScaleType == QCPAxis::stLinear)
  15722. {
  15723. double diff = ax->pixelToCoord(startPos.y()) - ax->pixelToCoord(event->pos().y());
  15724. ax->setRange(mDragStartVertRange.at(i).lower+diff, mDragStartVertRange.at(i).upper+diff);
  15725. } else if (ax->mScaleType == QCPAxis::stLogarithmic)
  15726. {
  15727. double diff = ax->pixelToCoord(startPos.y()) / ax->pixelToCoord(event->pos().y());
  15728. ax->setRange(mDragStartVertRange.at(i).lower*diff, mDragStartVertRange.at(i).upper*diff);
  15729. }
  15730. }
  15731. }
  15732. if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot
  15733. {
  15734. if (mParentPlot->noAntialiasingOnDrag())
  15735. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  15736. mParentPlot->replot(QCustomPlot::rpQueuedReplot);
  15737. }
  15738. }
  15739. }
  15740. /* inherits documentation from base class */
  15741. void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  15742. {
  15743. Q_UNUSED(event)
  15744. Q_UNUSED(startPos)
  15745. mDragging = false;
  15746. if (mParentPlot->noAntialiasingOnDrag())
  15747. {
  15748. mParentPlot->setAntialiasedElements(mAADragBackup);
  15749. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  15750. }
  15751. }
  15752. /*! \internal
  15753. Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
  15754. ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
  15755. the scaling operation is the current cursor position inside the axis rect. The scaling factor is
  15756. dependent on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
  15757. zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
  15758. Note, that event->angleDelta() is usually +/-120 for single rotation steps. However, if the mouse
  15759. wheel is turned rapidly, many steps may bunch up to one event, so the delta may then be multiples
  15760. of 120. This is taken into account here, by calculating \a wheelSteps and using it as exponent of
  15761. the range zoom factor. This takes care of the wheel direction automatically, by inverting the
  15762. factor, when the wheel step is negative (f^-1 = 1/f).
  15763. */
  15764. void QCPAxisRect::wheelEvent(QWheelEvent *event)
  15765. {
  15766. #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  15767. const double delta = event->delta();
  15768. #else
  15769. const double delta = event->angleDelta().y();
  15770. #endif
  15771. #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  15772. const QPointF pos = event->pos();
  15773. #else
  15774. const QPointF pos = event->position();
  15775. #endif
  15776. // Mouse range zooming interaction:
  15777. if (mParentPlot->interactions().testFlag(QCP::iRangeZoom))
  15778. {
  15779. if (mRangeZoom != 0)
  15780. {
  15781. double factor;
  15782. double wheelSteps = delta/120.0; // a single step delta is +/-120 usually
  15783. if (mRangeZoom.testFlag(Qt::Horizontal))
  15784. {
  15785. factor = qPow(mRangeZoomFactorHorz, wheelSteps);
  15786. foreach (QPointer<QCPAxis> axis, mRangeZoomHorzAxis)
  15787. {
  15788. if (!axis.isNull())
  15789. axis->scaleRange(factor, axis->pixelToCoord(pos.x()));
  15790. }
  15791. }
  15792. if (mRangeZoom.testFlag(Qt::Vertical))
  15793. {
  15794. factor = qPow(mRangeZoomFactorVert, wheelSteps);
  15795. foreach (QPointer<QCPAxis> axis, mRangeZoomVertAxis)
  15796. {
  15797. if (!axis.isNull())
  15798. axis->scaleRange(factor, axis->pixelToCoord(pos.y()));
  15799. }
  15800. }
  15801. mParentPlot->replot();
  15802. }
  15803. }
  15804. }
  15805. /* end of 'src/layoutelements/layoutelement-axisrect.cpp' */
  15806. /* including file 'src/layoutelements/layoutelement-legend.cpp' */
  15807. /* modified 2022-11-06T12:45:56, size 31762 */
  15808. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15809. //////////////////// QCPAbstractLegendItem
  15810. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15811. /*! \class QCPAbstractLegendItem
  15812. \brief The abstract base class for all entries in a QCPLegend.
  15813. It defines a very basic interface for entries in a QCPLegend. For representing plottables in the
  15814. legend, the subclass \ref QCPPlottableLegendItem is more suitable.
  15815. Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry
  15816. that's not even associated with a plottable).
  15817. You must implement the following pure virtual functions:
  15818. \li \ref draw (from QCPLayerable)
  15819. You inherit the following members you may use:
  15820. <table>
  15821. <tr>
  15822. <td>QCPLegend *\b mParentLegend</td>
  15823. <td>A pointer to the parent QCPLegend.</td>
  15824. </tr><tr>
  15825. <td>QFont \b mFont</td>
  15826. <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>
  15827. </tr>
  15828. </table>
  15829. */
  15830. /* start of documentation of signals */
  15831. /*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected)
  15832. This signal is emitted when the selection state of this legend item has changed, either by user
  15833. interaction or by a direct call to \ref setSelected.
  15834. */
  15835. /* end of documentation of signals */
  15836. /*!
  15837. Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not
  15838. cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately.
  15839. */
  15840. QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) :
  15841. QCPLayoutElement(parent->parentPlot()),
  15842. mParentLegend(parent),
  15843. mFont(parent->font()),
  15844. mTextColor(parent->textColor()),
  15845. mSelectedFont(parent->selectedFont()),
  15846. mSelectedTextColor(parent->selectedTextColor()),
  15847. mSelectable(true),
  15848. mSelected(false)
  15849. {
  15850. setLayer(QLatin1String("legend"));
  15851. setMargins(QMargins(0, 0, 0, 0));
  15852. }
  15853. /*!
  15854. Sets the default font of this specific legend item to \a font.
  15855. \see setTextColor, QCPLegend::setFont
  15856. */
  15857. void QCPAbstractLegendItem::setFont(const QFont &font)
  15858. {
  15859. mFont = font;
  15860. }
  15861. /*!
  15862. Sets the default text color of this specific legend item to \a color.
  15863. \see setFont, QCPLegend::setTextColor
  15864. */
  15865. void QCPAbstractLegendItem::setTextColor(const QColor &color)
  15866. {
  15867. mTextColor = color;
  15868. }
  15869. /*!
  15870. When this legend item is selected, \a font is used to draw generic text, instead of the normal
  15871. font set with \ref setFont.
  15872. \see setFont, QCPLegend::setSelectedFont
  15873. */
  15874. void QCPAbstractLegendItem::setSelectedFont(const QFont &font)
  15875. {
  15876. mSelectedFont = font;
  15877. }
  15878. /*!
  15879. When this legend item is selected, \a color is used to draw generic text, instead of the normal
  15880. color set with \ref setTextColor.
  15881. \see setTextColor, QCPLegend::setSelectedTextColor
  15882. */
  15883. void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color)
  15884. {
  15885. mSelectedTextColor = color;
  15886. }
  15887. /*!
  15888. Sets whether this specific legend item is selectable.
  15889. \see setSelectedParts, QCustomPlot::setInteractions
  15890. */
  15891. void QCPAbstractLegendItem::setSelectable(bool selectable)
  15892. {
  15893. if (mSelectable != selectable)
  15894. {
  15895. mSelectable = selectable;
  15896. emit selectableChanged(mSelectable);
  15897. }
  15898. }
  15899. /*!
  15900. Sets whether this specific legend item is selected.
  15901. It is possible to set the selection state of this item by calling this function directly, even if
  15902. setSelectable is set to false.
  15903. \see setSelectableParts, QCustomPlot::setInteractions
  15904. */
  15905. void QCPAbstractLegendItem::setSelected(bool selected)
  15906. {
  15907. if (mSelected != selected)
  15908. {
  15909. mSelected = selected;
  15910. emit selectionChanged(mSelected);
  15911. }
  15912. }
  15913. /* inherits documentation from base class */
  15914. double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  15915. {
  15916. Q_UNUSED(details)
  15917. if (!mParentPlot) return -1;
  15918. if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems)))
  15919. return -1;
  15920. if (mRect.contains(pos.toPoint()))
  15921. return mParentPlot->selectionTolerance()*0.99;
  15922. else
  15923. return -1;
  15924. }
  15925. /* inherits documentation from base class */
  15926. void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
  15927. {
  15928. applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems);
  15929. }
  15930. /* inherits documentation from base class */
  15931. QRect QCPAbstractLegendItem::clipRect() const
  15932. {
  15933. return mOuterRect;
  15934. }
  15935. /* inherits documentation from base class */
  15936. void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  15937. {
  15938. Q_UNUSED(event)
  15939. Q_UNUSED(details)
  15940. if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
  15941. {
  15942. bool selBefore = mSelected;
  15943. setSelected(additive ? !mSelected : true);
  15944. if (selectionStateChanged)
  15945. *selectionStateChanged = mSelected != selBefore;
  15946. }
  15947. }
  15948. /* inherits documentation from base class */
  15949. void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged)
  15950. {
  15951. if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
  15952. {
  15953. bool selBefore = mSelected;
  15954. setSelected(false);
  15955. if (selectionStateChanged)
  15956. *selectionStateChanged = mSelected != selBefore;
  15957. }
  15958. }
  15959. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15960. //////////////////// QCPPlottableLegendItem
  15961. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15962. /*! \class QCPPlottableLegendItem
  15963. \brief A legend item representing a plottable with an icon and the plottable name.
  15964. This is the standard legend item for plottables. It displays an icon of the plottable next to the
  15965. plottable name. The icon is drawn by the respective plottable itself (\ref
  15966. QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable.
  15967. For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the
  15968. middle.
  15969. Legend items of this type are always associated with one plottable (retrievable via the
  15970. plottable() function and settable with the constructor). You may change the font of the plottable
  15971. name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref
  15972. QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding.
  15973. The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend
  15974. creates/removes legend items of this type.
  15975. Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of
  15976. QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout
  15977. interface, QCPLegend has specialized functions for handling legend items conveniently, see the
  15978. documentation of \ref QCPLegend.
  15979. */
  15980. /*!
  15981. Creates a new legend item associated with \a plottable.
  15982. Once it's created, it can be added to the legend via \ref QCPLegend::addItem.
  15983. A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref
  15984. QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend.
  15985. */
  15986. QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) :
  15987. QCPAbstractLegendItem(parent),
  15988. mPlottable(plottable)
  15989. {
  15990. setAntialiased(false);
  15991. }
  15992. /*! \internal
  15993. Returns the pen that shall be used to draw the icon border, taking into account the selection
  15994. state of this item.
  15995. */
  15996. QPen QCPPlottableLegendItem::getIconBorderPen() const
  15997. {
  15998. return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen();
  15999. }
  16000. /*! \internal
  16001. Returns the text color that shall be used to draw text, taking into account the selection state
  16002. of this item.
  16003. */
  16004. QColor QCPPlottableLegendItem::getTextColor() const
  16005. {
  16006. return mSelected ? mSelectedTextColor : mTextColor;
  16007. }
  16008. /*! \internal
  16009. Returns the font that shall be used to draw text, taking into account the selection state of this
  16010. item.
  16011. */
  16012. QFont QCPPlottableLegendItem::getFont() const
  16013. {
  16014. return mSelected ? mSelectedFont : mFont;
  16015. }
  16016. /*! \internal
  16017. Draws the item with \a painter. The size and position of the drawn legend item is defined by the
  16018. parent layout (typically a \ref QCPLegend) and the \ref minimumOuterSizeHint and \ref
  16019. maximumOuterSizeHint of this legend item.
  16020. */
  16021. void QCPPlottableLegendItem::draw(QCPPainter *painter)
  16022. {
  16023. if (!mPlottable) return;
  16024. painter->setFont(getFont());
  16025. painter->setPen(QPen(getTextColor()));
  16026. QSize iconSize = mParentLegend->iconSize();
  16027. QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
  16028. QRect iconRect(mRect.topLeft(), iconSize);
  16029. int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops
  16030. painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name());
  16031. // draw icon:
  16032. painter->save();
  16033. painter->setClipRect(iconRect, Qt::IntersectClip);
  16034. mPlottable->drawLegendIcon(painter, iconRect);
  16035. painter->restore();
  16036. // draw icon border:
  16037. if (getIconBorderPen().style() != Qt::NoPen)
  16038. {
  16039. painter->setPen(getIconBorderPen());
  16040. painter->setBrush(Qt::NoBrush);
  16041. int halfPen = qCeil(painter->pen().widthF()*0.5)+1;
  16042. painter->setClipRect(mOuterRect.adjusted(-halfPen, -halfPen, halfPen, halfPen)); // extend default clip rect so thicker pens (especially during selection) are not clipped
  16043. painter->drawRect(iconRect);
  16044. }
  16045. }
  16046. /*! \internal
  16047. Calculates and returns the size of this item. This includes the icon, the text and the padding in
  16048. between.
  16049. \seebaseclassmethod
  16050. */
  16051. QSize QCPPlottableLegendItem::minimumOuterSizeHint() const
  16052. {
  16053. if (!mPlottable) return {};
  16054. QSize result(0, 0);
  16055. QRect textRect;
  16056. QFontMetrics fontMetrics(getFont());
  16057. QSize iconSize = mParentLegend->iconSize();
  16058. textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
  16059. result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width());
  16060. result.setHeight(qMax(textRect.height(), iconSize.height()));
  16061. result.rwidth() += mMargins.left()+mMargins.right();
  16062. result.rheight() += mMargins.top()+mMargins.bottom();
  16063. return result;
  16064. }
  16065. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16066. //////////////////// QCPLegend
  16067. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16068. /*! \class QCPLegend
  16069. \brief Manages a legend inside a QCustomPlot.
  16070. A legend is a small box somewhere in the plot which lists plottables with their name and icon.
  16071. A legend is populated with legend items by calling \ref QCPAbstractPlottable::addToLegend on the
  16072. plottable, for which a legend item shall be created. In the case of the main legend (\ref
  16073. QCustomPlot::legend), simply adding plottables to the plot while \ref
  16074. QCustomPlot::setAutoAddPlottableToLegend is set to true (the default) creates corresponding
  16075. legend items. The legend item associated with a certain plottable can be removed with \ref
  16076. QCPAbstractPlottable::removeFromLegend. However, QCPLegend also offers an interface to add and
  16077. manipulate legend items directly: \ref item, \ref itemWithPlottable, \ref itemCount, \ref
  16078. addItem, \ref removeItem, etc.
  16079. Since \ref QCPLegend derives from \ref QCPLayoutGrid, it can be placed in any position a \ref
  16080. QCPLayoutElement may be positioned. The legend items are themselves \ref QCPLayoutElement
  16081. "QCPLayoutElements" which are placed in the grid layout of the legend. \ref QCPLegend only adds
  16082. an interface specialized for handling child elements of type \ref QCPAbstractLegendItem, as
  16083. mentioned above. In principle, any other layout elements may also be added to a legend via the
  16084. normal \ref QCPLayoutGrid interface. See the special page about \link thelayoutsystem The Layout
  16085. System\endlink for examples on how to add other elements to the legend and move it outside the axis
  16086. rect.
  16087. Use the methods \ref setFillOrder and \ref setWrap inherited from \ref QCPLayoutGrid to control
  16088. in which order (column first or row first) the legend is filled up when calling \ref addItem, and
  16089. at which column or row wrapping occurs. The default fill order for legends is \ref foRowsFirst.
  16090. By default, every QCustomPlot has one legend (\ref QCustomPlot::legend) which is placed in the
  16091. inset layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another
  16092. position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend
  16093. outside of the axis rect, place it anywhere else with the \ref QCPLayout/\ref QCPLayoutElement
  16094. interface.
  16095. */
  16096. /* start of documentation of signals */
  16097. /*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection);
  16098. This signal is emitted when the selection state of this legend has changed.
  16099. \see setSelectedParts, setSelectableParts
  16100. */
  16101. /* end of documentation of signals */
  16102. /*!
  16103. Constructs a new QCPLegend instance with default values.
  16104. Note that by default, QCustomPlot already contains a legend ready to be used as \ref
  16105. QCustomPlot::legend
  16106. */
  16107. QCPLegend::QCPLegend() :
  16108. mIconTextPadding{}
  16109. {
  16110. setFillOrder(QCPLayoutGrid::foRowsFirst);
  16111. setWrap(0);
  16112. setRowSpacing(3);
  16113. setColumnSpacing(8);
  16114. setMargins(QMargins(7, 5, 7, 4));
  16115. setAntialiased(false);
  16116. setIconSize(32, 18);
  16117. setIconTextPadding(7);
  16118. setSelectableParts(spLegendBox | spItems);
  16119. setSelectedParts(spNone);
  16120. setBorderPen(QPen(Qt::black, 0));
  16121. setSelectedBorderPen(QPen(Qt::blue, 2));
  16122. setIconBorderPen(Qt::NoPen);
  16123. setSelectedIconBorderPen(QPen(Qt::blue, 2));
  16124. setBrush(Qt::white);
  16125. setSelectedBrush(Qt::white);
  16126. setTextColor(Qt::black);
  16127. setSelectedTextColor(Qt::blue);
  16128. }
  16129. QCPLegend::~QCPLegend()
  16130. {
  16131. clearItems();
  16132. 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)
  16133. mParentPlot->legendRemoved(this);
  16134. }
  16135. /* no doc for getter, see setSelectedParts */
  16136. QCPLegend::SelectableParts QCPLegend::selectedParts() const
  16137. {
  16138. // check whether any legend elements selected, if yes, add spItems to return value
  16139. bool hasSelectedItems = false;
  16140. for (int i=0; i<itemCount(); ++i)
  16141. {
  16142. if (item(i) && item(i)->selected())
  16143. {
  16144. hasSelectedItems = true;
  16145. break;
  16146. }
  16147. }
  16148. if (hasSelectedItems)
  16149. return mSelectedParts | spItems;
  16150. else
  16151. return mSelectedParts & ~spItems;
  16152. }
  16153. /*!
  16154. Sets the pen, the border of the entire legend is drawn with.
  16155. */
  16156. void QCPLegend::setBorderPen(const QPen &pen)
  16157. {
  16158. mBorderPen = pen;
  16159. }
  16160. /*!
  16161. Sets the brush of the legend background.
  16162. */
  16163. void QCPLegend::setBrush(const QBrush &brush)
  16164. {
  16165. mBrush = brush;
  16166. }
  16167. /*!
  16168. Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will
  16169. use this font by default. However, a different font can be specified on a per-item-basis by
  16170. accessing the specific legend item.
  16171. This function will also set \a font on all already existing legend items.
  16172. \see QCPAbstractLegendItem::setFont
  16173. */
  16174. void QCPLegend::setFont(const QFont &font)
  16175. {
  16176. mFont = font;
  16177. for (int i=0; i<itemCount(); ++i)
  16178. {
  16179. if (item(i))
  16180. item(i)->setFont(mFont);
  16181. }
  16182. }
  16183. /*!
  16184. Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph)
  16185. will use this color by default. However, a different colors can be specified on a per-item-basis
  16186. by accessing the specific legend item.
  16187. This function will also set \a color on all already existing legend items.
  16188. \see QCPAbstractLegendItem::setTextColor
  16189. */
  16190. void QCPLegend::setTextColor(const QColor &color)
  16191. {
  16192. mTextColor = color;
  16193. for (int i=0; i<itemCount(); ++i)
  16194. {
  16195. if (item(i))
  16196. item(i)->setTextColor(color);
  16197. }
  16198. }
  16199. /*!
  16200. Sets the size of legend icons. Legend items that draw an icon (e.g. a visual
  16201. representation of the graph) will use this size by default.
  16202. */
  16203. void QCPLegend::setIconSize(const QSize &size)
  16204. {
  16205. mIconSize = size;
  16206. }
  16207. /*! \overload
  16208. */
  16209. void QCPLegend::setIconSize(int width, int height)
  16210. {
  16211. mIconSize.setWidth(width);
  16212. mIconSize.setHeight(height);
  16213. }
  16214. /*!
  16215. Sets the horizontal space in pixels between the legend icon and the text next to it.
  16216. Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the
  16217. name of the graph) will use this space by default.
  16218. */
  16219. void QCPLegend::setIconTextPadding(int padding)
  16220. {
  16221. mIconTextPadding = padding;
  16222. }
  16223. /*!
  16224. Sets the pen used to draw a border around each legend icon. Legend items that draw an
  16225. icon (e.g. a visual representation of the graph) will use this pen by default.
  16226. If no border is wanted, set this to \a Qt::NoPen.
  16227. */
  16228. void QCPLegend::setIconBorderPen(const QPen &pen)
  16229. {
  16230. mIconBorderPen = pen;
  16231. }
  16232. /*!
  16233. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  16234. (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.)
  16235. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  16236. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  16237. directly.
  16238. \see SelectablePart, setSelectedParts
  16239. */
  16240. void QCPLegend::setSelectableParts(const SelectableParts &selectable)
  16241. {
  16242. if (mSelectableParts != selectable)
  16243. {
  16244. mSelectableParts = selectable;
  16245. emit selectableChanged(mSelectableParts);
  16246. }
  16247. }
  16248. /*!
  16249. Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part
  16250. is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected
  16251. doesn't contain \ref spItems, those items become deselected.
  16252. The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions
  16253. contains iSelectLegend. You only need to call this function when you wish to change the selection
  16254. state manually.
  16255. This function can change the selection state of a part even when \ref setSelectableParts was set to a
  16256. value that actually excludes the part.
  16257. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  16258. Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set
  16259. before, because there's no way to specify which exact items to newly select. Do this by calling
  16260. \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select.
  16261. \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush,
  16262. setSelectedFont
  16263. */
  16264. void QCPLegend::setSelectedParts(const SelectableParts &selected)
  16265. {
  16266. SelectableParts newSelected = selected;
  16267. mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed
  16268. if (mSelectedParts != newSelected)
  16269. {
  16270. if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that)
  16271. {
  16272. qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function";
  16273. newSelected &= ~spItems;
  16274. }
  16275. if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection
  16276. {
  16277. for (int i=0; i<itemCount(); ++i)
  16278. {
  16279. if (item(i))
  16280. item(i)->setSelected(false);
  16281. }
  16282. }
  16283. mSelectedParts = newSelected;
  16284. emit selectionChanged(mSelectedParts);
  16285. }
  16286. }
  16287. /*!
  16288. When the legend box is selected, this pen is used to draw the border instead of the normal pen
  16289. set via \ref setBorderPen.
  16290. \see setSelectedParts, setSelectableParts, setSelectedBrush
  16291. */
  16292. void QCPLegend::setSelectedBorderPen(const QPen &pen)
  16293. {
  16294. mSelectedBorderPen = pen;
  16295. }
  16296. /*!
  16297. Sets the pen legend items will use to draw their icon borders, when they are selected.
  16298. \see setSelectedParts, setSelectableParts, setSelectedFont
  16299. */
  16300. void QCPLegend::setSelectedIconBorderPen(const QPen &pen)
  16301. {
  16302. mSelectedIconBorderPen = pen;
  16303. }
  16304. /*!
  16305. When the legend box is selected, this brush is used to draw the legend background instead of the normal brush
  16306. set via \ref setBrush.
  16307. \see setSelectedParts, setSelectableParts, setSelectedBorderPen
  16308. */
  16309. void QCPLegend::setSelectedBrush(const QBrush &brush)
  16310. {
  16311. mSelectedBrush = brush;
  16312. }
  16313. /*!
  16314. Sets the default font that is used by legend items when they are selected.
  16315. This function will also set \a font on all already existing legend items.
  16316. \see setFont, QCPAbstractLegendItem::setSelectedFont
  16317. */
  16318. void QCPLegend::setSelectedFont(const QFont &font)
  16319. {
  16320. mSelectedFont = font;
  16321. for (int i=0; i<itemCount(); ++i)
  16322. {
  16323. if (item(i))
  16324. item(i)->setSelectedFont(font);
  16325. }
  16326. }
  16327. /*!
  16328. Sets the default text color that is used by legend items when they are selected.
  16329. This function will also set \a color on all already existing legend items.
  16330. \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor
  16331. */
  16332. void QCPLegend::setSelectedTextColor(const QColor &color)
  16333. {
  16334. mSelectedTextColor = color;
  16335. for (int i=0; i<itemCount(); ++i)
  16336. {
  16337. if (item(i))
  16338. item(i)->setSelectedTextColor(color);
  16339. }
  16340. }
  16341. /*!
  16342. Returns the item with index \a i. If non-legend items were added to the legend, and the element
  16343. at the specified cell index is not a QCPAbstractLegendItem, returns \c nullptr.
  16344. Note that the linear index depends on the current fill order (\ref setFillOrder).
  16345. \see itemCount, addItem, itemWithPlottable
  16346. */
  16347. QCPAbstractLegendItem *QCPLegend::item(int index) const
  16348. {
  16349. return qobject_cast<QCPAbstractLegendItem*>(elementAt(index));
  16350. }
  16351. /*!
  16352. Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
  16353. If such an item isn't in the legend, returns \c nullptr.
  16354. \see hasItemWithPlottable
  16355. */
  16356. QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const
  16357. {
  16358. for (int i=0; i<itemCount(); ++i)
  16359. {
  16360. if (QCPPlottableLegendItem *pli = qobject_cast<QCPPlottableLegendItem*>(item(i)))
  16361. {
  16362. if (pli->plottable() == plottable)
  16363. return pli;
  16364. }
  16365. }
  16366. return nullptr;
  16367. }
  16368. /*!
  16369. Returns the number of items currently in the legend. It is identical to the base class
  16370. QCPLayoutGrid::elementCount(), and unlike the other "item" interface methods of QCPLegend,
  16371. doesn't only address elements which can be cast to QCPAbstractLegendItem.
  16372. Note that if empty cells are in the legend (e.g. by calling methods of the \ref QCPLayoutGrid
  16373. base class which allows creating empty cells), they are included in the returned count.
  16374. \see item
  16375. */
  16376. int QCPLegend::itemCount() const
  16377. {
  16378. return elementCount();
  16379. }
  16380. /*!
  16381. Returns whether the legend contains \a item.
  16382. \see hasItemWithPlottable
  16383. */
  16384. bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const
  16385. {
  16386. for (int i=0; i<itemCount(); ++i)
  16387. {
  16388. if (item == this->item(i))
  16389. return true;
  16390. }
  16391. return false;
  16392. }
  16393. /*!
  16394. Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
  16395. If such an item isn't in the legend, returns false.
  16396. \see itemWithPlottable
  16397. */
  16398. bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const
  16399. {
  16400. return itemWithPlottable(plottable);
  16401. }
  16402. /*!
  16403. Adds \a item to the legend, if it's not present already. The element is arranged according to the
  16404. current fill order (\ref setFillOrder) and wrapping (\ref setWrap).
  16405. Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added.
  16406. The legend takes ownership of the item.
  16407. \see removeItem, item, hasItem
  16408. */
  16409. bool QCPLegend::addItem(QCPAbstractLegendItem *item)
  16410. {
  16411. return addElement(item);
  16412. }
  16413. /*! \overload
  16414. Removes the item with the specified \a index from the legend and deletes it.
  16415. After successful removal, the legend is reordered according to the current fill order (\ref
  16416. setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item
  16417. was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid.
  16418. Returns true, if successful. Unlike \ref QCPLayoutGrid::removeAt, this method only removes
  16419. elements derived from \ref QCPAbstractLegendItem.
  16420. \see itemCount, clearItems
  16421. */
  16422. bool QCPLegend::removeItem(int index)
  16423. {
  16424. if (QCPAbstractLegendItem *ali = item(index))
  16425. {
  16426. bool success = remove(ali);
  16427. if (success)
  16428. setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering
  16429. return success;
  16430. } else
  16431. return false;
  16432. }
  16433. /*! \overload
  16434. Removes \a item from the legend and deletes it.
  16435. After successful removal, the legend is reordered according to the current fill order (\ref
  16436. setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item
  16437. was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid.
  16438. Returns true, if successful.
  16439. \see clearItems
  16440. */
  16441. bool QCPLegend::removeItem(QCPAbstractLegendItem *item)
  16442. {
  16443. bool success = remove(item);
  16444. if (success)
  16445. setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering
  16446. return success;
  16447. }
  16448. /*!
  16449. Removes all items from the legend.
  16450. */
  16451. void QCPLegend::clearItems()
  16452. {
  16453. for (int i=elementCount()-1; i>=0; --i)
  16454. {
  16455. if (item(i))
  16456. removeAt(i); // don't use removeItem() because it would unnecessarily reorder the whole legend for each item
  16457. }
  16458. setFillOrder(fillOrder(), true); // get rid of empty cells by reordering once after all items are removed
  16459. }
  16460. /*!
  16461. Returns the legend items that are currently selected. If no items are selected,
  16462. the list is empty.
  16463. \see QCPAbstractLegendItem::setSelected, setSelectable
  16464. */
  16465. QList<QCPAbstractLegendItem *> QCPLegend::selectedItems() const
  16466. {
  16467. QList<QCPAbstractLegendItem*> result;
  16468. for (int i=0; i<itemCount(); ++i)
  16469. {
  16470. if (QCPAbstractLegendItem *ali = item(i))
  16471. {
  16472. if (ali->selected())
  16473. result.append(ali);
  16474. }
  16475. }
  16476. return result;
  16477. }
  16478. /*! \internal
  16479. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  16480. before drawing main legend elements.
  16481. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  16482. This function takes into account the local setting of the antialiasing flag as well as the
  16483. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  16484. QCustomPlot::setNotAntialiasedElements.
  16485. \seebaseclassmethod
  16486. \see setAntialiased
  16487. */
  16488. void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const
  16489. {
  16490. applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend);
  16491. }
  16492. /*! \internal
  16493. Returns the pen used to paint the border of the legend, taking into account the selection state
  16494. of the legend box.
  16495. */
  16496. QPen QCPLegend::getBorderPen() const
  16497. {
  16498. return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen;
  16499. }
  16500. /*! \internal
  16501. Returns the brush used to paint the background of the legend, taking into account the selection
  16502. state of the legend box.
  16503. */
  16504. QBrush QCPLegend::getBrush() const
  16505. {
  16506. return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush;
  16507. }
  16508. /*! \internal
  16509. Draws the legend box with the provided \a painter. The individual legend items are layerables
  16510. themselves, thus are drawn independently.
  16511. */
  16512. void QCPLegend::draw(QCPPainter *painter)
  16513. {
  16514. // draw background rect:
  16515. painter->setBrush(getBrush());
  16516. painter->setPen(getBorderPen());
  16517. painter->drawRect(mOuterRect);
  16518. }
  16519. /* inherits documentation from base class */
  16520. double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  16521. {
  16522. if (!mParentPlot) return -1;
  16523. if (onlySelectable && !mSelectableParts.testFlag(spLegendBox))
  16524. return -1;
  16525. if (mOuterRect.contains(pos.toPoint()))
  16526. {
  16527. if (details) details->setValue(spLegendBox);
  16528. return mParentPlot->selectionTolerance()*0.99;
  16529. }
  16530. return -1;
  16531. }
  16532. /* inherits documentation from base class */
  16533. void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  16534. {
  16535. Q_UNUSED(event)
  16536. mSelectedParts = selectedParts(); // in case item selection has changed
  16537. if (details.value<SelectablePart>() == spLegendBox && mSelectableParts.testFlag(spLegendBox))
  16538. {
  16539. SelectableParts selBefore = mSelectedParts;
  16540. 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)
  16541. if (selectionStateChanged)
  16542. *selectionStateChanged = mSelectedParts != selBefore;
  16543. }
  16544. }
  16545. /* inherits documentation from base class */
  16546. void QCPLegend::deselectEvent(bool *selectionStateChanged)
  16547. {
  16548. mSelectedParts = selectedParts(); // in case item selection has changed
  16549. if (mSelectableParts.testFlag(spLegendBox))
  16550. {
  16551. SelectableParts selBefore = mSelectedParts;
  16552. setSelectedParts(selectedParts() & ~spLegendBox);
  16553. if (selectionStateChanged)
  16554. *selectionStateChanged = mSelectedParts != selBefore;
  16555. }
  16556. }
  16557. /* inherits documentation from base class */
  16558. QCP::Interaction QCPLegend::selectionCategory() const
  16559. {
  16560. return QCP::iSelectLegend;
  16561. }
  16562. /* inherits documentation from base class */
  16563. QCP::Interaction QCPAbstractLegendItem::selectionCategory() const
  16564. {
  16565. return QCP::iSelectLegend;
  16566. }
  16567. /* inherits documentation from base class */
  16568. void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot)
  16569. {
  16570. if (parentPlot && !parentPlot->legend)
  16571. parentPlot->legend = this;
  16572. }
  16573. /* end of 'src/layoutelements/layoutelement-legend.cpp' */
  16574. /* including file 'src/layoutelements/layoutelement-textelement.cpp' */
  16575. /* modified 2022-11-06T12:45:56, size 12925 */
  16576. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16577. //////////////////// QCPTextElement
  16578. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16579. /*! \class QCPTextElement
  16580. \brief A layout element displaying a text
  16581. The text may be specified with \ref setText, the formatting can be controlled with \ref setFont,
  16582. \ref setTextColor, and \ref setTextFlags.
  16583. A text element can be added as follows:
  16584. \snippet documentation/doc-code-snippets/mainwindow.cpp qcptextelement-creation
  16585. */
  16586. /* start documentation of signals */
  16587. /*! \fn void QCPTextElement::selectionChanged(bool selected)
  16588. This signal is emitted when the selection state has changed to \a selected, either by user
  16589. interaction or by a direct call to \ref setSelected.
  16590. \see setSelected, setSelectable
  16591. */
  16592. /*! \fn void QCPTextElement::clicked(QMouseEvent *event)
  16593. This signal is emitted when the text element is clicked.
  16594. \see doubleClicked, selectTest
  16595. */
  16596. /*! \fn void QCPTextElement::doubleClicked(QMouseEvent *event)
  16597. This signal is emitted when the text element is double clicked.
  16598. \see clicked, selectTest
  16599. */
  16600. /* end documentation of signals */
  16601. /*! \overload
  16602. Creates a new QCPTextElement instance and sets default values. The initial text is empty (\ref
  16603. setText).
  16604. */
  16605. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot) :
  16606. QCPLayoutElement(parentPlot),
  16607. mText(),
  16608. mTextFlags(Qt::AlignCenter),
  16609. mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  16610. mTextColor(Qt::black),
  16611. mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  16612. mSelectedTextColor(Qt::blue),
  16613. mSelectable(false),
  16614. mSelected(false)
  16615. {
  16616. if (parentPlot)
  16617. {
  16618. mFont = parentPlot->font();
  16619. mSelectedFont = parentPlot->font();
  16620. }
  16621. setMargins(QMargins(2, 2, 2, 2));
  16622. }
  16623. /*! \overload
  16624. Creates a new QCPTextElement instance and sets default values.
  16625. The initial text is set to \a text.
  16626. */
  16627. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text) :
  16628. QCPLayoutElement(parentPlot),
  16629. mText(text),
  16630. mTextFlags(Qt::AlignCenter),
  16631. mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  16632. mTextColor(Qt::black),
  16633. mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  16634. mSelectedTextColor(Qt::blue),
  16635. mSelectable(false),
  16636. mSelected(false)
  16637. {
  16638. if (parentPlot)
  16639. {
  16640. mFont = parentPlot->font();
  16641. mSelectedFont = parentPlot->font();
  16642. }
  16643. setMargins(QMargins(2, 2, 2, 2));
  16644. }
  16645. /*! \overload
  16646. Creates a new QCPTextElement instance and sets default values.
  16647. The initial text is set to \a text with \a pointSize.
  16648. */
  16649. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, double pointSize) :
  16650. QCPLayoutElement(parentPlot),
  16651. mText(text),
  16652. mTextFlags(Qt::AlignCenter),
  16653. mFont(QFont(QLatin1String("sans serif"), int(pointSize))), // will be taken from parentPlot if available, see below
  16654. mTextColor(Qt::black),
  16655. mSelectedFont(QFont(QLatin1String("sans serif"), int(pointSize))), // will be taken from parentPlot if available, see below
  16656. mSelectedTextColor(Qt::blue),
  16657. mSelectable(false),
  16658. mSelected(false)
  16659. {
  16660. mFont.setPointSizeF(pointSize); // set here again as floating point, because constructor above only takes integer
  16661. if (parentPlot)
  16662. {
  16663. mFont = parentPlot->font();
  16664. mFont.setPointSizeF(pointSize);
  16665. mSelectedFont = parentPlot->font();
  16666. mSelectedFont.setPointSizeF(pointSize);
  16667. }
  16668. setMargins(QMargins(2, 2, 2, 2));
  16669. }
  16670. /*! \overload
  16671. Creates a new QCPTextElement instance and sets default values.
  16672. The initial text is set to \a text with \a pointSize and the specified \a fontFamily.
  16673. */
  16674. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QString &fontFamily, double pointSize) :
  16675. QCPLayoutElement(parentPlot),
  16676. mText(text),
  16677. mTextFlags(Qt::AlignCenter),
  16678. mFont(QFont(fontFamily, int(pointSize))),
  16679. mTextColor(Qt::black),
  16680. mSelectedFont(QFont(fontFamily, int(pointSize))),
  16681. mSelectedTextColor(Qt::blue),
  16682. mSelectable(false),
  16683. mSelected(false)
  16684. {
  16685. mFont.setPointSizeF(pointSize); // set here again as floating point, because constructor above only takes integer
  16686. setMargins(QMargins(2, 2, 2, 2));
  16687. }
  16688. /*! \overload
  16689. Creates a new QCPTextElement instance and sets default values.
  16690. The initial text is set to \a text with the specified \a font.
  16691. */
  16692. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QFont &font) :
  16693. QCPLayoutElement(parentPlot),
  16694. mText(text),
  16695. mTextFlags(Qt::AlignCenter),
  16696. mFont(font),
  16697. mTextColor(Qt::black),
  16698. mSelectedFont(font),
  16699. mSelectedTextColor(Qt::blue),
  16700. mSelectable(false),
  16701. mSelected(false)
  16702. {
  16703. setMargins(QMargins(2, 2, 2, 2));
  16704. }
  16705. /*!
  16706. Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n".
  16707. \see setFont, setTextColor, setTextFlags
  16708. */
  16709. void QCPTextElement::setText(const QString &text)
  16710. {
  16711. mText = text;
  16712. }
  16713. /*!
  16714. Sets options for text alignment and wrapping behaviour. \a flags is a bitwise OR-combination of
  16715. \c Qt::AlignmentFlag and \c Qt::TextFlag enums.
  16716. Possible enums are:
  16717. - Qt::AlignLeft
  16718. - Qt::AlignRight
  16719. - Qt::AlignHCenter
  16720. - Qt::AlignJustify
  16721. - Qt::AlignTop
  16722. - Qt::AlignBottom
  16723. - Qt::AlignVCenter
  16724. - Qt::AlignCenter
  16725. - Qt::TextDontClip
  16726. - Qt::TextSingleLine
  16727. - Qt::TextExpandTabs
  16728. - Qt::TextShowMnemonic
  16729. - Qt::TextWordWrap
  16730. - Qt::TextIncludeTrailingSpaces
  16731. */
  16732. void QCPTextElement::setTextFlags(int flags)
  16733. {
  16734. mTextFlags = flags;
  16735. }
  16736. /*!
  16737. Sets the \a font of the text.
  16738. \see setTextColor, setSelectedFont
  16739. */
  16740. void QCPTextElement::setFont(const QFont &font)
  16741. {
  16742. mFont = font;
  16743. }
  16744. /*!
  16745. Sets the \a color of the text.
  16746. \see setFont, setSelectedTextColor
  16747. */
  16748. void QCPTextElement::setTextColor(const QColor &color)
  16749. {
  16750. mTextColor = color;
  16751. }
  16752. /*!
  16753. Sets the \a font of the text that will be used if the text element is selected (\ref setSelected).
  16754. \see setFont
  16755. */
  16756. void QCPTextElement::setSelectedFont(const QFont &font)
  16757. {
  16758. mSelectedFont = font;
  16759. }
  16760. /*!
  16761. Sets the \a color of the text that will be used if the text element is selected (\ref setSelected).
  16762. \see setTextColor
  16763. */
  16764. void QCPTextElement::setSelectedTextColor(const QColor &color)
  16765. {
  16766. mSelectedTextColor = color;
  16767. }
  16768. /*!
  16769. Sets whether the user may select this text element.
  16770. Note that even when \a selectable is set to <tt>false</tt>, the selection state may be changed
  16771. programmatically via \ref setSelected.
  16772. */
  16773. void QCPTextElement::setSelectable(bool selectable)
  16774. {
  16775. if (mSelectable != selectable)
  16776. {
  16777. mSelectable = selectable;
  16778. emit selectableChanged(mSelectable);
  16779. }
  16780. }
  16781. /*!
  16782. Sets the selection state of this text element to \a selected. If the selection has changed, \ref
  16783. selectionChanged is emitted.
  16784. Note that this function can change the selection state independently of the current \ref
  16785. setSelectable state.
  16786. */
  16787. void QCPTextElement::setSelected(bool selected)
  16788. {
  16789. if (mSelected != selected)
  16790. {
  16791. mSelected = selected;
  16792. emit selectionChanged(mSelected);
  16793. }
  16794. }
  16795. /* inherits documentation from base class */
  16796. void QCPTextElement::applyDefaultAntialiasingHint(QCPPainter *painter) const
  16797. {
  16798. applyAntialiasingHint(painter, mAntialiased, QCP::aeOther);
  16799. }
  16800. /* inherits documentation from base class */
  16801. void QCPTextElement::draw(QCPPainter *painter)
  16802. {
  16803. painter->setFont(mainFont());
  16804. painter->setPen(QPen(mainTextColor()));
  16805. painter->drawText(mRect, mTextFlags, mText, &mTextBoundingRect);
  16806. }
  16807. /* inherits documentation from base class */
  16808. QSize QCPTextElement::minimumOuterSizeHint() const
  16809. {
  16810. QFontMetrics metrics(mFont);
  16811. QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, mText).size());
  16812. result.rwidth() += mMargins.left()+mMargins.right();
  16813. result.rheight() += mMargins.top()+mMargins.bottom();
  16814. return result;
  16815. }
  16816. /* inherits documentation from base class */
  16817. QSize QCPTextElement::maximumOuterSizeHint() const
  16818. {
  16819. QFontMetrics metrics(mFont);
  16820. QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, mText).size());
  16821. result.setWidth(QWIDGETSIZE_MAX);
  16822. result.rheight() += mMargins.top()+mMargins.bottom();
  16823. return result;
  16824. }
  16825. /* inherits documentation from base class */
  16826. void QCPTextElement::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  16827. {
  16828. Q_UNUSED(event)
  16829. Q_UNUSED(details)
  16830. if (mSelectable)
  16831. {
  16832. bool selBefore = mSelected;
  16833. setSelected(additive ? !mSelected : true);
  16834. if (selectionStateChanged)
  16835. *selectionStateChanged = mSelected != selBefore;
  16836. }
  16837. }
  16838. /* inherits documentation from base class */
  16839. void QCPTextElement::deselectEvent(bool *selectionStateChanged)
  16840. {
  16841. if (mSelectable)
  16842. {
  16843. bool selBefore = mSelected;
  16844. setSelected(false);
  16845. if (selectionStateChanged)
  16846. *selectionStateChanged = mSelected != selBefore;
  16847. }
  16848. }
  16849. /*!
  16850. Returns 0.99*selectionTolerance (see \ref QCustomPlot::setSelectionTolerance) when \a pos is
  16851. within the bounding box of the text element's text. Note that this bounding box is updated in the
  16852. draw call.
  16853. If \a pos is outside the text's bounding box or if \a onlySelectable is true and this text
  16854. element is not selectable (\ref setSelectable), returns -1.
  16855. \seebaseclassmethod
  16856. */
  16857. double QCPTextElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  16858. {
  16859. Q_UNUSED(details)
  16860. if (onlySelectable && !mSelectable)
  16861. return -1;
  16862. if (mTextBoundingRect.contains(pos.toPoint()))
  16863. return mParentPlot->selectionTolerance()*0.99;
  16864. else
  16865. return -1;
  16866. }
  16867. /*!
  16868. Accepts the mouse event in order to emit the according click signal in the \ref
  16869. mouseReleaseEvent.
  16870. \seebaseclassmethod
  16871. */
  16872. void QCPTextElement::mousePressEvent(QMouseEvent *event, const QVariant &details)
  16873. {
  16874. Q_UNUSED(details)
  16875. event->accept();
  16876. }
  16877. /*!
  16878. Emits the \ref clicked signal if the cursor hasn't moved by more than a few pixels since the \ref
  16879. mousePressEvent.
  16880. \seebaseclassmethod
  16881. */
  16882. void QCPTextElement::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  16883. {
  16884. if ((QPointF(event->pos())-startPos).manhattanLength() <= 3)
  16885. emit clicked(event);
  16886. }
  16887. /*!
  16888. Emits the \ref doubleClicked signal.
  16889. \seebaseclassmethod
  16890. */
  16891. void QCPTextElement::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details)
  16892. {
  16893. Q_UNUSED(details)
  16894. emit doubleClicked(event);
  16895. }
  16896. /*! \internal
  16897. Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to
  16898. <tt>true</tt>, else mFont is returned.
  16899. */
  16900. QFont QCPTextElement::mainFont() const
  16901. {
  16902. return mSelected ? mSelectedFont : mFont;
  16903. }
  16904. /*! \internal
  16905. Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to
  16906. <tt>true</tt>, else mTextColor is returned.
  16907. */
  16908. QColor QCPTextElement::mainTextColor() const
  16909. {
  16910. return mSelected ? mSelectedTextColor : mTextColor;
  16911. }
  16912. /* end of 'src/layoutelements/layoutelement-textelement.cpp' */
  16913. /* including file 'src/layoutelements/layoutelement-colorscale.cpp' */
  16914. /* modified 2022-11-06T12:45:56, size 26531 */
  16915. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16916. //////////////////// QCPColorScale
  16917. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16918. /*! \class QCPColorScale
  16919. \brief A color scale for use with color coding data such as QCPColorMap
  16920. This layout element can be placed on the plot to correlate a color gradient with data values. It
  16921. is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps".
  16922. \image html QCPColorScale.png
  16923. The color scale can be either horizontal or vertical, as shown in the image above. The
  16924. orientation and the side where the numbers appear is controlled with \ref setType.
  16925. Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are
  16926. connected, they share their gradient, data range and data scale type (\ref setGradient, \ref
  16927. setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color
  16928. scale, to make them all synchronize these properties.
  16929. To have finer control over the number display and axis behaviour, you can directly access the
  16930. \ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if
  16931. you want to change the number of automatically generated ticks, call
  16932. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-tickcount
  16933. Placing a color scale next to the main axis rect works like with any other layout element:
  16934. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-creation
  16935. In this case we have placed it to the right of the default axis rect, so it wasn't necessary to
  16936. call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color
  16937. scale can be set with \ref setLabel.
  16938. For optimum appearance (like in the image above), it may be desirable to line up the axis rect and
  16939. the borders of the color scale. Use a \ref QCPMarginGroup to achieve this:
  16940. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-margingroup
  16941. Color scales are initialized with a non-zero minimum top and bottom margin (\ref
  16942. setMinimumMargins), because vertical color scales are most common and the minimum top/bottom
  16943. margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a
  16944. horizontal color scale by setting \ref setType to \ref QCPAxis::atBottom or \ref QCPAxis::atTop, you
  16945. might want to also change the minimum margins accordingly, e.g. <tt>setMinimumMargins(QMargins(6, 0, 6, 0))</tt>.
  16946. */
  16947. /* start documentation of inline functions */
  16948. /*! \fn QCPAxis *QCPColorScale::axis() const
  16949. Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the
  16950. appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its
  16951. interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref
  16952. setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref
  16953. QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on
  16954. the QCPColorScale or on its QCPAxis.
  16955. If the type of the color scale is changed with \ref setType, the axis returned by this method
  16956. will change, too, to either the left, right, bottom or top axis, depending on which type was set.
  16957. */
  16958. /* end documentation of signals */
  16959. /* start documentation of signals */
  16960. /*! \fn void QCPColorScale::dataRangeChanged(const QCPRange &newRange);
  16961. This signal is emitted when the data range changes.
  16962. \see setDataRange
  16963. */
  16964. /*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
  16965. This signal is emitted when the data scale type changes.
  16966. \see setDataScaleType
  16967. */
  16968. /*! \fn void QCPColorScale::gradientChanged(const QCPColorGradient &newGradient);
  16969. This signal is emitted when the gradient changes.
  16970. \see setGradient
  16971. */
  16972. /* end documentation of signals */
  16973. /*!
  16974. Constructs a new QCPColorScale.
  16975. */
  16976. QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) :
  16977. QCPLayoutElement(parentPlot),
  16978. mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight
  16979. mDataScaleType(QCPAxis::stLinear),
  16980. mGradient(QCPColorGradient::gpCold),
  16981. mBarWidth(20),
  16982. mAxisRect(new QCPColorScaleAxisRectPrivate(this))
  16983. {
  16984. 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)
  16985. setType(QCPAxis::atRight);
  16986. setDataRange(QCPRange(0, 6));
  16987. }
  16988. QCPColorScale::~QCPColorScale()
  16989. {
  16990. delete mAxisRect;
  16991. }
  16992. /* undocumented getter */
  16993. QString QCPColorScale::label() const
  16994. {
  16995. if (!mColorAxis)
  16996. {
  16997. qDebug() << Q_FUNC_INFO << "internal color axis undefined";
  16998. return QString();
  16999. }
  17000. return mColorAxis.data()->label();
  17001. }
  17002. /* undocumented getter */
  17003. bool QCPColorScale::rangeDrag() const
  17004. {
  17005. if (!mAxisRect)
  17006. {
  17007. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17008. return false;
  17009. }
  17010. return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) &&
  17011. mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) &&
  17012. mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
  17013. }
  17014. /* undocumented getter */
  17015. bool QCPColorScale::rangeZoom() const
  17016. {
  17017. if (!mAxisRect)
  17018. {
  17019. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17020. return false;
  17021. }
  17022. return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) &&
  17023. mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) &&
  17024. mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
  17025. }
  17026. /*!
  17027. Sets at which side of the color scale the axis is placed, and thus also its orientation.
  17028. Note that after setting \a type to a different value, the axis returned by \ref axis() will
  17029. be a different one. The new axis will adopt the following properties from the previous axis: The
  17030. range, scale type, label and ticker (the latter will be shared and not copied).
  17031. */
  17032. void QCPColorScale::setType(QCPAxis::AxisType type)
  17033. {
  17034. if (!mAxisRect)
  17035. {
  17036. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17037. return;
  17038. }
  17039. if (mType != type)
  17040. {
  17041. mType = type;
  17042. QCPRange rangeTransfer(0, 6);
  17043. QString labelTransfer;
  17044. QSharedPointer<QCPAxisTicker> tickerTransfer;
  17045. // transfer/revert some settings on old axis if it exists:
  17046. bool doTransfer = !mColorAxis.isNull();
  17047. if (doTransfer)
  17048. {
  17049. rangeTransfer = mColorAxis.data()->range();
  17050. labelTransfer = mColorAxis.data()->label();
  17051. tickerTransfer = mColorAxis.data()->ticker();
  17052. mColorAxis.data()->setLabel(QString());
  17053. disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  17054. disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  17055. }
  17056. const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop;
  17057. foreach (QCPAxis::AxisType atype, allAxisTypes)
  17058. {
  17059. mAxisRect.data()->axis(atype)->setTicks(atype == mType);
  17060. mAxisRect.data()->axis(atype)->setTickLabels(atype== mType);
  17061. }
  17062. // set new mColorAxis pointer:
  17063. mColorAxis = mAxisRect.data()->axis(mType);
  17064. // transfer settings to new axis:
  17065. if (doTransfer)
  17066. {
  17067. 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)
  17068. mColorAxis.data()->setLabel(labelTransfer);
  17069. mColorAxis.data()->setTicker(tickerTransfer);
  17070. }
  17071. connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  17072. connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  17073. mAxisRect.data()->setRangeDragAxes(QList<QCPAxis*>() << mColorAxis.data());
  17074. }
  17075. }
  17076. /*!
  17077. Sets the range spanned by the color gradient and that is shown by the axis in the color scale.
  17078. It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is
  17079. also equivalent to directly accessing the \ref axis and setting its range with \ref
  17080. QCPAxis::setRange.
  17081. \see setDataScaleType, setGradient, rescaleDataRange
  17082. */
  17083. void QCPColorScale::setDataRange(const QCPRange &dataRange)
  17084. {
  17085. if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
  17086. {
  17087. mDataRange = dataRange;
  17088. if (mColorAxis)
  17089. mColorAxis.data()->setRange(mDataRange);
  17090. emit dataRangeChanged(mDataRange);
  17091. }
  17092. }
  17093. /*!
  17094. Sets the scale type of the color scale, i.e. whether values are associated with colors linearly
  17095. or logarithmically.
  17096. It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is
  17097. also equivalent to directly accessing the \ref axis and setting its scale type with \ref
  17098. QCPAxis::setScaleType.
  17099. Note that this method controls the coordinate transformation. For logarithmic scales, you will
  17100. likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting
  17101. the color scale's \ref axis ticker to an instance of \ref QCPAxisTickerLog :
  17102. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-colorscale
  17103. See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick
  17104. creation.
  17105. \see setDataRange, setGradient
  17106. */
  17107. void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType)
  17108. {
  17109. if (mDataScaleType != scaleType)
  17110. {
  17111. mDataScaleType = scaleType;
  17112. if (mColorAxis)
  17113. mColorAxis.data()->setScaleType(mDataScaleType);
  17114. if (mDataScaleType == QCPAxis::stLogarithmic)
  17115. setDataRange(mDataRange.sanitizedForLogScale());
  17116. emit dataScaleTypeChanged(mDataScaleType);
  17117. }
  17118. }
  17119. /*!
  17120. Sets the color gradient that will be used to represent data values.
  17121. It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps.
  17122. \see setDataRange, setDataScaleType
  17123. */
  17124. void QCPColorScale::setGradient(const QCPColorGradient &gradient)
  17125. {
  17126. if (mGradient != gradient)
  17127. {
  17128. mGradient = gradient;
  17129. if (mAxisRect)
  17130. mAxisRect.data()->mGradientImageInvalidated = true;
  17131. emit gradientChanged(mGradient);
  17132. }
  17133. }
  17134. /*!
  17135. Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on
  17136. the internal \ref axis.
  17137. */
  17138. void QCPColorScale::setLabel(const QString &str)
  17139. {
  17140. if (!mColorAxis)
  17141. {
  17142. qDebug() << Q_FUNC_INFO << "internal color axis undefined";
  17143. return;
  17144. }
  17145. mColorAxis.data()->setLabel(str);
  17146. }
  17147. /*!
  17148. Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed
  17149. will have.
  17150. */
  17151. void QCPColorScale::setBarWidth(int width)
  17152. {
  17153. mBarWidth = width;
  17154. }
  17155. /*!
  17156. Sets whether the user can drag the data range (\ref setDataRange).
  17157. Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref
  17158. QCustomPlot::setInteractions) to allow range dragging.
  17159. */
  17160. void QCPColorScale::setRangeDrag(bool enabled)
  17161. {
  17162. if (!mAxisRect)
  17163. {
  17164. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17165. return;
  17166. }
  17167. if (enabled)
  17168. {
  17169. mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType));
  17170. } else
  17171. {
  17172. #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0)
  17173. mAxisRect.data()->setRangeDrag(nullptr);
  17174. #else
  17175. mAxisRect.data()->setRangeDrag({});
  17176. #endif
  17177. }
  17178. }
  17179. /*!
  17180. Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel.
  17181. Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref
  17182. QCustomPlot::setInteractions) to allow range dragging.
  17183. */
  17184. void QCPColorScale::setRangeZoom(bool enabled)
  17185. {
  17186. if (!mAxisRect)
  17187. {
  17188. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17189. return;
  17190. }
  17191. if (enabled)
  17192. {
  17193. mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType));
  17194. } else
  17195. {
  17196. #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0)
  17197. mAxisRect.data()->setRangeDrag(nullptr);
  17198. #else
  17199. mAxisRect.data()->setRangeZoom({});
  17200. #endif
  17201. }
  17202. }
  17203. /*!
  17204. Returns a list of all the color maps associated with this color scale.
  17205. */
  17206. QList<QCPColorMap*> QCPColorScale::colorMaps() const
  17207. {
  17208. QList<QCPColorMap*> result;
  17209. for (int i=0; i<mParentPlot->plottableCount(); ++i)
  17210. {
  17211. if (QCPColorMap *cm = qobject_cast<QCPColorMap*>(mParentPlot->plottable(i)))
  17212. if (cm->colorScale() == this)
  17213. result.append(cm);
  17214. }
  17215. return result;
  17216. }
  17217. /*!
  17218. Changes the data range such that all color maps associated with this color scale are fully mapped
  17219. to the gradient in the data dimension.
  17220. \see setDataRange
  17221. */
  17222. void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps)
  17223. {
  17224. QList<QCPColorMap*> maps = colorMaps();
  17225. QCPRange newRange;
  17226. bool haveRange = false;
  17227. QCP::SignDomain sign = QCP::sdBoth;
  17228. if (mDataScaleType == QCPAxis::stLogarithmic)
  17229. sign = (mDataRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  17230. foreach (QCPColorMap *map, maps)
  17231. {
  17232. if (!map->realVisibility() && onlyVisibleMaps)
  17233. continue;
  17234. QCPRange mapRange;
  17235. if (map->colorScale() == this)
  17236. {
  17237. bool currentFoundRange = true;
  17238. mapRange = map->data()->dataBounds();
  17239. if (sign == QCP::sdPositive)
  17240. {
  17241. if (mapRange.lower <= 0 && mapRange.upper > 0)
  17242. mapRange.lower = mapRange.upper*1e-3;
  17243. else if (mapRange.lower <= 0 && mapRange.upper <= 0)
  17244. currentFoundRange = false;
  17245. } else if (sign == QCP::sdNegative)
  17246. {
  17247. if (mapRange.upper >= 0 && mapRange.lower < 0)
  17248. mapRange.upper = mapRange.lower*1e-3;
  17249. else if (mapRange.upper >= 0 && mapRange.lower >= 0)
  17250. currentFoundRange = false;
  17251. }
  17252. if (currentFoundRange)
  17253. {
  17254. if (!haveRange)
  17255. newRange = mapRange;
  17256. else
  17257. newRange.expand(mapRange);
  17258. haveRange = true;
  17259. }
  17260. }
  17261. }
  17262. if (haveRange)
  17263. {
  17264. 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
  17265. {
  17266. 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
  17267. if (mDataScaleType == QCPAxis::stLinear)
  17268. {
  17269. newRange.lower = center-mDataRange.size()/2.0;
  17270. newRange.upper = center+mDataRange.size()/2.0;
  17271. } else // mScaleType == stLogarithmic
  17272. {
  17273. newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower);
  17274. newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower);
  17275. }
  17276. }
  17277. setDataRange(newRange);
  17278. }
  17279. }
  17280. /* inherits documentation from base class */
  17281. void QCPColorScale::update(UpdatePhase phase)
  17282. {
  17283. QCPLayoutElement::update(phase);
  17284. if (!mAxisRect)
  17285. {
  17286. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17287. return;
  17288. }
  17289. mAxisRect.data()->update(phase);
  17290. switch (phase)
  17291. {
  17292. case upMargins:
  17293. {
  17294. if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop)
  17295. {
  17296. setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom());
  17297. setMinimumSize(0, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom());
  17298. } else
  17299. {
  17300. setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), QWIDGETSIZE_MAX);
  17301. setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), 0);
  17302. }
  17303. break;
  17304. }
  17305. case upLayout:
  17306. {
  17307. mAxisRect.data()->setOuterRect(rect());
  17308. break;
  17309. }
  17310. default: break;
  17311. }
  17312. }
  17313. /* inherits documentation from base class */
  17314. void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const
  17315. {
  17316. painter->setAntialiasing(false);
  17317. }
  17318. /* inherits documentation from base class */
  17319. void QCPColorScale::mousePressEvent(QMouseEvent *event, const QVariant &details)
  17320. {
  17321. if (!mAxisRect)
  17322. {
  17323. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17324. return;
  17325. }
  17326. mAxisRect.data()->mousePressEvent(event, details);
  17327. }
  17328. /* inherits documentation from base class */
  17329. void QCPColorScale::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  17330. {
  17331. if (!mAxisRect)
  17332. {
  17333. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17334. return;
  17335. }
  17336. mAxisRect.data()->mouseMoveEvent(event, startPos);
  17337. }
  17338. /* inherits documentation from base class */
  17339. void QCPColorScale::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  17340. {
  17341. if (!mAxisRect)
  17342. {
  17343. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17344. return;
  17345. }
  17346. mAxisRect.data()->mouseReleaseEvent(event, startPos);
  17347. }
  17348. /* inherits documentation from base class */
  17349. void QCPColorScale::wheelEvent(QWheelEvent *event)
  17350. {
  17351. if (!mAxisRect)
  17352. {
  17353. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17354. return;
  17355. }
  17356. mAxisRect.data()->wheelEvent(event);
  17357. }
  17358. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17359. //////////////////// QCPColorScaleAxisRectPrivate
  17360. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17361. /*! \class QCPColorScaleAxisRectPrivate
  17362. \internal
  17363. \brief An axis rect subclass for use in a QCPColorScale
  17364. This is a private class and not part of the public QCustomPlot interface.
  17365. It provides the axis rect functionality for the QCPColorScale class.
  17366. */
  17367. /*!
  17368. Creates a new instance, as a child of \a parentColorScale.
  17369. */
  17370. QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) :
  17371. QCPAxisRect(parentColorScale->parentPlot(), true),
  17372. mParentColorScale(parentColorScale),
  17373. mGradientImageInvalidated(true)
  17374. {
  17375. setParentLayerable(parentColorScale);
  17376. setMinimumMargins(QMargins(0, 0, 0, 0));
  17377. const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
  17378. foreach (QCPAxis::AxisType type, allAxisTypes)
  17379. {
  17380. axis(type)->setVisible(true);
  17381. axis(type)->grid()->setVisible(false);
  17382. axis(type)->setPadding(0);
  17383. connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts)));
  17384. connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts)));
  17385. }
  17386. connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange)));
  17387. connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange)));
  17388. connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange)));
  17389. connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange)));
  17390. connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType)));
  17391. connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType)));
  17392. connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType)));
  17393. connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType)));
  17394. // make layer transfers of color scale transfer to axis rect and axes
  17395. // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect:
  17396. connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*)));
  17397. foreach (QCPAxis::AxisType type, allAxisTypes)
  17398. connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*)));
  17399. }
  17400. /*! \internal
  17401. Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws
  17402. it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation.
  17403. \seebaseclassmethod
  17404. */
  17405. void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter)
  17406. {
  17407. if (mGradientImageInvalidated)
  17408. updateGradientImage();
  17409. bool mirrorHorz = false;
  17410. bool mirrorVert = false;
  17411. if (mParentColorScale->mColorAxis)
  17412. {
  17413. mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop);
  17414. mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight);
  17415. }
  17416. painter->drawImage(rect().adjusted(0, -1, 0, -1), mGradientImage.mirrored(mirrorHorz, mirrorVert));
  17417. QCPAxisRect::draw(painter);
  17418. }
  17419. /*! \internal
  17420. Uses the current gradient of the parent \ref QCPColorScale (specified in the constructor) to
  17421. generate a gradient image. This gradient image will be used in the \ref draw method.
  17422. */
  17423. void QCPColorScaleAxisRectPrivate::updateGradientImage()
  17424. {
  17425. if (rect().isEmpty())
  17426. return;
  17427. const QImage::Format format = QImage::Format_ARGB32_Premultiplied;
  17428. int n = mParentColorScale->mGradient.levelCount();
  17429. int w, h;
  17430. QVector<double> data(n);
  17431. for (int i=0; i<n; ++i)
  17432. data[i] = i;
  17433. if (mParentColorScale->mType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop)
  17434. {
  17435. w = n;
  17436. h = rect().height();
  17437. mGradientImage = QImage(w, h, format);
  17438. QVector<QRgb*> pixels;
  17439. for (int y=0; y<h; ++y)
  17440. pixels.append(reinterpret_cast<QRgb*>(mGradientImage.scanLine(y)));
  17441. mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n);
  17442. for (int y=1; y<h; ++y)
  17443. memcpy(pixels.at(y), pixels.first(), size_t(n)*sizeof(QRgb));
  17444. } else
  17445. {
  17446. w = rect().width();
  17447. h = n;
  17448. mGradientImage = QImage(w, h, format);
  17449. for (int y=0; y<h; ++y)
  17450. {
  17451. QRgb *pixels = reinterpret_cast<QRgb*>(mGradientImage.scanLine(y));
  17452. const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1));
  17453. for (int x=0; x<w; ++x)
  17454. pixels[x] = lineColor;
  17455. }
  17456. }
  17457. mGradientImageInvalidated = false;
  17458. }
  17459. /*! \internal
  17460. This slot is connected to the selectionChanged signals of the four axes in the constructor. It
  17461. synchronizes the selection state of the axes.
  17462. */
  17463. void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts selectedParts)
  17464. {
  17465. // axis bases of four axes shall always (de-)selected synchronously:
  17466. const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
  17467. foreach (QCPAxis::AxisType type, allAxisTypes)
  17468. {
  17469. if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
  17470. if (senderAxis->axisType() == type)
  17471. continue;
  17472. if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
  17473. {
  17474. if (selectedParts.testFlag(QCPAxis::spAxis))
  17475. axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis);
  17476. else
  17477. axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis);
  17478. }
  17479. }
  17480. }
  17481. /*! \internal
  17482. This slot is connected to the selectableChanged signals of the four axes in the constructor. It
  17483. synchronizes the selectability of the axes.
  17484. */
  17485. void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts)
  17486. {
  17487. // synchronize axis base selectability:
  17488. const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
  17489. foreach (QCPAxis::AxisType type, allAxisTypes)
  17490. {
  17491. if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
  17492. if (senderAxis->axisType() == type)
  17493. continue;
  17494. if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
  17495. {
  17496. if (selectableParts.testFlag(QCPAxis::spAxis))
  17497. axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis);
  17498. else
  17499. axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis);
  17500. }
  17501. }
  17502. }
  17503. /* end of 'src/layoutelements/layoutelement-colorscale.cpp' */
  17504. /* including file 'src/plottables/plottable-graph.cpp' */
  17505. /* modified 2022-11-06T12:45:57, size 74926 */
  17506. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17507. //////////////////// QCPGraphData
  17508. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17509. /*! \class QCPGraphData
  17510. \brief Holds the data of one single data point for QCPGraph.
  17511. The stored data is:
  17512. \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
  17513. \li \a value: coordinate on the value axis of this data point (this is the \a mainValue)
  17514. The container for storing multiple data points is \ref QCPGraphDataContainer. It is a typedef for
  17515. \ref QCPDataContainer with \ref QCPGraphData as the DataType template parameter. See the
  17516. documentation there for an explanation regarding the data type's generic methods.
  17517. \see QCPGraphDataContainer
  17518. */
  17519. /* start documentation of inline functions */
  17520. /*! \fn double QCPGraphData::sortKey() const
  17521. Returns the \a key member of this data point.
  17522. For a general explanation of what this method is good for in the context of the data container,
  17523. see the documentation of \ref QCPDataContainer.
  17524. */
  17525. /*! \fn static QCPGraphData QCPGraphData::fromSortKey(double sortKey)
  17526. Returns a data point with the specified \a sortKey. All other members are set to zero.
  17527. For a general explanation of what this method is good for in the context of the data container,
  17528. see the documentation of \ref QCPDataContainer.
  17529. */
  17530. /*! \fn static static bool QCPGraphData::sortKeyIsMainKey()
  17531. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  17532. this method returns true.
  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. /*! \fn double QCPGraphData::mainKey() const
  17537. Returns the \a key member of this data point.
  17538. For a general explanation of what this method is good for in the context of the data container,
  17539. see the documentation of \ref QCPDataContainer.
  17540. */
  17541. /*! \fn double QCPGraphData::mainValue() const
  17542. Returns the \a value member of this data point.
  17543. For a general explanation of what this method is good for in the context of the data container,
  17544. see the documentation of \ref QCPDataContainer.
  17545. */
  17546. /*! \fn QCPRange QCPGraphData::valueRange() const
  17547. Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
  17548. For a general explanation of what this method is good for in the context of the data container,
  17549. see the documentation of \ref QCPDataContainer.
  17550. */
  17551. /* end documentation of inline functions */
  17552. /*!
  17553. Constructs a data point with key and value set to zero.
  17554. */
  17555. QCPGraphData::QCPGraphData() :
  17556. key(0),
  17557. value(0)
  17558. {
  17559. }
  17560. /*!
  17561. Constructs a data point with the specified \a key and \a value.
  17562. */
  17563. QCPGraphData::QCPGraphData(double key, double value) :
  17564. key(key),
  17565. value(value)
  17566. {
  17567. }
  17568. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17569. //////////////////// QCPGraph
  17570. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17571. /*! \class QCPGraph
  17572. \brief A plottable representing a graph in a plot.
  17573. \image html QCPGraph.png
  17574. Usually you create new graphs by calling QCustomPlot::addGraph. The resulting instance can be
  17575. accessed via QCustomPlot::graph.
  17576. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
  17577. also access and modify the data via the \ref data method, which returns a pointer to the internal
  17578. \ref QCPGraphDataContainer.
  17579. Graphs are used to display single-valued data. Single-valued means that there should only be one
  17580. data point per unique key coordinate. In other words, the graph can't have \a loops. If you do
  17581. want to plot non-single-valued curves, rather use the QCPCurve plottable.
  17582. Gaps in the graph line can be created by adding data points with NaN as value
  17583. (<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
  17584. separated.
  17585. \section qcpgraph-appearance Changing the appearance
  17586. The appearance of the graph is mainly determined by the line style, scatter style, brush and pen
  17587. of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen).
  17588. \subsection filling Filling under or between graphs
  17589. QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to
  17590. the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill,
  17591. just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent.
  17592. By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill
  17593. between this graph and another one, call \ref setChannelFillGraph with the other graph as
  17594. parameter.
  17595. \see QCustomPlot::addGraph, QCustomPlot::graph
  17596. */
  17597. /* start of documentation of inline functions */
  17598. /*! \fn QSharedPointer<QCPGraphDataContainer> QCPGraph::data() const
  17599. Returns a shared pointer to the internal data storage of type \ref QCPGraphDataContainer. You may
  17600. use it to directly manipulate the data, which may be more convenient and faster than using the
  17601. regular \ref setData or \ref addData methods.
  17602. */
  17603. /* end of documentation of inline functions */
  17604. /*!
  17605. Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  17606. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  17607. the same orientation. If either of these restrictions is violated, a corresponding message is
  17608. printed to the debug output (qDebug), the construction is not aborted, though.
  17609. The created QCPGraph is automatically registered with the QCustomPlot instance inferred from \a
  17610. keyAxis. This QCustomPlot instance takes ownership of the QCPGraph, so do not delete it manually
  17611. but use QCustomPlot::removePlottable() instead.
  17612. To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function.
  17613. */
  17614. QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  17615. QCPAbstractPlottable1D<QCPGraphData>(keyAxis, valueAxis),
  17616. mLineStyle{},
  17617. mScatterSkip{},
  17618. mAdaptiveSampling{}
  17619. {
  17620. // special handling for QCPGraphs to maintain the simple graph interface:
  17621. mParentPlot->registerGraph(this);
  17622. setPen(QPen(Qt::blue, 0));
  17623. setBrush(Qt::NoBrush);
  17624. setLineStyle(lsLine);
  17625. setScatterSkip(0);
  17626. setChannelFillGraph(nullptr);
  17627. setAdaptiveSampling(true);
  17628. }
  17629. QCPGraph::~QCPGraph()
  17630. {
  17631. }
  17632. /*! \overload
  17633. Replaces the current data container with the provided \a data container.
  17634. Since a QSharedPointer is used, multiple QCPGraphs may share the same data container safely.
  17635. Modifying the data in the container will then affect all graphs that share the container. Sharing
  17636. can be achieved by simply exchanging the data containers wrapped in shared pointers:
  17637. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-1
  17638. If you do not wish to share containers, but create a copy from an existing container, rather use
  17639. the \ref QCPDataContainer<DataType>::set method on the graph's data container directly:
  17640. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-2
  17641. \see addData
  17642. */
  17643. void QCPGraph::setData(QSharedPointer<QCPGraphDataContainer> data)
  17644. {
  17645. mDataContainer = data;
  17646. }
  17647. /*! \overload
  17648. Replaces the current data with the provided points in \a keys and \a values. The provided
  17649. vectors should have equal length. Else, the number of added points will be the size of the
  17650. smallest vector.
  17651. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  17652. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  17653. \see addData
  17654. */
  17655. void QCPGraph::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  17656. {
  17657. mDataContainer->clear();
  17658. addData(keys, values, alreadySorted);
  17659. }
  17660. /*!
  17661. Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
  17662. \ref lsNone and \ref setScatterStyle to the desired scatter style.
  17663. \see setScatterStyle
  17664. */
  17665. void QCPGraph::setLineStyle(LineStyle ls)
  17666. {
  17667. mLineStyle = ls;
  17668. }
  17669. /*!
  17670. Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points
  17671. are drawn (e.g. for line-only-plots with appropriate line style).
  17672. \see QCPScatterStyle, setLineStyle
  17673. */
  17674. void QCPGraph::setScatterStyle(const QCPScatterStyle &style)
  17675. {
  17676. mScatterStyle = style;
  17677. }
  17678. /*!
  17679. If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of
  17680. scatter points are skipped/not drawn after every drawn scatter point.
  17681. This can be used to make the data appear sparser while for example still having a smooth line,
  17682. and to improve performance for very high density plots.
  17683. If \a skip is set to 0 (default), all scatter points are drawn.
  17684. \see setScatterStyle
  17685. */
  17686. void QCPGraph::setScatterSkip(int skip)
  17687. {
  17688. mScatterSkip = qMax(0, skip);
  17689. }
  17690. /*!
  17691. Sets the target graph for filling the area between this graph and \a targetGraph with the current
  17692. brush (\ref setBrush).
  17693. When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To
  17694. disable any filling, set the brush to Qt::NoBrush.
  17695. \see setBrush
  17696. */
  17697. void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph)
  17698. {
  17699. // prevent setting channel target to this graph itself:
  17700. if (targetGraph == this)
  17701. {
  17702. qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself";
  17703. mChannelFillGraph = nullptr;
  17704. return;
  17705. }
  17706. // prevent setting channel target to a graph not in the plot:
  17707. if (targetGraph && targetGraph->mParentPlot != mParentPlot)
  17708. {
  17709. qDebug() << Q_FUNC_INFO << "targetGraph not in same plot";
  17710. mChannelFillGraph = nullptr;
  17711. return;
  17712. }
  17713. mChannelFillGraph = targetGraph;
  17714. }
  17715. /*!
  17716. Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive
  17717. sampling technique can drastically improve the replot performance for graphs with a larger number
  17718. of points (e.g. above 10,000), without notably changing the appearance of the graph.
  17719. By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive
  17720. sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no
  17721. disadvantage in almost all cases.
  17722. \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling"
  17723. As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are
  17724. reproduced reliably, as well as the overall shape of the data set. The replot time reduces
  17725. dramatically though. This allows QCustomPlot to display large amounts of data in realtime.
  17726. \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling"
  17727. Care must be taken when using high-density scatter plots in combination with adaptive sampling.
  17728. The adaptive sampling algorithm treats scatter plots more carefully than line plots which still
  17729. gives a significant reduction of replot times, but not quite as much as for line plots. This is
  17730. because scatter plots inherently need more data points to be preserved in order to still resemble
  17731. the original, non-adaptive-sampling plot. As shown above, the results still aren't quite
  17732. identical, as banding occurs for the outer data points. This is in fact intentional, such that
  17733. the boundaries of the data cloud stay visible to the viewer. How strong the banding appears,
  17734. depends on the point density, i.e. the number of points in the plot.
  17735. For some situations with scatter plots it might thus be desirable to manually turn adaptive
  17736. sampling off. For example, when saving the plot to disk. This can be achieved by setting \a
  17737. enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled
  17738. back to true afterwards.
  17739. */
  17740. void QCPGraph::setAdaptiveSampling(bool enabled)
  17741. {
  17742. mAdaptiveSampling = enabled;
  17743. }
  17744. /*! \overload
  17745. Adds the provided points in \a keys and \a values to the current data. The provided vectors
  17746. should have equal length. Else, the number of added points will be the size of the smallest
  17747. vector.
  17748. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  17749. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  17750. Alternatively, you can also access and modify the data directly via the \ref data method, which
  17751. returns a pointer to the internal data container.
  17752. */
  17753. void QCPGraph::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  17754. {
  17755. if (keys.size() != values.size())
  17756. qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
  17757. const int n = qMin(keys.size(), values.size());
  17758. QVector<QCPGraphData> tempData(n);
  17759. QVector<QCPGraphData>::iterator it = tempData.begin();
  17760. const QVector<QCPGraphData>::iterator itEnd = tempData.end();
  17761. int i = 0;
  17762. while (it != itEnd)
  17763. {
  17764. it->key = keys[i];
  17765. it->value = values[i];
  17766. ++it;
  17767. ++i;
  17768. }
  17769. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  17770. }
  17771. /*! \overload
  17772. Adds the provided data point as \a key and \a value to the current data.
  17773. Alternatively, you can also access and modify the data directly via the \ref data method, which
  17774. returns a pointer to the internal data container.
  17775. */
  17776. void QCPGraph::addData(double key, double value)
  17777. {
  17778. mDataContainer->add(QCPGraphData(key, value));
  17779. }
  17780. /*!
  17781. Implements a selectTest specific to this plottable's point geometry.
  17782. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  17783. point to \a pos.
  17784. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  17785. */
  17786. double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  17787. {
  17788. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  17789. return -1;
  17790. if (!mKeyAxis || !mValueAxis)
  17791. return -1;
  17792. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  17793. {
  17794. QCPGraphDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  17795. double result = pointDistance(pos, closestDataPoint);
  17796. if (details)
  17797. {
  17798. int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
  17799. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  17800. }
  17801. return result;
  17802. } else
  17803. return -1;
  17804. }
  17805. /* inherits documentation from base class */
  17806. QCPRange QCPGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  17807. {
  17808. return mDataContainer->keyRange(foundRange, inSignDomain);
  17809. }
  17810. /* inherits documentation from base class */
  17811. QCPRange QCPGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  17812. {
  17813. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  17814. }
  17815. /* inherits documentation from base class */
  17816. void QCPGraph::draw(QCPPainter *painter)
  17817. {
  17818. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  17819. if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
  17820. if (mLineStyle == lsNone && mScatterStyle.isNone()) return;
  17821. QVector<QPointF> lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments
  17822. // loop over and draw segments of unselected/selected data:
  17823. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  17824. getDataSegments(selectedSegments, unselectedSegments);
  17825. allSegments << unselectedSegments << selectedSegments;
  17826. for (int i=0; i<allSegments.size(); ++i)
  17827. {
  17828. bool isSelectedSegment = i >= unselectedSegments.size();
  17829. // get line pixel points appropriate to line style:
  17830. 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)
  17831. getLines(&lines, lineDataRange);
  17832. // check data validity if flag set:
  17833. #ifdef QCUSTOMPLOT_CHECK_DATA
  17834. QCPGraphDataContainer::const_iterator it;
  17835. for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  17836. {
  17837. if (QCP::isInvalidData(it->key, it->value))
  17838. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
  17839. }
  17840. #endif
  17841. // draw fill of graph:
  17842. if (isSelectedSegment && mSelectionDecorator)
  17843. mSelectionDecorator->applyBrush(painter);
  17844. else
  17845. painter->setBrush(mBrush);
  17846. painter->setPen(Qt::NoPen);
  17847. drawFill(painter, &lines);
  17848. // draw line:
  17849. if (mLineStyle != lsNone)
  17850. {
  17851. if (isSelectedSegment && mSelectionDecorator)
  17852. mSelectionDecorator->applyPen(painter);
  17853. else
  17854. painter->setPen(mPen);
  17855. painter->setBrush(Qt::NoBrush);
  17856. if (mLineStyle == lsImpulse)
  17857. drawImpulsePlot(painter, lines);
  17858. else
  17859. drawLinePlot(painter, lines); // also step plots can be drawn as a line plot
  17860. }
  17861. // draw scatters:
  17862. QCPScatterStyle finalScatterStyle = mScatterStyle;
  17863. if (isSelectedSegment && mSelectionDecorator)
  17864. finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
  17865. if (!finalScatterStyle.isNone())
  17866. {
  17867. getScatters(&scatters, allSegments.at(i));
  17868. drawScatterPlot(painter, scatters, finalScatterStyle);
  17869. }
  17870. }
  17871. // draw other selection decoration that isn't just line/scatter pens and brushes:
  17872. if (mSelectionDecorator)
  17873. mSelectionDecorator->drawDecoration(painter, selection());
  17874. }
  17875. /* inherits documentation from base class */
  17876. void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  17877. {
  17878. // draw fill:
  17879. if (mBrush.style() != Qt::NoBrush)
  17880. {
  17881. applyFillAntialiasingHint(painter);
  17882. painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
  17883. }
  17884. // draw line vertically centered:
  17885. if (mLineStyle != lsNone)
  17886. {
  17887. applyDefaultAntialiasingHint(painter);
  17888. painter->setPen(mPen);
  17889. 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
  17890. }
  17891. // draw scatter symbol:
  17892. if (!mScatterStyle.isNone())
  17893. {
  17894. applyScattersAntialiasingHint(painter);
  17895. // scale scatter pixmap if it's too large to fit in legend icon rect:
  17896. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
  17897. {
  17898. QCPScatterStyle scaledStyle(mScatterStyle);
  17899. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  17900. scaledStyle.applyTo(painter, mPen);
  17901. scaledStyle.drawShape(painter, QRectF(rect).center());
  17902. } else
  17903. {
  17904. mScatterStyle.applyTo(painter, mPen);
  17905. mScatterStyle.drawShape(painter, QRectF(rect).center());
  17906. }
  17907. }
  17908. }
  17909. /*! \internal
  17910. This method retrieves an optimized set of data points via \ref getOptimizedLineData, and branches
  17911. out to the line style specific functions such as \ref dataToLines, \ref dataToStepLeftLines, etc.
  17912. according to the line style of the graph.
  17913. \a lines will be filled with points in pixel coordinates, that can be drawn with the according
  17914. draw functions like \ref drawLinePlot and \ref drawImpulsePlot. The points returned in \a lines
  17915. aren't necessarily the original data points. For example, step line styles require additional
  17916. points to form the steps when drawn. If the line style of the graph is \ref lsNone, the \a
  17917. lines vector will be empty.
  17918. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  17919. conversion. In this function, the specified range may exceed the total data bounds without harm:
  17920. a correspondingly trimmed data range will be used. This takes the burden off the user of this
  17921. function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
  17922. getDataSegments.
  17923. \see getScatters
  17924. */
  17925. void QCPGraph::getLines(QVector<QPointF> *lines, const QCPDataRange &dataRange) const
  17926. {
  17927. if (!lines) return;
  17928. QCPGraphDataContainer::const_iterator begin, end;
  17929. getVisibleDataBounds(begin, end, dataRange);
  17930. if (begin == end)
  17931. {
  17932. lines->clear();
  17933. return;
  17934. }
  17935. QVector<QCPGraphData> lineData;
  17936. if (mLineStyle != lsNone)
  17937. getOptimizedLineData(&lineData, begin, end);
  17938. if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in lineData (significantly simplifies following processing)
  17939. std::reverse(lineData.begin(), lineData.end());
  17940. switch (mLineStyle)
  17941. {
  17942. case lsNone: lines->clear(); break;
  17943. case lsLine: *lines = dataToLines(lineData); break;
  17944. case lsStepLeft: *lines = dataToStepLeftLines(lineData); break;
  17945. case lsStepRight: *lines = dataToStepRightLines(lineData); break;
  17946. case lsStepCenter: *lines = dataToStepCenterLines(lineData); break;
  17947. case lsImpulse: *lines = dataToImpulseLines(lineData); break;
  17948. }
  17949. }
  17950. /*! \internal
  17951. This method retrieves an optimized set of data points via \ref getOptimizedScatterData and then
  17952. converts them to pixel coordinates. The resulting points are returned in \a scatters, and can be
  17953. passed to \ref drawScatterPlot.
  17954. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  17955. conversion. In this function, the specified range may exceed the total data bounds without harm:
  17956. a correspondingly trimmed data range will be used. This takes the burden off the user of this
  17957. function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
  17958. getDataSegments.
  17959. */
  17960. void QCPGraph::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange) const
  17961. {
  17962. if (!scatters) return;
  17963. QCPAxis *keyAxis = mKeyAxis.data();
  17964. QCPAxis *valueAxis = mValueAxis.data();
  17965. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; scatters->clear(); return; }
  17966. QCPGraphDataContainer::const_iterator begin, end;
  17967. getVisibleDataBounds(begin, end, dataRange);
  17968. if (begin == end)
  17969. {
  17970. scatters->clear();
  17971. return;
  17972. }
  17973. QVector<QCPGraphData> data;
  17974. getOptimizedScatterData(&data, begin, end);
  17975. if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in data (significantly simplifies following processing)
  17976. std::reverse(data.begin(), data.end());
  17977. scatters->resize(data.size());
  17978. if (keyAxis->orientation() == Qt::Vertical)
  17979. {
  17980. for (int i=0; i<data.size(); ++i)
  17981. {
  17982. if (!qIsNaN(data.at(i).value))
  17983. {
  17984. (*scatters)[i].setX(valueAxis->coordToPixel(data.at(i).value));
  17985. (*scatters)[i].setY(keyAxis->coordToPixel(data.at(i).key));
  17986. }
  17987. }
  17988. } else
  17989. {
  17990. for (int i=0; i<data.size(); ++i)
  17991. {
  17992. if (!qIsNaN(data.at(i).value))
  17993. {
  17994. (*scatters)[i].setX(keyAxis->coordToPixel(data.at(i).key));
  17995. (*scatters)[i].setY(valueAxis->coordToPixel(data.at(i).value));
  17996. }
  17997. }
  17998. }
  17999. }
  18000. /*! \internal
  18001. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  18002. coordinate points which are suitable for drawing the line style \ref lsLine.
  18003. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  18004. getLines if the line style is set accordingly.
  18005. \see dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
  18006. */
  18007. QVector<QPointF> QCPGraph::dataToLines(const QVector<QCPGraphData> &data) const
  18008. {
  18009. QVector<QPointF> result;
  18010. QCPAxis *keyAxis = mKeyAxis.data();
  18011. QCPAxis *valueAxis = mValueAxis.data();
  18012. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  18013. result.resize(data.size());
  18014. // transform data points to pixels:
  18015. if (keyAxis->orientation() == Qt::Vertical)
  18016. {
  18017. for (int i=0; i<data.size(); ++i)
  18018. {
  18019. result[i].setX(valueAxis->coordToPixel(data.at(i).value));
  18020. result[i].setY(keyAxis->coordToPixel(data.at(i).key));
  18021. }
  18022. } else // key axis is horizontal
  18023. {
  18024. for (int i=0; i<data.size(); ++i)
  18025. {
  18026. result[i].setX(keyAxis->coordToPixel(data.at(i).key));
  18027. result[i].setY(valueAxis->coordToPixel(data.at(i).value));
  18028. }
  18029. }
  18030. return result;
  18031. }
  18032. /*! \internal
  18033. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  18034. coordinate points which are suitable for drawing the line style \ref lsStepLeft.
  18035. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  18036. getLines if the line style is set accordingly.
  18037. \see dataToLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
  18038. */
  18039. QVector<QPointF> QCPGraph::dataToStepLeftLines(const QVector<QCPGraphData> &data) const
  18040. {
  18041. QVector<QPointF> result;
  18042. QCPAxis *keyAxis = mKeyAxis.data();
  18043. QCPAxis *valueAxis = mValueAxis.data();
  18044. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  18045. result.resize(data.size()*2);
  18046. // calculate steps from data and transform to pixel coordinates:
  18047. if (keyAxis->orientation() == Qt::Vertical)
  18048. {
  18049. double lastValue = valueAxis->coordToPixel(data.first().value);
  18050. for (int i=0; i<data.size(); ++i)
  18051. {
  18052. const double key = keyAxis->coordToPixel(data.at(i).key);
  18053. result[i*2+0].setX(lastValue);
  18054. result[i*2+0].setY(key);
  18055. lastValue = valueAxis->coordToPixel(data.at(i).value);
  18056. result[i*2+1].setX(lastValue);
  18057. result[i*2+1].setY(key);
  18058. }
  18059. } else // key axis is horizontal
  18060. {
  18061. double lastValue = valueAxis->coordToPixel(data.first().value);
  18062. for (int i=0; i<data.size(); ++i)
  18063. {
  18064. const double key = keyAxis->coordToPixel(data.at(i).key);
  18065. result[i*2+0].setX(key);
  18066. result[i*2+0].setY(lastValue);
  18067. lastValue = valueAxis->coordToPixel(data.at(i).value);
  18068. result[i*2+1].setX(key);
  18069. result[i*2+1].setY(lastValue);
  18070. }
  18071. }
  18072. return result;
  18073. }
  18074. /*! \internal
  18075. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  18076. coordinate points which are suitable for drawing the line style \ref lsStepRight.
  18077. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  18078. getLines if the line style is set accordingly.
  18079. \see dataToLines, dataToStepLeftLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
  18080. */
  18081. QVector<QPointF> QCPGraph::dataToStepRightLines(const QVector<QCPGraphData> &data) const
  18082. {
  18083. QVector<QPointF> result;
  18084. QCPAxis *keyAxis = mKeyAxis.data();
  18085. QCPAxis *valueAxis = mValueAxis.data();
  18086. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  18087. result.resize(data.size()*2);
  18088. // calculate steps from data and transform to pixel coordinates:
  18089. if (keyAxis->orientation() == Qt::Vertical)
  18090. {
  18091. double lastKey = keyAxis->coordToPixel(data.first().key);
  18092. for (int i=0; i<data.size(); ++i)
  18093. {
  18094. const double value = valueAxis->coordToPixel(data.at(i).value);
  18095. result[i*2+0].setX(value);
  18096. result[i*2+0].setY(lastKey);
  18097. lastKey = keyAxis->coordToPixel(data.at(i).key);
  18098. result[i*2+1].setX(value);
  18099. result[i*2+1].setY(lastKey);
  18100. }
  18101. } else // key axis is horizontal
  18102. {
  18103. double lastKey = keyAxis->coordToPixel(data.first().key);
  18104. for (int i=0; i<data.size(); ++i)
  18105. {
  18106. const double value = valueAxis->coordToPixel(data.at(i).value);
  18107. result[i*2+0].setX(lastKey);
  18108. result[i*2+0].setY(value);
  18109. lastKey = keyAxis->coordToPixel(data.at(i).key);
  18110. result[i*2+1].setX(lastKey);
  18111. result[i*2+1].setY(value);
  18112. }
  18113. }
  18114. return result;
  18115. }
  18116. /*! \internal
  18117. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  18118. coordinate points which are suitable for drawing the line style \ref lsStepCenter.
  18119. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  18120. getLines if the line style is set accordingly.
  18121. \see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToImpulseLines, getLines, drawLinePlot
  18122. */
  18123. QVector<QPointF> QCPGraph::dataToStepCenterLines(const QVector<QCPGraphData> &data) const
  18124. {
  18125. QVector<QPointF> result;
  18126. QCPAxis *keyAxis = mKeyAxis.data();
  18127. QCPAxis *valueAxis = mValueAxis.data();
  18128. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  18129. result.resize(data.size()*2);
  18130. // calculate steps from data and transform to pixel coordinates:
  18131. if (keyAxis->orientation() == Qt::Vertical)
  18132. {
  18133. double lastKey = keyAxis->coordToPixel(data.first().key);
  18134. double lastValue = valueAxis->coordToPixel(data.first().value);
  18135. result[0].setX(lastValue);
  18136. result[0].setY(lastKey);
  18137. for (int i=1; i<data.size(); ++i)
  18138. {
  18139. const double key = (keyAxis->coordToPixel(data.at(i).key)+lastKey)*0.5;
  18140. result[i*2-1].setX(lastValue);
  18141. result[i*2-1].setY(key);
  18142. lastValue = valueAxis->coordToPixel(data.at(i).value);
  18143. lastKey = keyAxis->coordToPixel(data.at(i).key);
  18144. result[i*2+0].setX(lastValue);
  18145. result[i*2+0].setY(key);
  18146. }
  18147. result[data.size()*2-1].setX(lastValue);
  18148. result[data.size()*2-1].setY(lastKey);
  18149. } else // key axis is horizontal
  18150. {
  18151. double lastKey = keyAxis->coordToPixel(data.first().key);
  18152. double lastValue = valueAxis->coordToPixel(data.first().value);
  18153. result[0].setX(lastKey);
  18154. result[0].setY(lastValue);
  18155. for (int i=1; i<data.size(); ++i)
  18156. {
  18157. const double key = (keyAxis->coordToPixel(data.at(i).key)+lastKey)*0.5;
  18158. result[i*2-1].setX(key);
  18159. result[i*2-1].setY(lastValue);
  18160. lastValue = valueAxis->coordToPixel(data.at(i).value);
  18161. lastKey = keyAxis->coordToPixel(data.at(i).key);
  18162. result[i*2+0].setX(key);
  18163. result[i*2+0].setY(lastValue);
  18164. }
  18165. result[data.size()*2-1].setX(lastKey);
  18166. result[data.size()*2-1].setY(lastValue);
  18167. }
  18168. return result;
  18169. }
  18170. /*! \internal
  18171. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  18172. coordinate points which are suitable for drawing the line style \ref lsImpulse.
  18173. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  18174. getLines if the line style is set accordingly.
  18175. \see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, getLines, drawImpulsePlot
  18176. */
  18177. QVector<QPointF> QCPGraph::dataToImpulseLines(const QVector<QCPGraphData> &data) const
  18178. {
  18179. QVector<QPointF> result;
  18180. QCPAxis *keyAxis = mKeyAxis.data();
  18181. QCPAxis *valueAxis = mValueAxis.data();
  18182. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  18183. result.resize(data.size()*2);
  18184. // transform data points to pixels:
  18185. if (keyAxis->orientation() == Qt::Vertical)
  18186. {
  18187. for (int i=0; i<data.size(); ++i)
  18188. {
  18189. const QCPGraphData &current = data.at(i);
  18190. if (!qIsNaN(current.value))
  18191. {
  18192. const double key = keyAxis->coordToPixel(current.key);
  18193. result[i*2+0].setX(valueAxis->coordToPixel(0));
  18194. result[i*2+0].setY(key);
  18195. result[i*2+1].setX(valueAxis->coordToPixel(current.value));
  18196. result[i*2+1].setY(key);
  18197. } else
  18198. {
  18199. result[i*2+0] = QPointF(0, 0);
  18200. result[i*2+1] = QPointF(0, 0);
  18201. }
  18202. }
  18203. } else // key axis is horizontal
  18204. {
  18205. for (int i=0; i<data.size(); ++i)
  18206. {
  18207. const QCPGraphData &current = data.at(i);
  18208. if (!qIsNaN(current.value))
  18209. {
  18210. const double key = keyAxis->coordToPixel(data.at(i).key);
  18211. result[i*2+0].setX(key);
  18212. result[i*2+0].setY(valueAxis->coordToPixel(0));
  18213. result[i*2+1].setX(key);
  18214. result[i*2+1].setY(valueAxis->coordToPixel(data.at(i).value));
  18215. } else
  18216. {
  18217. result[i*2+0] = QPointF(0, 0);
  18218. result[i*2+1] = QPointF(0, 0);
  18219. }
  18220. }
  18221. }
  18222. return result;
  18223. }
  18224. /*! \internal
  18225. Draws the fill of the graph using the specified \a painter, with the currently set brush.
  18226. Depending on whether a normal fill or a channel fill (\ref setChannelFillGraph) is needed, \ref
  18227. getFillPolygon or \ref getChannelFillPolygon are used to find the according fill polygons.
  18228. In order to handle NaN Data points correctly (the fill needs to be split into disjoint areas),
  18229. this method first determines a list of non-NaN segments with \ref getNonNanSegments, on which to
  18230. operate. In the channel fill case, \ref getOverlappingSegments is used to consolidate the non-NaN
  18231. segments of the two involved graphs, before passing the overlapping pairs to \ref
  18232. getChannelFillPolygon.
  18233. Pass the points of this graph's line as \a lines, in pixel coordinates.
  18234. \see drawLinePlot, drawImpulsePlot, drawScatterPlot
  18235. */
  18236. void QCPGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lines) const
  18237. {
  18238. if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot
  18239. if (painter->brush().style() == Qt::NoBrush || painter->brush().color().alpha() == 0) return;
  18240. applyFillAntialiasingHint(painter);
  18241. const QVector<QCPDataRange> segments = getNonNanSegments(lines, keyAxis()->orientation());
  18242. if (!mChannelFillGraph)
  18243. {
  18244. // draw base fill under graph, fill goes all the way to the zero-value-line:
  18245. foreach (QCPDataRange segment, segments)
  18246. painter->drawPolygon(getFillPolygon(lines, segment));
  18247. } else
  18248. {
  18249. // draw fill between this graph and mChannelFillGraph:
  18250. QVector<QPointF> otherLines;
  18251. mChannelFillGraph->getLines(&otherLines, QCPDataRange(0, mChannelFillGraph->dataCount()));
  18252. if (!otherLines.isEmpty())
  18253. {
  18254. QVector<QCPDataRange> otherSegments = getNonNanSegments(&otherLines, mChannelFillGraph->keyAxis()->orientation());
  18255. QVector<QPair<QCPDataRange, QCPDataRange> > segmentPairs = getOverlappingSegments(segments, lines, otherSegments, &otherLines);
  18256. for (int i=0; i<segmentPairs.size(); ++i)
  18257. painter->drawPolygon(getChannelFillPolygon(lines, segmentPairs.at(i).first, &otherLines, segmentPairs.at(i).second));
  18258. }
  18259. }
  18260. }
  18261. /*! \internal
  18262. Draws scatter symbols at every point passed in \a scatters, given in pixel coordinates. The
  18263. scatters will be drawn with \a painter and have the appearance as specified in \a style.
  18264. \see drawLinePlot, drawImpulsePlot
  18265. */
  18266. void QCPGraph::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &scatters, const QCPScatterStyle &style) const
  18267. {
  18268. applyScattersAntialiasingHint(painter);
  18269. style.applyTo(painter, mPen);
  18270. foreach (const QPointF &scatter, scatters)
  18271. style.drawShape(painter, scatter.x(), scatter.y());
  18272. }
  18273. /*! \internal
  18274. Draws lines between the points in \a lines, given in pixel coordinates.
  18275. \see drawScatterPlot, drawImpulsePlot, QCPAbstractPlottable1D::drawPolyline
  18276. */
  18277. void QCPGraph::drawLinePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
  18278. {
  18279. if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
  18280. {
  18281. applyDefaultAntialiasingHint(painter);
  18282. drawPolyline(painter, lines);
  18283. }
  18284. }
  18285. /*! \internal
  18286. Draws impulses from the provided data, i.e. it connects all line pairs in \a lines, given in
  18287. pixel coordinates. The \a lines necessary for impulses are generated by \ref dataToImpulseLines
  18288. from the regular graph data points.
  18289. \see drawLinePlot, drawScatterPlot
  18290. */
  18291. void QCPGraph::drawImpulsePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
  18292. {
  18293. if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
  18294. {
  18295. applyDefaultAntialiasingHint(painter);
  18296. QPen oldPen = painter->pen();
  18297. QPen newPen = painter->pen();
  18298. newPen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line
  18299. painter->setPen(newPen);
  18300. painter->drawLines(lines);
  18301. painter->setPen(oldPen);
  18302. }
  18303. }
  18304. /*! \internal
  18305. Returns via \a lineData the data points that need to be visualized for this graph when plotting
  18306. graph lines, taking into consideration the currently visible axis ranges and, if \ref
  18307. setAdaptiveSampling is enabled, local point densities. The considered data can be restricted
  18308. further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref
  18309. getDataSegments).
  18310. This method is used by \ref getLines to retrieve the basic working set of data.
  18311. \see getOptimizedScatterData
  18312. */
  18313. void QCPGraph::getOptimizedLineData(QVector<QCPGraphData> *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const
  18314. {
  18315. if (!lineData) return;
  18316. QCPAxis *keyAxis = mKeyAxis.data();
  18317. QCPAxis *valueAxis = mValueAxis.data();
  18318. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  18319. if (begin == end) return;
  18320. int dataCount = int(end-begin);
  18321. int maxCount = (std::numeric_limits<int>::max)();
  18322. if (mAdaptiveSampling)
  18323. {
  18324. double keyPixelSpan = qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key));
  18325. if (2*keyPixelSpan+2 < static_cast<double>((std::numeric_limits<int>::max)()))
  18326. maxCount = int(2*keyPixelSpan+2);
  18327. }
  18328. if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
  18329. {
  18330. QCPGraphDataContainer::const_iterator it = begin;
  18331. double minValue = it->value;
  18332. double maxValue = it->value;
  18333. QCPGraphDataContainer::const_iterator currentIntervalFirstPoint = it;
  18334. int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction
  18335. int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
  18336. double currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(begin->key)+reversedRound));
  18337. double lastIntervalEndKey = currentIntervalStartKey;
  18338. double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
  18339. bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
  18340. int intervalDataCount = 1;
  18341. ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect
  18342. while (it != end)
  18343. {
  18344. if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary
  18345. {
  18346. if (it->value < minValue)
  18347. minValue = it->value;
  18348. else if (it->value > maxValue)
  18349. maxValue = it->value;
  18350. ++intervalDataCount;
  18351. } else // new pixel interval started
  18352. {
  18353. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
  18354. {
  18355. if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point
  18356. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value));
  18357. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
  18358. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
  18359. 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
  18360. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.8, (it-1)->value));
  18361. } else
  18362. lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value));
  18363. lastIntervalEndKey = (it-1)->key;
  18364. minValue = it->value;
  18365. maxValue = it->value;
  18366. currentIntervalFirstPoint = it;
  18367. currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(it->key)+reversedRound));
  18368. if (keyEpsilonVariable)
  18369. keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
  18370. intervalDataCount = 1;
  18371. }
  18372. ++it;
  18373. }
  18374. // handle last interval:
  18375. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
  18376. {
  18377. if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point
  18378. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value));
  18379. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
  18380. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
  18381. } else
  18382. lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value));
  18383. } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output
  18384. {
  18385. lineData->resize(dataCount);
  18386. std::copy(begin, end, lineData->begin());
  18387. }
  18388. }
  18389. /*! \internal
  18390. Returns via \a scatterData the data points that need to be visualized for this graph when
  18391. plotting scatter points, taking into consideration the currently visible axis ranges and, if \ref
  18392. setAdaptiveSampling is enabled, local point densities. The considered data can be restricted
  18393. further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref
  18394. getDataSegments).
  18395. This method is used by \ref getScatters to retrieve the basic working set of data.
  18396. \see getOptimizedLineData
  18397. */
  18398. void QCPGraph::getOptimizedScatterData(QVector<QCPGraphData> *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const
  18399. {
  18400. if (!scatterData) return;
  18401. QCPAxis *keyAxis = mKeyAxis.data();
  18402. QCPAxis *valueAxis = mValueAxis.data();
  18403. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  18404. const int scatterModulo = mScatterSkip+1;
  18405. const bool doScatterSkip = mScatterSkip > 0;
  18406. int beginIndex = int(begin-mDataContainer->constBegin());
  18407. int endIndex = int(end-mDataContainer->constBegin());
  18408. while (doScatterSkip && begin != end && beginIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter
  18409. {
  18410. ++beginIndex;
  18411. ++begin;
  18412. }
  18413. if (begin == end) return;
  18414. int dataCount = int(end-begin);
  18415. int maxCount = (std::numeric_limits<int>::max)();
  18416. if (mAdaptiveSampling)
  18417. {
  18418. int keyPixelSpan = int(qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key)));
  18419. maxCount = 2*keyPixelSpan+2;
  18420. }
  18421. if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
  18422. {
  18423. double valueMaxRange = valueAxis->range().upper;
  18424. double valueMinRange = valueAxis->range().lower;
  18425. QCPGraphDataContainer::const_iterator it = begin;
  18426. int itIndex = int(beginIndex);
  18427. double minValue = it->value;
  18428. double maxValue = it->value;
  18429. QCPGraphDataContainer::const_iterator minValueIt = it;
  18430. QCPGraphDataContainer::const_iterator maxValueIt = it;
  18431. QCPGraphDataContainer::const_iterator currentIntervalStart = it;
  18432. int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction
  18433. int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
  18434. double currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(begin->key)+reversedRound));
  18435. double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
  18436. bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
  18437. int intervalDataCount = 1;
  18438. // advance iterator to second (non-skipped) data point because adaptive sampling works in 1 point retrospect:
  18439. if (!doScatterSkip)
  18440. ++it;
  18441. else
  18442. {
  18443. itIndex += scatterModulo;
  18444. if (itIndex < endIndex) // make sure we didn't jump over end
  18445. it += scatterModulo;
  18446. else
  18447. {
  18448. it = end;
  18449. itIndex = endIndex;
  18450. }
  18451. }
  18452. // main loop over data points:
  18453. while (it != end)
  18454. {
  18455. if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary
  18456. {
  18457. if (it->value < minValue && it->value > valueMinRange && it->value < valueMaxRange)
  18458. {
  18459. minValue = it->value;
  18460. minValueIt = it;
  18461. } else if (it->value > maxValue && it->value > valueMinRange && it->value < valueMaxRange)
  18462. {
  18463. maxValue = it->value;
  18464. maxValueIt = it;
  18465. }
  18466. ++intervalDataCount;
  18467. } else // new pixel started
  18468. {
  18469. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
  18470. {
  18471. // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
  18472. double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
  18473. int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
  18474. QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart;
  18475. int c = 0;
  18476. while (intervalIt != it)
  18477. {
  18478. if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange)
  18479. scatterData->append(*intervalIt);
  18480. ++c;
  18481. if (!doScatterSkip)
  18482. ++intervalIt;
  18483. else
  18484. intervalIt += scatterModulo; // since we know indices of "currentIntervalStart", "intervalIt" and "it" are multiples of scatterModulo, we can't accidentally jump over "it" here
  18485. }
  18486. } else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange)
  18487. scatterData->append(*currentIntervalStart);
  18488. minValue = it->value;
  18489. maxValue = it->value;
  18490. currentIntervalStart = it;
  18491. currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(it->key)+reversedRound));
  18492. if (keyEpsilonVariable)
  18493. keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
  18494. intervalDataCount = 1;
  18495. }
  18496. // advance to next data point:
  18497. if (!doScatterSkip)
  18498. ++it;
  18499. else
  18500. {
  18501. itIndex += scatterModulo;
  18502. if (itIndex < endIndex) // make sure we didn't jump over end
  18503. it += scatterModulo;
  18504. else
  18505. {
  18506. it = end;
  18507. itIndex = endIndex;
  18508. }
  18509. }
  18510. }
  18511. // handle last interval:
  18512. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
  18513. {
  18514. // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
  18515. double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
  18516. int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
  18517. QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart;
  18518. int intervalItIndex = int(intervalIt-mDataContainer->constBegin());
  18519. int c = 0;
  18520. while (intervalIt != it)
  18521. {
  18522. if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange)
  18523. scatterData->append(*intervalIt);
  18524. ++c;
  18525. if (!doScatterSkip)
  18526. ++intervalIt;
  18527. 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:
  18528. {
  18529. intervalItIndex += scatterModulo;
  18530. if (intervalItIndex < itIndex)
  18531. intervalIt += scatterModulo;
  18532. else
  18533. {
  18534. intervalIt = it;
  18535. intervalItIndex = itIndex;
  18536. }
  18537. }
  18538. }
  18539. } else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange)
  18540. scatterData->append(*currentIntervalStart);
  18541. } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output
  18542. {
  18543. QCPGraphDataContainer::const_iterator it = begin;
  18544. int itIndex = beginIndex;
  18545. scatterData->reserve(dataCount);
  18546. while (it != end)
  18547. {
  18548. scatterData->append(*it);
  18549. // advance to next data point:
  18550. if (!doScatterSkip)
  18551. ++it;
  18552. else
  18553. {
  18554. itIndex += scatterModulo;
  18555. if (itIndex < endIndex)
  18556. it += scatterModulo;
  18557. else
  18558. {
  18559. it = end;
  18560. itIndex = endIndex;
  18561. }
  18562. }
  18563. }
  18564. }
  18565. }
  18566. /*!
  18567. This method outputs the currently visible data range via \a begin and \a end. The returned range
  18568. will also never exceed \a rangeRestriction.
  18569. This method takes into account that the drawing of data lines at the axis rect border always
  18570. requires the points just outside the visible axis range. So \a begin and \a end may actually
  18571. indicate a range that contains one additional data point to the left and right of the visible
  18572. axis range.
  18573. */
  18574. void QCPGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
  18575. {
  18576. if (rangeRestriction.isEmpty())
  18577. {
  18578. end = mDataContainer->constEnd();
  18579. begin = end;
  18580. } else
  18581. {
  18582. QCPAxis *keyAxis = mKeyAxis.data();
  18583. QCPAxis *valueAxis = mValueAxis.data();
  18584. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  18585. // get visible data range:
  18586. begin = mDataContainer->findBegin(keyAxis->range().lower);
  18587. end = mDataContainer->findEnd(keyAxis->range().upper);
  18588. // limit lower/upperEnd to rangeRestriction:
  18589. mDataContainer->limitIteratorsToDataRange(begin, end, rangeRestriction); // this also ensures rangeRestriction outside data bounds doesn't break anything
  18590. }
  18591. }
  18592. /*! \internal
  18593. This method goes through the passed points in \a lineData and returns a list of the segments
  18594. which don't contain NaN data points.
  18595. \a keyOrientation defines whether the \a x or \a y member of the passed QPointF is used to check
  18596. for NaN. If \a keyOrientation is \c Qt::Horizontal, the \a y member is checked, if it is \c
  18597. Qt::Vertical, the \a x member is checked.
  18598. \see getOverlappingSegments, drawFill
  18599. */
  18600. QVector<QCPDataRange> QCPGraph::getNonNanSegments(const QVector<QPointF> *lineData, Qt::Orientation keyOrientation) const
  18601. {
  18602. QVector<QCPDataRange> result;
  18603. const int n = lineData->size();
  18604. QCPDataRange currentSegment(-1, -1);
  18605. int i = 0;
  18606. if (keyOrientation == Qt::Horizontal)
  18607. {
  18608. while (i < n)
  18609. {
  18610. while (i < n && qIsNaN(lineData->at(i).y())) // seek next non-NaN data point
  18611. ++i;
  18612. if (i == n)
  18613. break;
  18614. currentSegment.setBegin(i++);
  18615. while (i < n && !qIsNaN(lineData->at(i).y())) // seek next NaN data point or end of data
  18616. ++i;
  18617. currentSegment.setEnd(i++);
  18618. result.append(currentSegment);
  18619. }
  18620. } else // keyOrientation == Qt::Vertical
  18621. {
  18622. while (i < n)
  18623. {
  18624. while (i < n && qIsNaN(lineData->at(i).x())) // seek next non-NaN data point
  18625. ++i;
  18626. if (i == n)
  18627. break;
  18628. currentSegment.setBegin(i++);
  18629. while (i < n && !qIsNaN(lineData->at(i).x())) // seek next NaN data point or end of data
  18630. ++i;
  18631. currentSegment.setEnd(i++);
  18632. result.append(currentSegment);
  18633. }
  18634. }
  18635. return result;
  18636. }
  18637. /*! \internal
  18638. This method takes two segment lists (e.g. created by \ref getNonNanSegments) \a thisSegments and
  18639. \a otherSegments, and their associated point data \a thisData and \a otherData.
  18640. It returns all pairs of segments (the first from \a thisSegments, the second from \a
  18641. otherSegments), which overlap in plot coordinates.
  18642. This method is useful in the case of a channel fill between two graphs, when only those non-NaN
  18643. segments which actually overlap in their key coordinate shall be considered for drawing a channel
  18644. fill polygon.
  18645. It is assumed that the passed segments in \a thisSegments are ordered ascending by index, and
  18646. that the segments don't overlap themselves. The same is assumed for the segments in \a
  18647. otherSegments. This is fulfilled when the segments are obtained via \ref getNonNanSegments.
  18648. \see getNonNanSegments, segmentsIntersect, drawFill, getChannelFillPolygon
  18649. */
  18650. QVector<QPair<QCPDataRange, QCPDataRange> > QCPGraph::getOverlappingSegments(QVector<QCPDataRange> thisSegments, const QVector<QPointF> *thisData, QVector<QCPDataRange> otherSegments, const QVector<QPointF> *otherData) const
  18651. {
  18652. QVector<QPair<QCPDataRange, QCPDataRange> > result;
  18653. if (thisData->isEmpty() || otherData->isEmpty() || thisSegments.isEmpty() || otherSegments.isEmpty())
  18654. return result;
  18655. int thisIndex = 0;
  18656. int otherIndex = 0;
  18657. const bool verticalKey = mKeyAxis->orientation() == Qt::Vertical;
  18658. while (thisIndex < thisSegments.size() && otherIndex < otherSegments.size())
  18659. {
  18660. if (thisSegments.at(thisIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow
  18661. {
  18662. ++thisIndex;
  18663. continue;
  18664. }
  18665. if (otherSegments.at(otherIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow
  18666. {
  18667. ++otherIndex;
  18668. continue;
  18669. }
  18670. double thisLower, thisUpper, otherLower, otherUpper;
  18671. if (!verticalKey)
  18672. {
  18673. thisLower = thisData->at(thisSegments.at(thisIndex).begin()).x();
  18674. thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).x();
  18675. otherLower = otherData->at(otherSegments.at(otherIndex).begin()).x();
  18676. otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).x();
  18677. } else
  18678. {
  18679. thisLower = thisData->at(thisSegments.at(thisIndex).begin()).y();
  18680. thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).y();
  18681. otherLower = otherData->at(otherSegments.at(otherIndex).begin()).y();
  18682. otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).y();
  18683. }
  18684. int bPrecedence;
  18685. if (segmentsIntersect(thisLower, thisUpper, otherLower, otherUpper, bPrecedence))
  18686. result.append(QPair<QCPDataRange, QCPDataRange>(thisSegments.at(thisIndex), otherSegments.at(otherIndex)));
  18687. if (bPrecedence <= 0) // otherSegment doesn't reach as far as thisSegment, so continue with next otherSegment, keeping current thisSegment
  18688. ++otherIndex;
  18689. else // otherSegment reaches further than thisSegment, so continue with next thisSegment, keeping current otherSegment
  18690. ++thisIndex;
  18691. }
  18692. return result;
  18693. }
  18694. /*! \internal
  18695. Returns whether the segments defined by the coordinates (aLower, aUpper) and (bLower, bUpper)
  18696. have overlap.
  18697. The output parameter \a bPrecedence indicates whether the \a b segment reaches farther than the
  18698. \a a segment or not. If \a bPrecedence returns 1, segment \a b reaches the farthest to higher
  18699. coordinates (i.e. bUpper > aUpper). If it returns -1, segment \a a reaches the farthest. Only if
  18700. both segment's upper bounds are identical, 0 is returned as \a bPrecedence.
  18701. It is assumed that the lower bounds always have smaller or equal values than the upper bounds.
  18702. \see getOverlappingSegments
  18703. */
  18704. bool QCPGraph::segmentsIntersect(double aLower, double aUpper, double bLower, double bUpper, int &bPrecedence) const
  18705. {
  18706. bPrecedence = 0;
  18707. if (aLower > bUpper)
  18708. {
  18709. bPrecedence = -1;
  18710. return false;
  18711. } else if (bLower > aUpper)
  18712. {
  18713. bPrecedence = 1;
  18714. return false;
  18715. } else
  18716. {
  18717. if (aUpper > bUpper)
  18718. bPrecedence = -1;
  18719. else if (aUpper < bUpper)
  18720. bPrecedence = 1;
  18721. return true;
  18722. }
  18723. }
  18724. /*! \internal
  18725. Returns the point which closes the fill polygon on the zero-value-line parallel to the key axis.
  18726. The logarithmic axis scale case is a bit special, since the zero-value-line in pixel coordinates
  18727. is in positive or negative infinity. So this case is handled separately by just closing the fill
  18728. polygon on the axis which lies in the direction towards the zero value.
  18729. \a matchingDataPoint will provide the key (in pixels) of the returned point. Depending on whether
  18730. the key axis of this graph is horizontal or vertical, \a matchingDataPoint will provide the x or
  18731. y value of the returned point, respectively.
  18732. */
  18733. QPointF QCPGraph::getFillBasePoint(QPointF matchingDataPoint) const
  18734. {
  18735. QCPAxis *keyAxis = mKeyAxis.data();
  18736. QCPAxis *valueAxis = mValueAxis.data();
  18737. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
  18738. QPointF result;
  18739. if (valueAxis->scaleType() == QCPAxis::stLinear)
  18740. {
  18741. if (keyAxis->orientation() == Qt::Horizontal)
  18742. {
  18743. result.setX(matchingDataPoint.x());
  18744. result.setY(valueAxis->coordToPixel(0));
  18745. } else // keyAxis->orientation() == Qt::Vertical
  18746. {
  18747. result.setX(valueAxis->coordToPixel(0));
  18748. result.setY(matchingDataPoint.y());
  18749. }
  18750. } else // valueAxis->mScaleType == QCPAxis::stLogarithmic
  18751. {
  18752. // In logarithmic scaling we can't just draw to value 0 so we just fill all the way
  18753. // to the axis which is in the direction towards 0
  18754. if (keyAxis->orientation() == Qt::Vertical)
  18755. {
  18756. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
  18757. (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
  18758. result.setX(keyAxis->axisRect()->right());
  18759. else
  18760. result.setX(keyAxis->axisRect()->left());
  18761. result.setY(matchingDataPoint.y());
  18762. } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom)
  18763. {
  18764. result.setX(matchingDataPoint.x());
  18765. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
  18766. (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
  18767. result.setY(keyAxis->axisRect()->top());
  18768. else
  18769. result.setY(keyAxis->axisRect()->bottom());
  18770. }
  18771. }
  18772. return result;
  18773. }
  18774. /*! \internal
  18775. Returns the polygon needed for drawing normal fills between this graph and the key axis.
  18776. Pass the graph's data points (in pixel coordinates) as \a lineData, and specify the \a segment
  18777. which shall be used for the fill. The collection of \a lineData points described by \a segment
  18778. must not contain NaN data points (see \ref getNonNanSegments).
  18779. The returned fill polygon will be closed at the key axis (the zero-value line) for linear value
  18780. axes. For logarithmic value axes the polygon will reach just beyond the corresponding axis rect
  18781. side (see \ref getFillBasePoint).
  18782. For increased performance (due to implicit sharing), keep the returned QPolygonF const.
  18783. \see drawFill, getNonNanSegments
  18784. */
  18785. const QPolygonF QCPGraph::getFillPolygon(const QVector<QPointF> *lineData, QCPDataRange segment) const
  18786. {
  18787. if (segment.size() < 2)
  18788. return QPolygonF();
  18789. QPolygonF result(segment.size()+2);
  18790. result[0] = getFillBasePoint(lineData->at(segment.begin()));
  18791. std::copy(lineData->constBegin()+segment.begin(), lineData->constBegin()+segment.end(), result.begin()+1);
  18792. result[result.size()-1] = getFillBasePoint(lineData->at(segment.end()-1));
  18793. return result;
  18794. }
  18795. /*! \internal
  18796. Returns the polygon needed for drawing (partial) channel fills between this graph and the graph
  18797. specified by \ref setChannelFillGraph.
  18798. The data points of this graph are passed as pixel coordinates via \a thisData, the data of the
  18799. other graph as \a otherData. The returned polygon will be calculated for the specified data
  18800. segments \a thisSegment and \a otherSegment, pertaining to the respective \a thisData and \a
  18801. otherData, respectively.
  18802. The passed \a thisSegment and \a otherSegment should correspond to the segment pairs returned by
  18803. \ref getOverlappingSegments, to make sure only segments that actually have key coordinate overlap
  18804. need to be processed here.
  18805. For increased performance due to implicit sharing, keep the returned QPolygonF const.
  18806. \see drawFill, getOverlappingSegments, getNonNanSegments
  18807. */
  18808. const QPolygonF QCPGraph::getChannelFillPolygon(const QVector<QPointF> *thisData, QCPDataRange thisSegment, const QVector<QPointF> *otherData, QCPDataRange otherSegment) const
  18809. {
  18810. if (!mChannelFillGraph)
  18811. return QPolygonF();
  18812. QCPAxis *keyAxis = mKeyAxis.data();
  18813. QCPAxis *valueAxis = mValueAxis.data();
  18814. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); }
  18815. if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); }
  18816. if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation())
  18817. 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)
  18818. if (thisData->isEmpty()) return QPolygonF();
  18819. QVector<QPointF> thisSegmentData(thisSegment.size());
  18820. QVector<QPointF> otherSegmentData(otherSegment.size());
  18821. std::copy(thisData->constBegin()+thisSegment.begin(), thisData->constBegin()+thisSegment.end(), thisSegmentData.begin());
  18822. std::copy(otherData->constBegin()+otherSegment.begin(), otherData->constBegin()+otherSegment.end(), otherSegmentData.begin());
  18823. // pointers to be able to swap them, depending which data range needs cropping:
  18824. QVector<QPointF> *staticData = &thisSegmentData;
  18825. QVector<QPointF> *croppedData = &otherSegmentData;
  18826. // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType):
  18827. if (keyAxis->orientation() == Qt::Horizontal)
  18828. {
  18829. // x is key
  18830. // crop lower bound:
  18831. if (staticData->first().x() < croppedData->first().x()) // other one must be cropped
  18832. qSwap(staticData, croppedData);
  18833. const int lowBound = findIndexBelowX(croppedData, staticData->first().x());
  18834. if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
  18835. croppedData->remove(0, lowBound);
  18836. // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation:
  18837. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18838. double slope;
  18839. if (!qFuzzyCompare(croppedData->at(1).x(), croppedData->at(0).x()))
  18840. slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x());
  18841. else
  18842. slope = 0;
  18843. (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x()));
  18844. (*croppedData)[0].setX(staticData->first().x());
  18845. // crop upper bound:
  18846. if (staticData->last().x() > croppedData->last().x()) // other one must be cropped
  18847. qSwap(staticData, croppedData);
  18848. int highBound = findIndexAboveX(croppedData, staticData->last().x());
  18849. if (highBound == -1) return QPolygonF(); // key ranges have no overlap
  18850. croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
  18851. // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation:
  18852. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18853. const int li = croppedData->size()-1; // last index
  18854. if (!qFuzzyCompare(croppedData->at(li).x(), croppedData->at(li-1).x()))
  18855. slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x());
  18856. else
  18857. slope = 0;
  18858. (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x()));
  18859. (*croppedData)[li].setX(staticData->last().x());
  18860. } else // mKeyAxis->orientation() == Qt::Vertical
  18861. {
  18862. // y is key
  18863. // crop lower bound:
  18864. if (staticData->first().y() < croppedData->first().y()) // other one must be cropped
  18865. qSwap(staticData, croppedData);
  18866. int lowBound = findIndexBelowY(croppedData, staticData->first().y());
  18867. if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
  18868. croppedData->remove(0, lowBound);
  18869. // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation:
  18870. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18871. double slope;
  18872. if (!qFuzzyCompare(croppedData->at(1).y(), croppedData->at(0).y())) // avoid division by zero in step plots
  18873. slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y());
  18874. else
  18875. slope = 0;
  18876. (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y()));
  18877. (*croppedData)[0].setY(staticData->first().y());
  18878. // crop upper bound:
  18879. if (staticData->last().y() > croppedData->last().y()) // other one must be cropped
  18880. qSwap(staticData, croppedData);
  18881. int highBound = findIndexAboveY(croppedData, staticData->last().y());
  18882. if (highBound == -1) return QPolygonF(); // key ranges have no overlap
  18883. croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
  18884. // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation:
  18885. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18886. int li = croppedData->size()-1; // last index
  18887. if (!qFuzzyCompare(croppedData->at(li).y(), croppedData->at(li-1).y())) // avoid division by zero in step plots
  18888. slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y());
  18889. else
  18890. slope = 0;
  18891. (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y()));
  18892. (*croppedData)[li].setY(staticData->last().y());
  18893. }
  18894. // return joined:
  18895. for (int i=otherSegmentData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted
  18896. thisSegmentData << otherSegmentData.at(i);
  18897. return QPolygonF(thisSegmentData);
  18898. }
  18899. /*! \internal
  18900. Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in
  18901. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  18902. axis is horizontal.
  18903. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  18904. */
  18905. int QCPGraph::findIndexAboveX(const QVector<QPointF> *data, double x) const
  18906. {
  18907. for (int i=data->size()-1; i>=0; --i)
  18908. {
  18909. if (data->at(i).x() < x)
  18910. {
  18911. if (i<data->size()-1)
  18912. return i+1;
  18913. else
  18914. return data->size()-1;
  18915. }
  18916. }
  18917. return -1;
  18918. }
  18919. /*! \internal
  18920. Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in
  18921. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  18922. axis is horizontal.
  18923. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  18924. */
  18925. int QCPGraph::findIndexBelowX(const QVector<QPointF> *data, double x) const
  18926. {
  18927. for (int i=0; i<data->size(); ++i)
  18928. {
  18929. if (data->at(i).x() > x)
  18930. {
  18931. if (i>0)
  18932. return i-1;
  18933. else
  18934. return 0;
  18935. }
  18936. }
  18937. return -1;
  18938. }
  18939. /*! \internal
  18940. Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in
  18941. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  18942. axis is vertical.
  18943. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  18944. */
  18945. int QCPGraph::findIndexAboveY(const QVector<QPointF> *data, double y) const
  18946. {
  18947. for (int i=data->size()-1; i>=0; --i)
  18948. {
  18949. if (data->at(i).y() < y)
  18950. {
  18951. if (i<data->size()-1)
  18952. return i+1;
  18953. else
  18954. return data->size()-1;
  18955. }
  18956. }
  18957. return -1;
  18958. }
  18959. /*! \internal
  18960. Calculates the minimum distance in pixels the graph's representation has from the given \a
  18961. pixelPoint. This is used to determine whether the graph was clicked or not, e.g. in \ref
  18962. selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that if
  18963. the graph has a line representation, the returned distance may be smaller than the distance to
  18964. the \a closestData point, since the distance to the graph line is also taken into account.
  18965. If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape
  18966. is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns -1.0.
  18967. */
  18968. double QCPGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const
  18969. {
  18970. closestData = mDataContainer->constEnd();
  18971. if (mDataContainer->isEmpty())
  18972. return -1.0;
  18973. if (mLineStyle == lsNone && mScatterStyle.isNone())
  18974. return -1.0;
  18975. // calculate minimum distances to graph data points and find closestData iterator:
  18976. double minDistSqr = (std::numeric_limits<double>::max)();
  18977. // determine which key range comes into question, taking selection tolerance around pos into account:
  18978. double posKeyMin, posKeyMax, dummy;
  18979. pixelsToCoords(pixelPoint-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy);
  18980. pixelsToCoords(pixelPoint+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy);
  18981. if (posKeyMin > posKeyMax)
  18982. qSwap(posKeyMin, posKeyMax);
  18983. // iterate over found data points and then choose the one with the shortest distance to pos:
  18984. QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true);
  18985. QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true);
  18986. for (QCPGraphDataContainer::const_iterator it=begin; it!=end; ++it)
  18987. {
  18988. const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
  18989. if (currentDistSqr < minDistSqr)
  18990. {
  18991. minDistSqr = currentDistSqr;
  18992. closestData = it;
  18993. }
  18994. }
  18995. // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point):
  18996. if (mLineStyle != lsNone)
  18997. {
  18998. // line displayed, calculate distance to line segments:
  18999. QVector<QPointF> lineData;
  19000. 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
  19001. QCPVector2D p(pixelPoint);
  19002. const int step = mLineStyle==lsImpulse ? 2 : 1; // impulse plot differs from other line styles in that the lineData points are only pairwise connected
  19003. for (int i=0; i<lineData.size()-1; i+=step)
  19004. {
  19005. const double currentDistSqr = p.distanceSquaredToLine(lineData.at(i), lineData.at(i+1));
  19006. if (currentDistSqr < minDistSqr)
  19007. minDistSqr = currentDistSqr;
  19008. }
  19009. }
  19010. return qSqrt(minDistSqr);
  19011. }
  19012. /*! \internal
  19013. Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in
  19014. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  19015. axis is vertical.
  19016. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  19017. */
  19018. int QCPGraph::findIndexBelowY(const QVector<QPointF> *data, double y) const
  19019. {
  19020. for (int i=0; i<data->size(); ++i)
  19021. {
  19022. if (data->at(i).y() > y)
  19023. {
  19024. if (i>0)
  19025. return i-1;
  19026. else
  19027. return 0;
  19028. }
  19029. }
  19030. return -1;
  19031. }
  19032. /* end of 'src/plottables/plottable-graph.cpp' */
  19033. /* including file 'src/plottables/plottable-curve.cpp' */
  19034. /* modified 2022-11-06T12:45:56, size 63851 */
  19035. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19036. //////////////////// QCPCurveData
  19037. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19038. /*! \class QCPCurveData
  19039. \brief Holds the data of one single data point for QCPCurve.
  19040. The stored data is:
  19041. \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)
  19042. \li \a key: coordinate on the key axis of this curve point (this is the \a mainKey)
  19043. \li \a value: coordinate on the value axis of this curve point (this is the \a mainValue)
  19044. The container for storing multiple data points is \ref QCPCurveDataContainer. It is a typedef for
  19045. \ref QCPDataContainer with \ref QCPCurveData as the DataType template parameter. See the
  19046. documentation there for an explanation regarding the data type's generic methods.
  19047. \see QCPCurveDataContainer
  19048. */
  19049. /* start documentation of inline functions */
  19050. /*! \fn double QCPCurveData::sortKey() const
  19051. Returns the \a t member of this data point.
  19052. For a general explanation of what this method is good for in the context of the data container,
  19053. see the documentation of \ref QCPDataContainer.
  19054. */
  19055. /*! \fn static QCPCurveData QCPCurveData::fromSortKey(double sortKey)
  19056. Returns a data point with the specified \a sortKey (assigned to the data point's \a t member).
  19057. All other members are set to zero.
  19058. For a general explanation of what this method is good for in the context of the data container,
  19059. see the documentation of \ref QCPDataContainer.
  19060. */
  19061. /*! \fn static static bool QCPCurveData::sortKeyIsMainKey()
  19062. Since the member \a key is the data point key coordinate and the member \a t is the data ordering
  19063. parameter, this method returns false.
  19064. For a general explanation of what this method is good for in the context of the data container,
  19065. see the documentation of \ref QCPDataContainer.
  19066. */
  19067. /*! \fn double QCPCurveData::mainKey() const
  19068. Returns the \a key member of this data point.
  19069. For a general explanation of what this method is good for in the context of the data container,
  19070. see the documentation of \ref QCPDataContainer.
  19071. */
  19072. /*! \fn double QCPCurveData::mainValue() const
  19073. Returns the \a value member of this data point.
  19074. For a general explanation of what this method is good for in the context of the data container,
  19075. see the documentation of \ref QCPDataContainer.
  19076. */
  19077. /*! \fn QCPRange QCPCurveData::valueRange() const
  19078. Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
  19079. For a general explanation of what this method is good for in the context of the data container,
  19080. see the documentation of \ref QCPDataContainer.
  19081. */
  19082. /* end documentation of inline functions */
  19083. /*!
  19084. Constructs a curve data point with t, key and value set to zero.
  19085. */
  19086. QCPCurveData::QCPCurveData() :
  19087. t(0),
  19088. key(0),
  19089. value(0)
  19090. {
  19091. }
  19092. /*!
  19093. Constructs a curve data point with the specified \a t, \a key and \a value.
  19094. */
  19095. QCPCurveData::QCPCurveData(double t, double key, double value) :
  19096. t(t),
  19097. key(key),
  19098. value(value)
  19099. {
  19100. }
  19101. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19102. //////////////////// QCPCurve
  19103. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19104. /*! \class QCPCurve
  19105. \brief A plottable representing a parametric curve in a plot.
  19106. \image html QCPCurve.png
  19107. Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate,
  19108. so their visual representation can have \a loops. This is realized by introducing a third
  19109. coordinate \a t, which defines the order of the points described by the other two coordinates \a
  19110. x and \a y.
  19111. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
  19112. also access and modify the curve's data via the \ref data method, which returns a pointer to the
  19113. internal \ref QCPCurveDataContainer.
  19114. Gaps in the curve can be created by adding data points with NaN as key and value
  19115. (<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
  19116. separated.
  19117. \section qcpcurve-appearance Changing the appearance
  19118. The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush).
  19119. \section qcpcurve-usage Usage
  19120. Like all data representing objects in QCustomPlot, the QCPCurve is a plottable
  19121. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  19122. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  19123. Usually, you first create an instance:
  19124. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-1
  19125. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  19126. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  19127. The newly created plottable can be modified, e.g.:
  19128. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-2
  19129. */
  19130. /* start of documentation of inline functions */
  19131. /*! \fn QSharedPointer<QCPCurveDataContainer> QCPCurve::data() const
  19132. Returns a shared pointer to the internal data storage of type \ref QCPCurveDataContainer. You may
  19133. use it to directly manipulate the data, which may be more convenient and faster than using the
  19134. regular \ref setData or \ref addData methods.
  19135. */
  19136. /* end of documentation of inline functions */
  19137. /*!
  19138. Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  19139. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  19140. the same orientation. If either of these restrictions is violated, a corresponding message is
  19141. printed to the debug output (qDebug), the construction is not aborted, though.
  19142. The created QCPCurve is automatically registered with the QCustomPlot instance inferred from \a
  19143. keyAxis. This QCustomPlot instance takes ownership of the QCPCurve, so do not delete it manually
  19144. but use QCustomPlot::removePlottable() instead.
  19145. */
  19146. QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  19147. QCPAbstractPlottable1D<QCPCurveData>(keyAxis, valueAxis),
  19148. mScatterSkip{},
  19149. mLineStyle{}
  19150. {
  19151. // modify inherited properties from abstract plottable:
  19152. setPen(QPen(Qt::blue, 0));
  19153. setBrush(Qt::NoBrush);
  19154. setScatterStyle(QCPScatterStyle());
  19155. setLineStyle(lsLine);
  19156. setScatterSkip(0);
  19157. }
  19158. QCPCurve::~QCPCurve()
  19159. {
  19160. }
  19161. /*! \overload
  19162. Replaces the current data container with the provided \a data container.
  19163. Since a QSharedPointer is used, multiple QCPCurves may share the same data container safely.
  19164. Modifying the data in the container will then affect all curves that share the container. Sharing
  19165. can be achieved by simply exchanging the data containers wrapped in shared pointers:
  19166. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-1
  19167. If you do not wish to share containers, but create a copy from an existing container, rather use
  19168. the \ref QCPDataContainer<DataType>::set method on the curve's data container directly:
  19169. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-2
  19170. \see addData
  19171. */
  19172. void QCPCurve::setData(QSharedPointer<QCPCurveDataContainer> data)
  19173. {
  19174. mDataContainer = data;
  19175. }
  19176. /*! \overload
  19177. Replaces the current data with the provided points in \a t, \a keys and \a values. The provided
  19178. vectors should have equal length. Else, the number of added points will be the size of the
  19179. smallest vector.
  19180. If you can guarantee that the passed data points are sorted by \a t in ascending order, you can
  19181. set \a alreadySorted to true, to improve performance by saving a sorting run.
  19182. \see addData
  19183. */
  19184. void QCPCurve::setData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  19185. {
  19186. mDataContainer->clear();
  19187. addData(t, keys, values, alreadySorted);
  19188. }
  19189. /*! \overload
  19190. Replaces the current data with the provided points in \a keys and \a values. The provided vectors
  19191. should have equal length. Else, the number of added points will be the size of the smallest
  19192. vector.
  19193. The t parameter of each data point will be set to the integer index of the respective key/value
  19194. pair.
  19195. \see addData
  19196. */
  19197. void QCPCurve::setData(const QVector<double> &keys, const QVector<double> &values)
  19198. {
  19199. mDataContainer->clear();
  19200. addData(keys, values);
  19201. }
  19202. /*!
  19203. Sets the visual appearance of single data points in the plot. If set to \ref
  19204. QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate
  19205. line style).
  19206. \see QCPScatterStyle, setLineStyle
  19207. */
  19208. void QCPCurve::setScatterStyle(const QCPScatterStyle &style)
  19209. {
  19210. mScatterStyle = style;
  19211. }
  19212. /*!
  19213. If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of
  19214. scatter points are skipped/not drawn after every drawn scatter point.
  19215. This can be used to make the data appear sparser while for example still having a smooth line,
  19216. and to improve performance for very high density plots.
  19217. If \a skip is set to 0 (default), all scatter points are drawn.
  19218. \see setScatterStyle
  19219. */
  19220. void QCPCurve::setScatterSkip(int skip)
  19221. {
  19222. mScatterSkip = qMax(0, skip);
  19223. }
  19224. /*!
  19225. Sets how the single data points are connected in the plot or how they are represented visually
  19226. apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref
  19227. setScatterStyle to the desired scatter style.
  19228. \see setScatterStyle
  19229. */
  19230. void QCPCurve::setLineStyle(QCPCurve::LineStyle style)
  19231. {
  19232. mLineStyle = style;
  19233. }
  19234. /*! \overload
  19235. Adds the provided points in \a t, \a keys and \a values to the current data. The provided vectors
  19236. should have equal length. Else, the number of added points will be the size of the smallest
  19237. vector.
  19238. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  19239. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  19240. Alternatively, you can also access and modify the data directly via the \ref data method, which
  19241. returns a pointer to the internal data container.
  19242. */
  19243. void QCPCurve::addData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  19244. {
  19245. if (t.size() != keys.size() || t.size() != values.size())
  19246. qDebug() << Q_FUNC_INFO << "ts, keys and values have different sizes:" << t.size() << keys.size() << values.size();
  19247. const int n = qMin(qMin(t.size(), keys.size()), values.size());
  19248. QVector<QCPCurveData> tempData(n);
  19249. QVector<QCPCurveData>::iterator it = tempData.begin();
  19250. const QVector<QCPCurveData>::iterator itEnd = tempData.end();
  19251. int i = 0;
  19252. while (it != itEnd)
  19253. {
  19254. it->t = t[i];
  19255. it->key = keys[i];
  19256. it->value = values[i];
  19257. ++it;
  19258. ++i;
  19259. }
  19260. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  19261. }
  19262. /*! \overload
  19263. Adds the provided points in \a keys and \a values to the current data. The provided vectors
  19264. should have equal length. Else, the number of added points will be the size of the smallest
  19265. vector.
  19266. The t parameter of each data point will be set to the integer index of the respective key/value
  19267. pair.
  19268. Alternatively, you can also access and modify the data directly via the \ref data method, which
  19269. returns a pointer to the internal data container.
  19270. */
  19271. void QCPCurve::addData(const QVector<double> &keys, const QVector<double> &values)
  19272. {
  19273. if (keys.size() != values.size())
  19274. qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
  19275. const int n = qMin(keys.size(), values.size());
  19276. double tStart;
  19277. if (!mDataContainer->isEmpty())
  19278. tStart = (mDataContainer->constEnd()-1)->t + 1.0;
  19279. else
  19280. tStart = 0;
  19281. QVector<QCPCurveData> tempData(n);
  19282. QVector<QCPCurveData>::iterator it = tempData.begin();
  19283. const QVector<QCPCurveData>::iterator itEnd = tempData.end();
  19284. int i = 0;
  19285. while (it != itEnd)
  19286. {
  19287. it->t = tStart + i;
  19288. it->key = keys[i];
  19289. it->value = values[i];
  19290. ++it;
  19291. ++i;
  19292. }
  19293. mDataContainer->add(tempData, true); // don't modify tempData beyond this to prevent copy on write
  19294. }
  19295. /*! \overload
  19296. Adds the provided data point as \a t, \a key and \a value to the current data.
  19297. Alternatively, you can also access and modify the data directly via the \ref data method, which
  19298. returns a pointer to the internal data container.
  19299. */
  19300. void QCPCurve::addData(double t, double key, double value)
  19301. {
  19302. mDataContainer->add(QCPCurveData(t, key, value));
  19303. }
  19304. /*! \overload
  19305. Adds the provided data point as \a key and \a value to the current data.
  19306. The t parameter is generated automatically by increments of 1 for each point, starting at the
  19307. highest t of previously existing data or 0, if the curve data is empty.
  19308. Alternatively, you can also access and modify the data directly via the \ref data method, which
  19309. returns a pointer to the internal data container.
  19310. */
  19311. void QCPCurve::addData(double key, double value)
  19312. {
  19313. if (!mDataContainer->isEmpty())
  19314. mDataContainer->add(QCPCurveData((mDataContainer->constEnd()-1)->t + 1.0, key, value));
  19315. else
  19316. mDataContainer->add(QCPCurveData(0.0, key, value));
  19317. }
  19318. /*!
  19319. Implements a selectTest specific to this plottable's point geometry.
  19320. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  19321. point to \a pos.
  19322. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  19323. */
  19324. double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  19325. {
  19326. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  19327. return -1;
  19328. if (!mKeyAxis || !mValueAxis)
  19329. return -1;
  19330. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  19331. {
  19332. QCPCurveDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  19333. double result = pointDistance(pos, closestDataPoint);
  19334. if (details)
  19335. {
  19336. int pointIndex = int( closestDataPoint-mDataContainer->constBegin() );
  19337. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  19338. }
  19339. return result;
  19340. } else
  19341. return -1;
  19342. }
  19343. /* inherits documentation from base class */
  19344. QCPRange QCPCurve::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  19345. {
  19346. return mDataContainer->keyRange(foundRange, inSignDomain);
  19347. }
  19348. /* inherits documentation from base class */
  19349. QCPRange QCPCurve::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  19350. {
  19351. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  19352. }
  19353. /* inherits documentation from base class */
  19354. void QCPCurve::draw(QCPPainter *painter)
  19355. {
  19356. if (mDataContainer->isEmpty()) return;
  19357. // allocate line vector:
  19358. QVector<QPointF> lines, scatters;
  19359. // loop over and draw segments of unselected/selected data:
  19360. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  19361. getDataSegments(selectedSegments, unselectedSegments);
  19362. allSegments << unselectedSegments << selectedSegments;
  19363. for (int i=0; i<allSegments.size(); ++i)
  19364. {
  19365. bool isSelectedSegment = i >= unselectedSegments.size();
  19366. // fill with curve data:
  19367. QPen finalCurvePen = mPen; // determine the final pen already here, because the line optimization depends on its stroke width
  19368. if (isSelectedSegment && mSelectionDecorator)
  19369. finalCurvePen = mSelectionDecorator->pen();
  19370. 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)
  19371. getCurveLines(&lines, lineDataRange, finalCurvePen.widthF());
  19372. // check data validity if flag set:
  19373. #ifdef QCUSTOMPLOT_CHECK_DATA
  19374. for (QCPCurveDataContainer::const_iterator it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  19375. {
  19376. if (QCP::isInvalidData(it->t) ||
  19377. QCP::isInvalidData(it->key, it->value))
  19378. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
  19379. }
  19380. #endif
  19381. // draw curve fill:
  19382. applyFillAntialiasingHint(painter);
  19383. if (isSelectedSegment && mSelectionDecorator)
  19384. mSelectionDecorator->applyBrush(painter);
  19385. else
  19386. painter->setBrush(mBrush);
  19387. painter->setPen(Qt::NoPen);
  19388. if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0)
  19389. painter->drawPolygon(QPolygonF(lines));
  19390. // draw curve line:
  19391. if (mLineStyle != lsNone)
  19392. {
  19393. painter->setPen(finalCurvePen);
  19394. painter->setBrush(Qt::NoBrush);
  19395. drawCurveLine(painter, lines);
  19396. }
  19397. // draw scatters:
  19398. QCPScatterStyle finalScatterStyle = mScatterStyle;
  19399. if (isSelectedSegment && mSelectionDecorator)
  19400. finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
  19401. if (!finalScatterStyle.isNone())
  19402. {
  19403. getScatters(&scatters, allSegments.at(i), finalScatterStyle.size());
  19404. drawScatterPlot(painter, scatters, finalScatterStyle);
  19405. }
  19406. }
  19407. // draw other selection decoration that isn't just line/scatter pens and brushes:
  19408. if (mSelectionDecorator)
  19409. mSelectionDecorator->drawDecoration(painter, selection());
  19410. }
  19411. /* inherits documentation from base class */
  19412. void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  19413. {
  19414. // draw fill:
  19415. if (mBrush.style() != Qt::NoBrush)
  19416. {
  19417. applyFillAntialiasingHint(painter);
  19418. painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
  19419. }
  19420. // draw line vertically centered:
  19421. if (mLineStyle != lsNone)
  19422. {
  19423. applyDefaultAntialiasingHint(painter);
  19424. painter->setPen(mPen);
  19425. 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
  19426. }
  19427. // draw scatter symbol:
  19428. if (!mScatterStyle.isNone())
  19429. {
  19430. applyScattersAntialiasingHint(painter);
  19431. // scale scatter pixmap if it's too large to fit in legend icon rect:
  19432. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
  19433. {
  19434. QCPScatterStyle scaledStyle(mScatterStyle);
  19435. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  19436. scaledStyle.applyTo(painter, mPen);
  19437. scaledStyle.drawShape(painter, QRectF(rect).center());
  19438. } else
  19439. {
  19440. mScatterStyle.applyTo(painter, mPen);
  19441. mScatterStyle.drawShape(painter, QRectF(rect).center());
  19442. }
  19443. }
  19444. }
  19445. /*! \internal
  19446. Draws lines between the points in \a lines, given in pixel coordinates.
  19447. \see drawScatterPlot, getCurveLines
  19448. */
  19449. void QCPCurve::drawCurveLine(QCPPainter *painter, const QVector<QPointF> &lines) const
  19450. {
  19451. if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
  19452. {
  19453. applyDefaultAntialiasingHint(painter);
  19454. drawPolyline(painter, lines);
  19455. }
  19456. }
  19457. /*! \internal
  19458. Draws scatter symbols at every point passed in \a points, given in pixel coordinates. The
  19459. scatters will be drawn with \a painter and have the appearance as specified in \a style.
  19460. \see drawCurveLine, getCurveLines
  19461. */
  19462. void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &points, const QCPScatterStyle &style) const
  19463. {
  19464. // draw scatter point symbols:
  19465. applyScattersAntialiasingHint(painter);
  19466. style.applyTo(painter, mPen);
  19467. foreach (const QPointF &point, points)
  19468. if (!qIsNaN(point.x()) && !qIsNaN(point.y()))
  19469. style.drawShape(painter, point);
  19470. }
  19471. /*! \internal
  19472. Called by \ref draw to generate points in pixel coordinates which represent the line of the
  19473. curve.
  19474. Line segments that aren't visible in the current axis rect are handled in an optimized way. They
  19475. are projected onto a rectangle slightly larger than the visible axis rect and simplified
  19476. regarding point count. The algorithm makes sure to preserve appearance of lines and fills inside
  19477. the visible axis rect by generating new temporary points on the outer rect if necessary.
  19478. \a lines will be filled with points in pixel coordinates, that can be drawn with \ref
  19479. drawCurveLine.
  19480. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  19481. conversion. In this function, the specified range may exceed the total data bounds without harm:
  19482. a correspondingly trimmed data range will be used. This takes the burden off the user of this
  19483. function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
  19484. getDataSegments.
  19485. \a penWidth specifies the pen width that will be used to later draw the lines generated by this
  19486. function. This is needed here to calculate an accordingly wider margin around the axis rect when
  19487. performing the line optimization.
  19488. Methods that are also involved in the algorithm are: \ref getRegion, \ref getOptimizedPoint, \ref
  19489. getOptimizedCornerPoints \ref mayTraverse, \ref getTraverse, \ref getTraverseCornerPoints.
  19490. \see drawCurveLine, drawScatterPlot
  19491. */
  19492. void QCPCurve::getCurveLines(QVector<QPointF> *lines, const QCPDataRange &dataRange, double penWidth) const
  19493. {
  19494. if (!lines) return;
  19495. lines->clear();
  19496. QCPAxis *keyAxis = mKeyAxis.data();
  19497. QCPAxis *valueAxis = mValueAxis.data();
  19498. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  19499. // add margins to rect to compensate for stroke width
  19500. const double strokeMargin = qMax(qreal(1.0), qreal(penWidth*0.75)); // stroke radius + 50% safety
  19501. const double keyMin = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().lower)-strokeMargin*keyAxis->pixelOrientation());
  19502. const double keyMax = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().upper)+strokeMargin*keyAxis->pixelOrientation());
  19503. const double valueMin = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().lower)-strokeMargin*valueAxis->pixelOrientation());
  19504. const double valueMax = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().upper)+strokeMargin*valueAxis->pixelOrientation());
  19505. QCPCurveDataContainer::const_iterator itBegin = mDataContainer->constBegin();
  19506. QCPCurveDataContainer::const_iterator itEnd = mDataContainer->constEnd();
  19507. mDataContainer->limitIteratorsToDataRange(itBegin, itEnd, dataRange);
  19508. if (itBegin == itEnd)
  19509. return;
  19510. QCPCurveDataContainer::const_iterator it = itBegin;
  19511. QCPCurveDataContainer::const_iterator prevIt = itEnd-1;
  19512. int prevRegion = getRegion(prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin);
  19513. 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)
  19514. while (it != itEnd)
  19515. {
  19516. const int currentRegion = getRegion(it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  19517. if (currentRegion != prevRegion) // changed region, possibly need to add some optimized edge points or original points if entering R
  19518. {
  19519. if (currentRegion != 5) // segment doesn't end in R, so it's a candidate for removal
  19520. {
  19521. QPointF crossA, crossB;
  19522. if (prevRegion == 5) // we're coming from R, so add this point optimized
  19523. {
  19524. lines->append(getOptimizedPoint(currentRegion, it->key, it->value, prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin));
  19525. // 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
  19526. *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  19527. } else if (mayTraverse(prevRegion, currentRegion) &&
  19528. getTraverse(prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin, crossA, crossB))
  19529. {
  19530. // add the two cross points optimized if segment crosses R and if segment isn't virtual zeroth segment between last and first curve point:
  19531. QVector<QPointF> beforeTraverseCornerPoints, afterTraverseCornerPoints;
  19532. getTraverseCornerPoints(prevRegion, currentRegion, keyMin, valueMax, keyMax, valueMin, beforeTraverseCornerPoints, afterTraverseCornerPoints);
  19533. if (it != itBegin)
  19534. {
  19535. *lines << beforeTraverseCornerPoints;
  19536. lines->append(crossA);
  19537. lines->append(crossB);
  19538. *lines << afterTraverseCornerPoints;
  19539. } else
  19540. {
  19541. lines->append(crossB);
  19542. *lines << afterTraverseCornerPoints;
  19543. trailingPoints << beforeTraverseCornerPoints << crossA ;
  19544. }
  19545. } 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)
  19546. {
  19547. *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  19548. }
  19549. } else // segment does end in R, so we add previous point optimized and this point at original position
  19550. {
  19551. 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
  19552. trailingPoints << getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  19553. else
  19554. lines->append(getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin));
  19555. lines->append(coordsToPixels(it->key, it->value));
  19556. }
  19557. } else // region didn't change
  19558. {
  19559. if (currentRegion == 5) // still in R, keep adding original points
  19560. {
  19561. lines->append(coordsToPixels(it->key, it->value));
  19562. } else // still outside R, no need to add anything
  19563. {
  19564. // see how this is not doing anything? That's the main optimization...
  19565. }
  19566. }
  19567. prevIt = it;
  19568. prevRegion = currentRegion;
  19569. ++it;
  19570. }
  19571. *lines << trailingPoints;
  19572. }
  19573. /*! \internal
  19574. Called by \ref draw to generate points in pixel coordinates which represent the scatters of the
  19575. curve. If a scatter skip is configured (\ref setScatterSkip), the returned points are accordingly
  19576. sparser.
  19577. Scatters that aren't visible in the current axis rect are optimized away.
  19578. \a scatters will be filled with points in pixel coordinates, that can be drawn with \ref
  19579. drawScatterPlot.
  19580. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  19581. conversion.
  19582. \a scatterWidth specifies the scatter width that will be used to later draw the scatters at pixel
  19583. coordinates generated by this function. This is needed here to calculate an accordingly wider
  19584. margin around the axis rect when performing the data point reduction.
  19585. \see draw, drawScatterPlot
  19586. */
  19587. void QCPCurve::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange, double scatterWidth) const
  19588. {
  19589. if (!scatters) return;
  19590. scatters->clear();
  19591. QCPAxis *keyAxis = mKeyAxis.data();
  19592. QCPAxis *valueAxis = mValueAxis.data();
  19593. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  19594. QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin();
  19595. QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd();
  19596. mDataContainer->limitIteratorsToDataRange(begin, end, dataRange);
  19597. if (begin == end)
  19598. return;
  19599. const int scatterModulo = mScatterSkip+1;
  19600. const bool doScatterSkip = mScatterSkip > 0;
  19601. int endIndex = int( end-mDataContainer->constBegin() );
  19602. QCPRange keyRange = keyAxis->range();
  19603. QCPRange valueRange = valueAxis->range();
  19604. // extend range to include width of scatter symbols:
  19605. keyRange.lower = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.lower)-scatterWidth*keyAxis->pixelOrientation());
  19606. keyRange.upper = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.upper)+scatterWidth*keyAxis->pixelOrientation());
  19607. valueRange.lower = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.lower)-scatterWidth*valueAxis->pixelOrientation());
  19608. valueRange.upper = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.upper)+scatterWidth*valueAxis->pixelOrientation());
  19609. QCPCurveDataContainer::const_iterator it = begin;
  19610. int itIndex = int( begin-mDataContainer->constBegin() );
  19611. while (doScatterSkip && it != end && itIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter
  19612. {
  19613. ++itIndex;
  19614. ++it;
  19615. }
  19616. if (keyAxis->orientation() == Qt::Vertical)
  19617. {
  19618. while (it != end)
  19619. {
  19620. if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value))
  19621. scatters->append(QPointF(valueAxis->coordToPixel(it->value), keyAxis->coordToPixel(it->key)));
  19622. // advance iterator to next (non-skipped) data point:
  19623. if (!doScatterSkip)
  19624. ++it;
  19625. else
  19626. {
  19627. itIndex += scatterModulo;
  19628. if (itIndex < endIndex) // make sure we didn't jump over end
  19629. it += scatterModulo;
  19630. else
  19631. {
  19632. it = end;
  19633. itIndex = endIndex;
  19634. }
  19635. }
  19636. }
  19637. } else
  19638. {
  19639. while (it != end)
  19640. {
  19641. if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value))
  19642. scatters->append(QPointF(keyAxis->coordToPixel(it->key), valueAxis->coordToPixel(it->value)));
  19643. // advance iterator to next (non-skipped) data point:
  19644. if (!doScatterSkip)
  19645. ++it;
  19646. else
  19647. {
  19648. itIndex += scatterModulo;
  19649. if (itIndex < endIndex) // make sure we didn't jump over end
  19650. it += scatterModulo;
  19651. else
  19652. {
  19653. it = end;
  19654. itIndex = endIndex;
  19655. }
  19656. }
  19657. }
  19658. }
  19659. }
  19660. /*! \internal
  19661. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19662. It returns the region of the given point (\a key, \a value) with respect to a rectangle defined
  19663. by \a keyMin, \a keyMax, \a valueMin, and \a valueMax.
  19664. The regions are enumerated from top to bottom (\a valueMin to \a valueMax) and left to right (\a
  19665. keyMin to \a keyMax):
  19666. <table style="width:10em; text-align:center">
  19667. <tr><td>1</td><td>4</td><td>7</td></tr>
  19668. <tr><td>2</td><td style="border:1px solid black">5</td><td>8</td></tr>
  19669. <tr><td>3</td><td>6</td><td>9</td></tr>
  19670. </table>
  19671. With the rectangle being region 5, and the outer regions extending infinitely outwards. In the
  19672. curve optimization algorithm, region 5 is considered to be the visible portion of the plot.
  19673. */
  19674. int QCPCurve::getRegion(double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
  19675. {
  19676. if (key < keyMin) // region 123
  19677. {
  19678. if (value > valueMax)
  19679. return 1;
  19680. else if (value < valueMin)
  19681. return 3;
  19682. else
  19683. return 2;
  19684. } else if (key > keyMax) // region 789
  19685. {
  19686. if (value > valueMax)
  19687. return 7;
  19688. else if (value < valueMin)
  19689. return 9;
  19690. else
  19691. return 8;
  19692. } else // region 456
  19693. {
  19694. if (value > valueMax)
  19695. return 4;
  19696. else if (value < valueMin)
  19697. return 6;
  19698. else
  19699. return 5;
  19700. }
  19701. }
  19702. /*! \internal
  19703. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19704. This method is used in case the current segment passes from inside the visible rect (region 5,
  19705. see \ref getRegion) to any of the outer regions (\a otherRegion). The current segment is given by
  19706. the line connecting (\a key, \a value) with (\a otherKey, \a otherValue).
  19707. It returns the intersection point of the segment with the border of region 5.
  19708. For this function it doesn't matter whether (\a key, \a value) is the point inside region 5 or
  19709. whether it's (\a otherKey, \a otherValue), i.e. whether the segment is coming from region 5 or
  19710. leaving it. It is important though that \a otherRegion correctly identifies the other region not
  19711. equal to 5.
  19712. */
  19713. QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
  19714. {
  19715. // The intersection point interpolation here is done in pixel coordinates, so we don't need to
  19716. // differentiate between different axis scale types. Note that the nomenclature
  19717. // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be
  19718. // different in pixel coordinates (horz/vert key axes, reversed ranges)
  19719. const double keyMinPx = mKeyAxis->coordToPixel(keyMin);
  19720. const double keyMaxPx = mKeyAxis->coordToPixel(keyMax);
  19721. const double valueMinPx = mValueAxis->coordToPixel(valueMin);
  19722. const double valueMaxPx = mValueAxis->coordToPixel(valueMax);
  19723. const double otherValuePx = mValueAxis->coordToPixel(otherValue);
  19724. const double valuePx = mValueAxis->coordToPixel(value);
  19725. const double otherKeyPx = mKeyAxis->coordToPixel(otherKey);
  19726. const double keyPx = mKeyAxis->coordToPixel(key);
  19727. double intersectKeyPx = keyMinPx; // initial key just a fail-safe
  19728. double intersectValuePx = valueMinPx; // initial value just a fail-safe
  19729. switch (otherRegion)
  19730. {
  19731. case 1: // top and left edge
  19732. {
  19733. intersectValuePx = valueMaxPx;
  19734. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19735. 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)
  19736. {
  19737. intersectKeyPx = keyMinPx;
  19738. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19739. }
  19740. break;
  19741. }
  19742. case 2: // left edge
  19743. {
  19744. intersectKeyPx = keyMinPx;
  19745. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19746. break;
  19747. }
  19748. case 3: // bottom and left edge
  19749. {
  19750. intersectValuePx = valueMinPx;
  19751. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19752. 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)
  19753. {
  19754. intersectKeyPx = keyMinPx;
  19755. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19756. }
  19757. break;
  19758. }
  19759. case 4: // top edge
  19760. {
  19761. intersectValuePx = valueMaxPx;
  19762. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19763. break;
  19764. }
  19765. case 5:
  19766. {
  19767. break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table
  19768. }
  19769. case 6: // bottom edge
  19770. {
  19771. intersectValuePx = valueMinPx;
  19772. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19773. break;
  19774. }
  19775. case 7: // top and right edge
  19776. {
  19777. intersectValuePx = valueMaxPx;
  19778. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19779. 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)
  19780. {
  19781. intersectKeyPx = keyMaxPx;
  19782. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19783. }
  19784. break;
  19785. }
  19786. case 8: // right edge
  19787. {
  19788. intersectKeyPx = keyMaxPx;
  19789. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19790. break;
  19791. }
  19792. case 9: // bottom and right edge
  19793. {
  19794. intersectValuePx = valueMinPx;
  19795. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19796. 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)
  19797. {
  19798. intersectKeyPx = keyMaxPx;
  19799. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19800. }
  19801. break;
  19802. }
  19803. }
  19804. if (mKeyAxis->orientation() == Qt::Horizontal)
  19805. return {intersectKeyPx, intersectValuePx};
  19806. else
  19807. return {intersectValuePx, intersectKeyPx};
  19808. }
  19809. /*! \internal
  19810. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19811. In situations where a single segment skips over multiple regions it might become necessary to add
  19812. extra points at the corners of region 5 (see \ref getRegion) such that the optimized segment
  19813. doesn't unintentionally cut through the visible area of the axis rect and create plot artifacts.
  19814. This method provides these points that must be added, assuming the original segment doesn't
  19815. start, end, or traverse region 5. (Corner points where region 5 is traversed are calculated by
  19816. \ref getTraverseCornerPoints.)
  19817. For example, consider a segment which directly goes from region 4 to 2 but originally is far out
  19818. to the top left such that it doesn't cross region 5. Naively optimizing these points by
  19819. projecting them on the top and left borders of region 5 will create a segment that surely crosses
  19820. 5, creating a visual artifact in the plot. This method prevents this by providing extra points at
  19821. the top left corner, making the optimized curve correctly pass from region 4 to 1 to 2 without
  19822. traversing 5.
  19823. */
  19824. 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
  19825. {
  19826. QVector<QPointF> result;
  19827. switch (prevRegion)
  19828. {
  19829. case 1:
  19830. {
  19831. switch (currentRegion)
  19832. {
  19833. case 2: { result << coordsToPixels(keyMin, valueMax); break; }
  19834. case 4: { result << coordsToPixels(keyMin, valueMax); break; }
  19835. case 3: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); break; }
  19836. case 7: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); break; }
  19837. case 6: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19838. case 8: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19839. 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
  19840. if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R
  19841. { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); }
  19842. else
  19843. { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); }
  19844. break;
  19845. }
  19846. }
  19847. break;
  19848. }
  19849. case 2:
  19850. {
  19851. switch (currentRegion)
  19852. {
  19853. case 1: { result << coordsToPixels(keyMin, valueMax); break; }
  19854. case 3: { result << coordsToPixels(keyMin, valueMin); break; }
  19855. case 4: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19856. case 6: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19857. case 7: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; }
  19858. case 9: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; }
  19859. }
  19860. break;
  19861. }
  19862. case 3:
  19863. {
  19864. switch (currentRegion)
  19865. {
  19866. case 2: { result << coordsToPixels(keyMin, valueMin); break; }
  19867. case 6: { result << coordsToPixels(keyMin, valueMin); break; }
  19868. case 1: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); break; }
  19869. case 9: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); break; }
  19870. case 4: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19871. case 8: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19872. 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
  19873. if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R
  19874. { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); }
  19875. else
  19876. { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); }
  19877. break;
  19878. }
  19879. }
  19880. break;
  19881. }
  19882. case 4:
  19883. {
  19884. switch (currentRegion)
  19885. {
  19886. case 1: { result << coordsToPixels(keyMin, valueMax); break; }
  19887. case 7: { result << coordsToPixels(keyMax, valueMax); break; }
  19888. case 2: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19889. case 8: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19890. case 3: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; }
  19891. case 9: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; }
  19892. }
  19893. break;
  19894. }
  19895. case 5:
  19896. {
  19897. switch (currentRegion)
  19898. {
  19899. case 1: { result << coordsToPixels(keyMin, valueMax); break; }
  19900. case 7: { result << coordsToPixels(keyMax, valueMax); break; }
  19901. case 9: { result << coordsToPixels(keyMax, valueMin); break; }
  19902. case 3: { result << coordsToPixels(keyMin, valueMin); break; }
  19903. }
  19904. break;
  19905. }
  19906. case 6:
  19907. {
  19908. switch (currentRegion)
  19909. {
  19910. case 3: { result << coordsToPixels(keyMin, valueMin); break; }
  19911. case 9: { result << coordsToPixels(keyMax, valueMin); break; }
  19912. case 2: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19913. case 8: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19914. case 1: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; }
  19915. case 7: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; }
  19916. }
  19917. break;
  19918. }
  19919. case 7:
  19920. {
  19921. switch (currentRegion)
  19922. {
  19923. case 4: { result << coordsToPixels(keyMax, valueMax); break; }
  19924. case 8: { result << coordsToPixels(keyMax, valueMax); break; }
  19925. case 1: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); break; }
  19926. case 9: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); break; }
  19927. case 2: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19928. case 6: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19929. 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
  19930. if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R
  19931. { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); }
  19932. else
  19933. { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); }
  19934. break;
  19935. }
  19936. }
  19937. break;
  19938. }
  19939. case 8:
  19940. {
  19941. switch (currentRegion)
  19942. {
  19943. case 7: { result << coordsToPixels(keyMax, valueMax); break; }
  19944. case 9: { result << coordsToPixels(keyMax, valueMin); break; }
  19945. case 4: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19946. case 6: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19947. case 1: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; }
  19948. case 3: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; }
  19949. }
  19950. break;
  19951. }
  19952. case 9:
  19953. {
  19954. switch (currentRegion)
  19955. {
  19956. case 6: { result << coordsToPixels(keyMax, valueMin); break; }
  19957. case 8: { result << coordsToPixels(keyMax, valueMin); break; }
  19958. case 3: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); break; }
  19959. case 7: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); break; }
  19960. case 2: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19961. case 4: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19962. 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
  19963. if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R
  19964. { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); }
  19965. else
  19966. { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); }
  19967. break;
  19968. }
  19969. }
  19970. break;
  19971. }
  19972. }
  19973. return result;
  19974. }
  19975. /*! \internal
  19976. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19977. This method returns whether a segment going from \a prevRegion to \a currentRegion (see \ref
  19978. getRegion) may traverse the visible region 5. This function assumes that neither \a prevRegion
  19979. nor \a currentRegion is 5 itself.
  19980. If this method returns false, the segment for sure doesn't pass region 5. If it returns true, the
  19981. segment may or may not pass region 5 and a more fine-grained calculation must be used (\ref
  19982. getTraverse).
  19983. */
  19984. bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const
  19985. {
  19986. switch (prevRegion)
  19987. {
  19988. case 1:
  19989. {
  19990. switch (currentRegion)
  19991. {
  19992. case 4:
  19993. case 7:
  19994. case 2:
  19995. case 3: return false;
  19996. default: return true;
  19997. }
  19998. }
  19999. case 2:
  20000. {
  20001. switch (currentRegion)
  20002. {
  20003. case 1:
  20004. case 3: return false;
  20005. default: return true;
  20006. }
  20007. }
  20008. case 3:
  20009. {
  20010. switch (currentRegion)
  20011. {
  20012. case 1:
  20013. case 2:
  20014. case 6:
  20015. case 9: return false;
  20016. default: return true;
  20017. }
  20018. }
  20019. case 4:
  20020. {
  20021. switch (currentRegion)
  20022. {
  20023. case 1:
  20024. case 7: return false;
  20025. default: return true;
  20026. }
  20027. }
  20028. case 5: return false; // should never occur
  20029. case 6:
  20030. {
  20031. switch (currentRegion)
  20032. {
  20033. case 3:
  20034. case 9: return false;
  20035. default: return true;
  20036. }
  20037. }
  20038. case 7:
  20039. {
  20040. switch (currentRegion)
  20041. {
  20042. case 1:
  20043. case 4:
  20044. case 8:
  20045. case 9: return false;
  20046. default: return true;
  20047. }
  20048. }
  20049. case 8:
  20050. {
  20051. switch (currentRegion)
  20052. {
  20053. case 7:
  20054. case 9: return false;
  20055. default: return true;
  20056. }
  20057. }
  20058. case 9:
  20059. {
  20060. switch (currentRegion)
  20061. {
  20062. case 3:
  20063. case 6:
  20064. case 8:
  20065. case 7: return false;
  20066. default: return true;
  20067. }
  20068. }
  20069. default: return true;
  20070. }
  20071. }
  20072. /*! \internal
  20073. This function is part of the curve optimization algorithm of \ref getCurveLines.
  20074. This method assumes that the \ref mayTraverse test has returned true, so there is a chance the
  20075. segment defined by (\a prevKey, \a prevValue) and (\a key, \a value) goes through the visible
  20076. region 5.
  20077. The return value of this method indicates whether the segment actually traverses region 5 or not.
  20078. If the segment traverses 5, the output parameters \a crossA and \a crossB indicate the entry and
  20079. exit points of region 5. They will become the optimized points for that segment.
  20080. */
  20081. bool QCPCurve::getTraverse(double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin, QPointF &crossA, QPointF &crossB) const
  20082. {
  20083. // The intersection point interpolation here is done in pixel coordinates, so we don't need to
  20084. // differentiate between different axis scale types. Note that the nomenclature
  20085. // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be
  20086. // different in pixel coordinates (horz/vert key axes, reversed ranges)
  20087. QList<QPointF> intersections;
  20088. const double valueMinPx = mValueAxis->coordToPixel(valueMin);
  20089. const double valueMaxPx = mValueAxis->coordToPixel(valueMax);
  20090. const double keyMinPx = mKeyAxis->coordToPixel(keyMin);
  20091. const double keyMaxPx = mKeyAxis->coordToPixel(keyMax);
  20092. const double keyPx = mKeyAxis->coordToPixel(key);
  20093. const double valuePx = mValueAxis->coordToPixel(value);
  20094. const double prevKeyPx = mKeyAxis->coordToPixel(prevKey);
  20095. const double prevValuePx = mValueAxis->coordToPixel(prevValue);
  20096. if (qFuzzyIsNull(keyPx-prevKeyPx)) // line is parallel to value axis
  20097. {
  20098. // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here
  20099. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMinPx) : QPointF(valueMinPx, keyPx)); // direction will be taken care of at end of method
  20100. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMaxPx) : QPointF(valueMaxPx, keyPx));
  20101. } else if (qFuzzyIsNull(valuePx-prevValuePx)) // line is parallel to key axis
  20102. {
  20103. // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here
  20104. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, valuePx) : QPointF(valuePx, keyMinPx)); // direction will be taken care of at end of method
  20105. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, valuePx) : QPointF(valuePx, keyMaxPx));
  20106. } else // line is skewed
  20107. {
  20108. double gamma;
  20109. double keyPerValuePx = (keyPx-prevKeyPx)/(valuePx-prevValuePx);
  20110. // check top of rect:
  20111. gamma = prevKeyPx + (valueMaxPx-prevValuePx)*keyPerValuePx;
  20112. if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed
  20113. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMaxPx) : QPointF(valueMaxPx, gamma));
  20114. // check bottom of rect:
  20115. gamma = prevKeyPx + (valueMinPx-prevValuePx)*keyPerValuePx;
  20116. if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed
  20117. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMinPx) : QPointF(valueMinPx, gamma));
  20118. const double valuePerKeyPx = 1.0/keyPerValuePx;
  20119. // check left of rect:
  20120. gamma = prevValuePx + (keyMinPx-prevKeyPx)*valuePerKeyPx;
  20121. if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed
  20122. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, gamma) : QPointF(gamma, keyMinPx));
  20123. // check right of rect:
  20124. gamma = prevValuePx + (keyMaxPx-prevKeyPx)*valuePerKeyPx;
  20125. if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed
  20126. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, gamma) : QPointF(gamma, keyMaxPx));
  20127. }
  20128. // handle cases where found points isn't exactly 2:
  20129. if (intersections.size() > 2)
  20130. {
  20131. // line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between:
  20132. double distSqrMax = 0;
  20133. QPointF pv1, pv2;
  20134. for (int i=0; i<intersections.size()-1; ++i)
  20135. {
  20136. for (int k=i+1; k<intersections.size(); ++k)
  20137. {
  20138. QPointF distPoint = intersections.at(i)-intersections.at(k);
  20139. double distSqr = distPoint.x()*distPoint.x()+distPoint.y()+distPoint.y();
  20140. if (distSqr > distSqrMax)
  20141. {
  20142. pv1 = intersections.at(i);
  20143. pv2 = intersections.at(k);
  20144. distSqrMax = distSqr;
  20145. }
  20146. }
  20147. }
  20148. intersections = QList<QPointF>() << pv1 << pv2;
  20149. } else if (intersections.size() != 2)
  20150. {
  20151. // one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment
  20152. return false;
  20153. }
  20154. // possibly re-sort points so optimized point segment has same direction as original segment:
  20155. double xDelta = keyPx-prevKeyPx;
  20156. double yDelta = valuePx-prevValuePx;
  20157. if (mKeyAxis->orientation() != Qt::Horizontal)
  20158. qSwap(xDelta, yDelta);
  20159. 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
  20160. intersections.move(0, 1);
  20161. crossA = intersections.at(0);
  20162. crossB = intersections.at(1);
  20163. return true;
  20164. }
  20165. /*! \internal
  20166. This function is part of the curve optimization algorithm of \ref getCurveLines.
  20167. This method assumes that the \ref getTraverse test has returned true, so the segment definitely
  20168. traverses the visible region 5 when going from \a prevRegion to \a currentRegion.
  20169. In certain situations it is not sufficient to merely generate the entry and exit points of the
  20170. segment into/out of region 5, as \ref getTraverse provides. It may happen that a single segment, in
  20171. addition to traversing region 5, skips another region outside of region 5, which makes it
  20172. necessary to add an optimized corner point there (very similar to the job \ref
  20173. getOptimizedCornerPoints does for segments that are completely in outside regions and don't
  20174. traverse 5).
  20175. As an example, consider a segment going from region 1 to region 6, traversing the lower left
  20176. corner of region 5. In this configuration, the segment additionally crosses the border between
  20177. region 1 and 2 before entering region 5. This makes it necessary to add an additional point in
  20178. the top left corner, before adding the optimized traverse points. So in this case, the output
  20179. parameter \a beforeTraverse will contain the top left corner point, and \a afterTraverse will be
  20180. empty.
  20181. In some cases, such as when going from region 1 to 9, it may even be necessary to add additional
  20182. corner points before and after the traverse. Then both \a beforeTraverse and \a afterTraverse
  20183. return the respective corner points.
  20184. */
  20185. void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double keyMin, double valueMax, double keyMax, double valueMin, QVector<QPointF> &beforeTraverse, QVector<QPointF> &afterTraverse) const
  20186. {
  20187. switch (prevRegion)
  20188. {
  20189. case 1:
  20190. {
  20191. switch (currentRegion)
  20192. {
  20193. case 6: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; }
  20194. case 9: { beforeTraverse << coordsToPixels(keyMin, valueMax); afterTraverse << coordsToPixels(keyMax, valueMin); break; }
  20195. case 8: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; }
  20196. }
  20197. break;
  20198. }
  20199. case 2:
  20200. {
  20201. switch (currentRegion)
  20202. {
  20203. case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; }
  20204. case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; }
  20205. }
  20206. break;
  20207. }
  20208. case 3:
  20209. {
  20210. switch (currentRegion)
  20211. {
  20212. case 4: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; }
  20213. case 7: { beforeTraverse << coordsToPixels(keyMin, valueMin); afterTraverse << coordsToPixels(keyMax, valueMax); break; }
  20214. case 8: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; }
  20215. }
  20216. break;
  20217. }
  20218. case 4:
  20219. {
  20220. switch (currentRegion)
  20221. {
  20222. case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; }
  20223. case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; }
  20224. }
  20225. break;
  20226. }
  20227. case 5: { break; } // shouldn't happen because this method only handles full traverses
  20228. case 6:
  20229. {
  20230. switch (currentRegion)
  20231. {
  20232. case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; }
  20233. case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; }
  20234. }
  20235. break;
  20236. }
  20237. case 7:
  20238. {
  20239. switch (currentRegion)
  20240. {
  20241. case 2: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; }
  20242. case 3: { beforeTraverse << coordsToPixels(keyMax, valueMax); afterTraverse << coordsToPixels(keyMin, valueMin); break; }
  20243. case 6: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; }
  20244. }
  20245. break;
  20246. }
  20247. case 8:
  20248. {
  20249. switch (currentRegion)
  20250. {
  20251. case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; }
  20252. case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; }
  20253. }
  20254. break;
  20255. }
  20256. case 9:
  20257. {
  20258. switch (currentRegion)
  20259. {
  20260. case 2: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; }
  20261. case 1: { beforeTraverse << coordsToPixels(keyMax, valueMin); afterTraverse << coordsToPixels(keyMin, valueMax); break; }
  20262. case 4: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; }
  20263. }
  20264. break;
  20265. }
  20266. }
  20267. }
  20268. /*! \internal
  20269. Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a
  20270. pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in
  20271. \ref selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that
  20272. if the curve has a line representation, the returned distance may be smaller than the distance to
  20273. the \a closestData point, since the distance to the curve line is also taken into account.
  20274. If either the curve has no data or if the line style is \ref lsNone and the scatter style's shape
  20275. is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the curve), returns
  20276. -1.0.
  20277. */
  20278. double QCPCurve::pointDistance(const QPointF &pixelPoint, QCPCurveDataContainer::const_iterator &closestData) const
  20279. {
  20280. closestData = mDataContainer->constEnd();
  20281. if (mDataContainer->isEmpty())
  20282. return -1.0;
  20283. if (mLineStyle == lsNone && mScatterStyle.isNone())
  20284. return -1.0;
  20285. if (mDataContainer->size() == 1)
  20286. {
  20287. QPointF dataPoint = coordsToPixels(mDataContainer->constBegin()->key, mDataContainer->constBegin()->value);
  20288. closestData = mDataContainer->constBegin();
  20289. return QCPVector2D(dataPoint-pixelPoint).length();
  20290. }
  20291. // calculate minimum distances to curve data points and find closestData iterator:
  20292. double minDistSqr = (std::numeric_limits<double>::max)();
  20293. // iterate over found data points and then choose the one with the shortest distance to pos:
  20294. QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin();
  20295. QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd();
  20296. for (QCPCurveDataContainer::const_iterator it=begin; it!=end; ++it)
  20297. {
  20298. const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
  20299. if (currentDistSqr < minDistSqr)
  20300. {
  20301. minDistSqr = currentDistSqr;
  20302. closestData = it;
  20303. }
  20304. }
  20305. // calculate distance to line if there is one (if so, will probably be smaller than distance to closest data point):
  20306. if (mLineStyle != lsNone)
  20307. {
  20308. QVector<QPointF> lines;
  20309. 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
  20310. for (int i=0; i<lines.size()-1; ++i)
  20311. {
  20312. double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(lines.at(i), lines.at(i+1));
  20313. if (currentDistSqr < minDistSqr)
  20314. minDistSqr = currentDistSqr;
  20315. }
  20316. }
  20317. return qSqrt(minDistSqr);
  20318. }
  20319. /* end of 'src/plottables/plottable-curve.cpp' */
  20320. /* including file 'src/plottables/plottable-bars.cpp' */
  20321. /* modified 2022-11-06T12:45:56, size 43907 */
  20322. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20323. //////////////////// QCPBarsGroup
  20324. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20325. /*! \class QCPBarsGroup
  20326. \brief Groups multiple QCPBars together so they appear side by side
  20327. \image html QCPBarsGroup.png
  20328. When showing multiple QCPBars in one plot which have bars at identical keys, it may be desirable
  20329. to have them appearing next to each other at each key. This is what adding the respective QCPBars
  20330. plottables to a QCPBarsGroup achieves. (An alternative approach is to stack them on top of each
  20331. other, see \ref QCPBars::moveAbove.)
  20332. \section qcpbarsgroup-usage Usage
  20333. To add a QCPBars plottable to the group, create a new group and then add the respective bars
  20334. intances:
  20335. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbarsgroup-creation
  20336. Alternatively to appending to the group like shown above, you can also set the group on the
  20337. QCPBars plottable via \ref QCPBars::setBarsGroup.
  20338. The spacing between the bars can be configured via \ref setSpacingType and \ref setSpacing. The
  20339. bars in this group appear in the plot in the order they were appended. To insert a bars plottable
  20340. at a certain index position, or to reposition a bars plottable which is already in the group, use
  20341. \ref insert.
  20342. To remove specific bars from the group, use either \ref remove or call \ref
  20343. QCPBars::setBarsGroup "QCPBars::setBarsGroup(0)" on the respective bars plottable.
  20344. To clear the entire group, call \ref clear, or simply delete the group.
  20345. \section qcpbarsgroup-example Example
  20346. The image above is generated with the following code:
  20347. \snippet documentation/doc-image-generator/mainwindow.cpp qcpbarsgroup-example
  20348. */
  20349. /* start of documentation of inline functions */
  20350. /*! \fn QList<QCPBars*> QCPBarsGroup::bars() const
  20351. Returns all bars currently in this group.
  20352. \see bars(int index)
  20353. */
  20354. /*! \fn int QCPBarsGroup::size() const
  20355. Returns the number of QCPBars plottables that are part of this group.
  20356. */
  20357. /*! \fn bool QCPBarsGroup::isEmpty() const
  20358. Returns whether this bars group is empty.
  20359. \see size
  20360. */
  20361. /*! \fn bool QCPBarsGroup::contains(QCPBars *bars)
  20362. Returns whether the specified \a bars plottable is part of this group.
  20363. */
  20364. /* end of documentation of inline functions */
  20365. /*!
  20366. Constructs a new bars group for the specified QCustomPlot instance.
  20367. */
  20368. QCPBarsGroup::QCPBarsGroup(QCustomPlot *parentPlot) :
  20369. QObject(parentPlot),
  20370. mParentPlot(parentPlot),
  20371. mSpacingType(stAbsolute),
  20372. mSpacing(4)
  20373. {
  20374. }
  20375. QCPBarsGroup::~QCPBarsGroup()
  20376. {
  20377. clear();
  20378. }
  20379. /*!
  20380. Sets how the spacing between adjacent bars is interpreted. See \ref SpacingType.
  20381. The actual spacing can then be specified with \ref setSpacing.
  20382. \see setSpacing
  20383. */
  20384. void QCPBarsGroup::setSpacingType(SpacingType spacingType)
  20385. {
  20386. mSpacingType = spacingType;
  20387. }
  20388. /*!
  20389. Sets the spacing between adjacent bars. What the number passed as \a spacing actually means, is
  20390. defined by the current \ref SpacingType, which can be set with \ref setSpacingType.
  20391. \see setSpacingType
  20392. */
  20393. void QCPBarsGroup::setSpacing(double spacing)
  20394. {
  20395. mSpacing = spacing;
  20396. }
  20397. /*!
  20398. Returns the QCPBars instance with the specified \a index in this group. If no such QCPBars
  20399. exists, returns \c nullptr.
  20400. \see bars(), size
  20401. */
  20402. QCPBars *QCPBarsGroup::bars(int index) const
  20403. {
  20404. if (index >= 0 && index < mBars.size())
  20405. {
  20406. return mBars.at(index);
  20407. } else
  20408. {
  20409. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  20410. return nullptr;
  20411. }
  20412. }
  20413. /*!
  20414. Removes all QCPBars plottables from this group.
  20415. \see isEmpty
  20416. */
  20417. void QCPBarsGroup::clear()
  20418. {
  20419. const QList<QCPBars*> oldBars = mBars;
  20420. foreach (QCPBars *bars, oldBars)
  20421. bars->setBarsGroup(nullptr); // removes itself from mBars via removeBars
  20422. }
  20423. /*!
  20424. Adds the specified \a bars plottable to this group. Alternatively, you can also use \ref
  20425. QCPBars::setBarsGroup on the \a bars instance.
  20426. \see insert, remove
  20427. */
  20428. void QCPBarsGroup::append(QCPBars *bars)
  20429. {
  20430. if (!bars)
  20431. {
  20432. qDebug() << Q_FUNC_INFO << "bars is 0";
  20433. return;
  20434. }
  20435. if (!mBars.contains(bars))
  20436. bars->setBarsGroup(this);
  20437. else
  20438. qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast<quintptr>(bars);
  20439. }
  20440. /*!
  20441. Inserts the specified \a bars plottable into this group at the specified index position \a i.
  20442. This gives you full control over the ordering of the bars.
  20443. \a bars may already be part of this group. In that case, \a bars is just moved to the new index
  20444. position.
  20445. \see append, remove
  20446. */
  20447. void QCPBarsGroup::insert(int i, QCPBars *bars)
  20448. {
  20449. if (!bars)
  20450. {
  20451. qDebug() << Q_FUNC_INFO << "bars is 0";
  20452. return;
  20453. }
  20454. // first append to bars list normally:
  20455. if (!mBars.contains(bars))
  20456. bars->setBarsGroup(this);
  20457. // then move to according position:
  20458. mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size()-1));
  20459. }
  20460. /*!
  20461. Removes the specified \a bars plottable from this group.
  20462. \see contains, clear
  20463. */
  20464. void QCPBarsGroup::remove(QCPBars *bars)
  20465. {
  20466. if (!bars)
  20467. {
  20468. qDebug() << Q_FUNC_INFO << "bars is 0";
  20469. return;
  20470. }
  20471. if (mBars.contains(bars))
  20472. bars->setBarsGroup(nullptr);
  20473. else
  20474. qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast<quintptr>(bars);
  20475. }
  20476. /*! \internal
  20477. Adds the specified \a bars to the internal mBars list of bars. This method does not change the
  20478. barsGroup property on \a bars.
  20479. \see unregisterBars
  20480. */
  20481. void QCPBarsGroup::registerBars(QCPBars *bars)
  20482. {
  20483. if (!mBars.contains(bars))
  20484. mBars.append(bars);
  20485. }
  20486. /*! \internal
  20487. Removes the specified \a bars from the internal mBars list of bars. This method does not change
  20488. the barsGroup property on \a bars.
  20489. \see registerBars
  20490. */
  20491. void QCPBarsGroup::unregisterBars(QCPBars *bars)
  20492. {
  20493. mBars.removeOne(bars);
  20494. }
  20495. /*! \internal
  20496. Returns the pixel offset in the key dimension the specified \a bars plottable should have at the
  20497. given key coordinate \a keyCoord. The offset is relative to the pixel position of the key
  20498. coordinate \a keyCoord.
  20499. */
  20500. double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord)
  20501. {
  20502. // find list of all base bars in case some mBars are stacked:
  20503. QList<const QCPBars*> baseBars;
  20504. foreach (const QCPBars *b, mBars)
  20505. {
  20506. while (b->barBelow())
  20507. b = b->barBelow();
  20508. if (!baseBars.contains(b))
  20509. baseBars.append(b);
  20510. }
  20511. // find base bar this "bars" is stacked on:
  20512. const QCPBars *thisBase = bars;
  20513. while (thisBase->barBelow())
  20514. thisBase = thisBase->barBelow();
  20515. // determine key pixel offset of this base bars considering all other base bars in this barsgroup:
  20516. double result = 0;
  20517. int index = baseBars.indexOf(thisBase);
  20518. if (index >= 0)
  20519. {
  20520. if (baseBars.size() % 2 == 1 && index == (baseBars.size()-1)/2) // is center bar (int division on purpose)
  20521. {
  20522. return result;
  20523. } else
  20524. {
  20525. double lowerPixelWidth, upperPixelWidth;
  20526. int startIndex;
  20527. int dir = (index <= (baseBars.size()-1)/2) ? -1 : 1; // if bar is to lower keys of center, dir is negative
  20528. if (baseBars.size() % 2 == 0) // even number of bars
  20529. {
  20530. startIndex = baseBars.size()/2 + (dir < 0 ? -1 : 0);
  20531. result += getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing
  20532. } else // uneven number of bars
  20533. {
  20534. startIndex = (baseBars.size()-1)/2+dir;
  20535. baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  20536. result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar
  20537. result += getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing
  20538. }
  20539. for (int i = startIndex; i != index; i += dir) // add widths and spacings of bars in between center and our bars
  20540. {
  20541. baseBars.at(i)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  20542. result += qAbs(upperPixelWidth-lowerPixelWidth);
  20543. result += getPixelSpacing(baseBars.at(i), keyCoord);
  20544. }
  20545. // finally half of our bars width:
  20546. baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  20547. result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5;
  20548. // correct sign of result depending on orientation and direction of key axis:
  20549. result *= dir*thisBase->keyAxis()->pixelOrientation();
  20550. }
  20551. }
  20552. return result;
  20553. }
  20554. /*! \internal
  20555. Returns the spacing in pixels which is between this \a bars and the following one, both at the
  20556. key coordinate \a keyCoord.
  20557. \note Typically the returned value doesn't depend on \a bars or \a keyCoord. \a bars is only
  20558. needed to get access to the key axis transformation and axis rect for the modes \ref
  20559. stAxisRectRatio and \ref stPlotCoords. The \a keyCoord is only relevant for spacings given in
  20560. \ref stPlotCoords on a logarithmic axis.
  20561. */
  20562. double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord)
  20563. {
  20564. switch (mSpacingType)
  20565. {
  20566. case stAbsolute:
  20567. {
  20568. return mSpacing;
  20569. }
  20570. case stAxisRectRatio:
  20571. {
  20572. if (bars->keyAxis()->orientation() == Qt::Horizontal)
  20573. return bars->keyAxis()->axisRect()->width()*mSpacing;
  20574. else
  20575. return bars->keyAxis()->axisRect()->height()*mSpacing;
  20576. }
  20577. case stPlotCoords:
  20578. {
  20579. double keyPixel = bars->keyAxis()->coordToPixel(keyCoord);
  20580. return qAbs(bars->keyAxis()->coordToPixel(keyCoord+mSpacing)-keyPixel);
  20581. }
  20582. }
  20583. return 0;
  20584. }
  20585. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20586. //////////////////// QCPBarsData
  20587. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20588. /*! \class QCPBarsData
  20589. \brief Holds the data of one single data point (one bar) for QCPBars.
  20590. The stored data is:
  20591. \li \a key: coordinate on the key axis of this bar (this is the \a mainKey and the \a sortKey)
  20592. \li \a value: height coordinate on the value axis of this bar (this is the \a mainValue)
  20593. The container for storing multiple data points is \ref QCPBarsDataContainer. It is a typedef for
  20594. \ref QCPDataContainer with \ref QCPBarsData as the DataType template parameter. See the
  20595. documentation there for an explanation regarding the data type's generic methods.
  20596. \see QCPBarsDataContainer
  20597. */
  20598. /* start documentation of inline functions */
  20599. /*! \fn double QCPBarsData::sortKey() const
  20600. Returns the \a key member of this data point.
  20601. For a general explanation of what this method is good for in the context of the data container,
  20602. see the documentation of \ref QCPDataContainer.
  20603. */
  20604. /*! \fn static QCPBarsData QCPBarsData::fromSortKey(double sortKey)
  20605. Returns a data point with the specified \a sortKey. All other members are set to zero.
  20606. For a general explanation of what this method is good for in the context of the data container,
  20607. see the documentation of \ref QCPDataContainer.
  20608. */
  20609. /*! \fn static static bool QCPBarsData::sortKeyIsMainKey()
  20610. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  20611. this method returns true.
  20612. For a general explanation of what this method is good for in the context of the data container,
  20613. see the documentation of \ref QCPDataContainer.
  20614. */
  20615. /*! \fn double QCPBarsData::mainKey() const
  20616. Returns the \a key member of this data point.
  20617. For a general explanation of what this method is good for in the context of the data container,
  20618. see the documentation of \ref QCPDataContainer.
  20619. */
  20620. /*! \fn double QCPBarsData::mainValue() const
  20621. Returns the \a value member of this data point.
  20622. For a general explanation of what this method is good for in the context of the data container,
  20623. see the documentation of \ref QCPDataContainer.
  20624. */
  20625. /*! \fn QCPRange QCPBarsData::valueRange() const
  20626. Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
  20627. For a general explanation of what this method is good for in the context of the data container,
  20628. see the documentation of \ref QCPDataContainer.
  20629. */
  20630. /* end documentation of inline functions */
  20631. /*!
  20632. Constructs a bar data point with key and value set to zero.
  20633. */
  20634. QCPBarsData::QCPBarsData() :
  20635. key(0),
  20636. value(0)
  20637. {
  20638. }
  20639. /*!
  20640. Constructs a bar data point with the specified \a key and \a value.
  20641. */
  20642. QCPBarsData::QCPBarsData(double key, double value) :
  20643. key(key),
  20644. value(value)
  20645. {
  20646. }
  20647. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20648. //////////////////// QCPBars
  20649. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20650. /*! \class QCPBars
  20651. \brief A plottable representing a bar chart in a plot.
  20652. \image html QCPBars.png
  20653. To plot data, assign it with the \ref setData or \ref addData functions.
  20654. \section qcpbars-appearance Changing the appearance
  20655. The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush).
  20656. The width of the individual bars can be controlled with \ref setWidthType and \ref setWidth.
  20657. Bar charts are stackable. This means, two QCPBars plottables can be placed on top of each other
  20658. (see \ref QCPBars::moveAbove). So when two bars are at the same key position, they will appear
  20659. stacked.
  20660. If you would like to group multiple QCPBars plottables together so they appear side by side as
  20661. shown below, use QCPBarsGroup.
  20662. \image html QCPBarsGroup.png
  20663. \section qcpbars-usage Usage
  20664. Like all data representing objects in QCustomPlot, the QCPBars is a plottable
  20665. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  20666. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  20667. Usually, you first create an instance:
  20668. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-1
  20669. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  20670. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  20671. The newly created plottable can be modified, e.g.:
  20672. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-2
  20673. */
  20674. /* start of documentation of inline functions */
  20675. /*! \fn QSharedPointer<QCPBarsDataContainer> QCPBars::data() const
  20676. Returns a shared pointer to the internal data storage of type \ref QCPBarsDataContainer. You may
  20677. use it to directly manipulate the data, which may be more convenient and faster than using the
  20678. regular \ref setData or \ref addData methods.
  20679. */
  20680. /*! \fn QCPBars *QCPBars::barBelow() const
  20681. Returns the bars plottable that is directly below this bars plottable.
  20682. If there is no such plottable, returns \c nullptr.
  20683. \see barAbove, moveBelow, moveAbove
  20684. */
  20685. /*! \fn QCPBars *QCPBars::barAbove() const
  20686. Returns the bars plottable that is directly above this bars plottable.
  20687. If there is no such plottable, returns \c nullptr.
  20688. \see barBelow, moveBelow, moveAbove
  20689. */
  20690. /* end of documentation of inline functions */
  20691. /*!
  20692. Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  20693. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  20694. the same orientation. If either of these restrictions is violated, a corresponding message is
  20695. printed to the debug output (qDebug), the construction is not aborted, though.
  20696. The created QCPBars is automatically registered with the QCustomPlot instance inferred from \a
  20697. keyAxis. This QCustomPlot instance takes ownership of the QCPBars, so do not delete it manually
  20698. but use QCustomPlot::removePlottable() instead.
  20699. */
  20700. QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  20701. QCPAbstractPlottable1D<QCPBarsData>(keyAxis, valueAxis),
  20702. mWidth(0.75),
  20703. mWidthType(wtPlotCoords),
  20704. mBarsGroup(nullptr),
  20705. mBaseValue(0),
  20706. mStackingGap(1)
  20707. {
  20708. // modify inherited properties from abstract plottable:
  20709. mPen.setColor(Qt::blue);
  20710. mPen.setStyle(Qt::SolidLine);
  20711. mBrush.setColor(QColor(40, 50, 255, 30));
  20712. mBrush.setStyle(Qt::SolidPattern);
  20713. mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255)));
  20714. }
  20715. QCPBars::~QCPBars()
  20716. {
  20717. setBarsGroup(nullptr);
  20718. if (mBarBelow || mBarAbove)
  20719. connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking
  20720. }
  20721. /*! \overload
  20722. Replaces the current data container with the provided \a data container.
  20723. Since a QSharedPointer is used, multiple QCPBars may share the same data container safely.
  20724. Modifying the data in the container will then affect all bars that share the container. Sharing
  20725. can be achieved by simply exchanging the data containers wrapped in shared pointers:
  20726. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-datasharing-1
  20727. If you do not wish to share containers, but create a copy from an existing container, rather use
  20728. the \ref QCPDataContainer<DataType>::set method on the bar's data container directly:
  20729. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-datasharing-2
  20730. \see addData
  20731. */
  20732. void QCPBars::setData(QSharedPointer<QCPBarsDataContainer> data)
  20733. {
  20734. mDataContainer = data;
  20735. }
  20736. /*! \overload
  20737. Replaces the current data with the provided points in \a keys and \a values. The provided
  20738. vectors should have equal length. Else, the number of added points will be the size of the
  20739. smallest vector.
  20740. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  20741. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  20742. \see addData
  20743. */
  20744. void QCPBars::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  20745. {
  20746. mDataContainer->clear();
  20747. addData(keys, values, alreadySorted);
  20748. }
  20749. /*!
  20750. Sets the width of the bars.
  20751. How the number passed as \a width is interpreted (e.g. screen pixels, plot coordinates,...),
  20752. depends on the currently set width type, see \ref setWidthType and \ref WidthType.
  20753. */
  20754. void QCPBars::setWidth(double width)
  20755. {
  20756. mWidth = width;
  20757. }
  20758. /*!
  20759. Sets how the width of the bars is defined. See the documentation of \ref WidthType for an
  20760. explanation of the possible values for \a widthType.
  20761. The default value is \ref wtPlotCoords.
  20762. \see setWidth
  20763. */
  20764. void QCPBars::setWidthType(QCPBars::WidthType widthType)
  20765. {
  20766. mWidthType = widthType;
  20767. }
  20768. /*!
  20769. Sets to which QCPBarsGroup this QCPBars instance belongs to. Alternatively, you can also use \ref
  20770. QCPBarsGroup::append.
  20771. To remove this QCPBars from any group, set \a barsGroup to \c nullptr.
  20772. */
  20773. void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup)
  20774. {
  20775. // deregister at old group:
  20776. if (mBarsGroup)
  20777. mBarsGroup->unregisterBars(this);
  20778. mBarsGroup = barsGroup;
  20779. // register at new group:
  20780. if (mBarsGroup)
  20781. mBarsGroup->registerBars(this);
  20782. }
  20783. /*!
  20784. Sets the base value of this bars plottable.
  20785. The base value defines where on the value coordinate the bars start. How far the bars extend from
  20786. the base value is given by their individual value data. For example, if the base value is set to
  20787. 1, a bar with data value 2 will have its lowest point at value coordinate 1 and highest point at
  20788. 3.
  20789. For stacked bars, only the base value of the bottom-most QCPBars has meaning.
  20790. The default base value is 0.
  20791. */
  20792. void QCPBars::setBaseValue(double baseValue)
  20793. {
  20794. mBaseValue = baseValue;
  20795. }
  20796. /*!
  20797. If this bars plottable is stacked on top of another bars plottable (\ref moveAbove), this method
  20798. allows specifying a distance in \a pixels, by which the drawn bar rectangles will be separated by
  20799. the bars below it.
  20800. */
  20801. void QCPBars::setStackingGap(double pixels)
  20802. {
  20803. mStackingGap = pixels;
  20804. }
  20805. /*! \overload
  20806. Adds the provided points in \a keys and \a values to the current data. The provided vectors
  20807. should have equal length. Else, the number of added points will be the size of the smallest
  20808. vector.
  20809. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  20810. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  20811. Alternatively, you can also access and modify the data directly via the \ref data method, which
  20812. returns a pointer to the internal data container.
  20813. */
  20814. void QCPBars::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  20815. {
  20816. if (keys.size() != values.size())
  20817. qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
  20818. const int n = qMin(keys.size(), values.size());
  20819. QVector<QCPBarsData> tempData(n);
  20820. QVector<QCPBarsData>::iterator it = tempData.begin();
  20821. const QVector<QCPBarsData>::iterator itEnd = tempData.end();
  20822. int i = 0;
  20823. while (it != itEnd)
  20824. {
  20825. it->key = keys[i];
  20826. it->value = values[i];
  20827. ++it;
  20828. ++i;
  20829. }
  20830. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  20831. }
  20832. /*! \overload
  20833. Adds the provided data point as \a key and \a value to the current data.
  20834. Alternatively, you can also access and modify the data directly via the \ref data method, which
  20835. returns a pointer to the internal data container.
  20836. */
  20837. void QCPBars::addData(double key, double value)
  20838. {
  20839. mDataContainer->add(QCPBarsData(key, value));
  20840. }
  20841. /*!
  20842. Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear
  20843. below the bars of \a bars. The move target \a bars must use the same key and value axis as this
  20844. plottable.
  20845. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
  20846. has a bars object below itself, this bars object is inserted between the two. If this bars object
  20847. is already between two other bars, the two other bars will be stacked on top of each other after
  20848. the operation.
  20849. To remove this bars plottable from any stacking, set \a bars to \c nullptr.
  20850. \see moveBelow, barAbove, barBelow
  20851. */
  20852. void QCPBars::moveBelow(QCPBars *bars)
  20853. {
  20854. if (bars == this) return;
  20855. if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
  20856. {
  20857. qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
  20858. return;
  20859. }
  20860. // remove from stacking:
  20861. connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
  20862. // if new bar given, insert this bar below it:
  20863. if (bars)
  20864. {
  20865. if (bars->mBarBelow)
  20866. connectBars(bars->mBarBelow.data(), this);
  20867. connectBars(this, bars);
  20868. }
  20869. }
  20870. /*!
  20871. Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear
  20872. above the bars of \a bars. The move target \a bars must use the same key and value axis as this
  20873. plottable.
  20874. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
  20875. has a bars object above itself, this bars object is inserted between the two. If this bars object
  20876. is already between two other bars, the two other bars will be stacked on top of each other after
  20877. the operation.
  20878. To remove this bars plottable from any stacking, set \a bars to \c nullptr.
  20879. \see moveBelow, barBelow, barAbove
  20880. */
  20881. void QCPBars::moveAbove(QCPBars *bars)
  20882. {
  20883. if (bars == this) return;
  20884. if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
  20885. {
  20886. qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
  20887. return;
  20888. }
  20889. // remove from stacking:
  20890. connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
  20891. // if new bar given, insert this bar above it:
  20892. if (bars)
  20893. {
  20894. if (bars->mBarAbove)
  20895. connectBars(this, bars->mBarAbove.data());
  20896. connectBars(bars, this);
  20897. }
  20898. }
  20899. /*!
  20900. \copydoc QCPPlottableInterface1D::selectTestRect
  20901. */
  20902. QCPDataSelection QCPBars::selectTestRect(const QRectF &rect, bool onlySelectable) const
  20903. {
  20904. QCPDataSelection result;
  20905. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  20906. return result;
  20907. if (!mKeyAxis || !mValueAxis)
  20908. return result;
  20909. QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  20910. getVisibleDataBounds(visibleBegin, visibleEnd);
  20911. for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  20912. {
  20913. if (rect.intersects(getBarRect(it->key, it->value)))
  20914. result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
  20915. }
  20916. result.simplify();
  20917. return result;
  20918. }
  20919. /*!
  20920. Implements a selectTest specific to this plottable's point geometry.
  20921. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  20922. point to \a pos.
  20923. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  20924. */
  20925. double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  20926. {
  20927. Q_UNUSED(details)
  20928. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  20929. return -1;
  20930. if (!mKeyAxis || !mValueAxis)
  20931. return -1;
  20932. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  20933. {
  20934. // get visible data range:
  20935. QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  20936. getVisibleDataBounds(visibleBegin, visibleEnd);
  20937. for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  20938. {
  20939. if (getBarRect(it->key, it->value).contains(pos))
  20940. {
  20941. if (details)
  20942. {
  20943. int pointIndex = int(it-mDataContainer->constBegin());
  20944. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  20945. }
  20946. return mParentPlot->selectionTolerance()*0.99;
  20947. }
  20948. }
  20949. }
  20950. return -1;
  20951. }
  20952. /* inherits documentation from base class */
  20953. QCPRange QCPBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  20954. {
  20955. /* Note: If this QCPBars uses absolute pixels as width (or is in a QCPBarsGroup with spacing in
  20956. absolute pixels), using this method to adapt the key axis range to fit the bars into the
  20957. currently visible axis range will not work perfectly. Because in the moment the axis range is
  20958. changed to the new range, the fixed pixel widths/spacings will represent different coordinate
  20959. spans than before, which in turn would require a different key range to perfectly fit, and so on.
  20960. The only solution would be to iteratively approach the perfect fitting axis range, but the
  20961. mismatch isn't large enough in most applications, to warrant this here. If a user does need a
  20962. better fit, he should call the corresponding axis rescale multiple times in a row.
  20963. */
  20964. QCPRange range;
  20965. range = mDataContainer->keyRange(foundRange, inSignDomain);
  20966. // determine exact range of bars by including bar width and barsgroup offset:
  20967. if (foundRange && mKeyAxis)
  20968. {
  20969. double lowerPixelWidth, upperPixelWidth, keyPixel;
  20970. // lower range bound:
  20971. getPixelWidth(range.lower, lowerPixelWidth, upperPixelWidth);
  20972. keyPixel = mKeyAxis.data()->coordToPixel(range.lower) + lowerPixelWidth;
  20973. if (mBarsGroup)
  20974. keyPixel += mBarsGroup->keyPixelOffset(this, range.lower);
  20975. const double lowerCorrected = mKeyAxis.data()->pixelToCoord(keyPixel);
  20976. if (!qIsNaN(lowerCorrected) && qIsFinite(lowerCorrected) && range.lower > lowerCorrected)
  20977. range.lower = lowerCorrected;
  20978. // upper range bound:
  20979. getPixelWidth(range.upper, lowerPixelWidth, upperPixelWidth);
  20980. keyPixel = mKeyAxis.data()->coordToPixel(range.upper) + upperPixelWidth;
  20981. if (mBarsGroup)
  20982. keyPixel += mBarsGroup->keyPixelOffset(this, range.upper);
  20983. const double upperCorrected = mKeyAxis.data()->pixelToCoord(keyPixel);
  20984. if (!qIsNaN(upperCorrected) && qIsFinite(upperCorrected) && range.upper < upperCorrected)
  20985. range.upper = upperCorrected;
  20986. }
  20987. return range;
  20988. }
  20989. /* inherits documentation from base class */
  20990. QCPRange QCPBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  20991. {
  20992. // Note: can't simply use mDataContainer->valueRange here because we need to
  20993. // take into account bar base value and possible stacking of multiple bars
  20994. QCPRange range;
  20995. range.lower = mBaseValue;
  20996. range.upper = mBaseValue;
  20997. bool haveLower = true; // set to true, because baseValue should always be visible in bar charts
  20998. bool haveUpper = true; // set to true, because baseValue should always be visible in bar charts
  20999. QCPBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin();
  21000. QCPBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd();
  21001. if (inKeyRange != QCPRange())
  21002. {
  21003. itBegin = mDataContainer->findBegin(inKeyRange.lower, false);
  21004. itEnd = mDataContainer->findEnd(inKeyRange.upper, false);
  21005. }
  21006. for (QCPBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it)
  21007. {
  21008. const double current = it->value + getStackedBaseValue(it->key, it->value >= 0);
  21009. if (qIsNaN(current)) continue;
  21010. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  21011. {
  21012. if (current < range.lower || !haveLower)
  21013. {
  21014. range.lower = current;
  21015. haveLower = true;
  21016. }
  21017. if (current > range.upper || !haveUpper)
  21018. {
  21019. range.upper = current;
  21020. haveUpper = true;
  21021. }
  21022. }
  21023. }
  21024. foundRange = true; // return true because bar charts always have the 0-line visible
  21025. return range;
  21026. }
  21027. /* inherits documentation from base class */
  21028. QPointF QCPBars::dataPixelPosition(int index) const
  21029. {
  21030. if (index >= 0 && index < mDataContainer->size())
  21031. {
  21032. QCPAxis *keyAxis = mKeyAxis.data();
  21033. QCPAxis *valueAxis = mValueAxis.data();
  21034. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
  21035. const QCPDataContainer<QCPBarsData>::const_iterator it = mDataContainer->constBegin()+index;
  21036. const double valuePixel = valueAxis->coordToPixel(getStackedBaseValue(it->key, it->value >= 0) + it->value);
  21037. const double keyPixel = keyAxis->coordToPixel(it->key) + (mBarsGroup ? mBarsGroup->keyPixelOffset(this, it->key) : 0);
  21038. if (keyAxis->orientation() == Qt::Horizontal)
  21039. return {keyPixel, valuePixel};
  21040. else
  21041. return {valuePixel, keyPixel};
  21042. } else
  21043. {
  21044. qDebug() << Q_FUNC_INFO << "Index out of bounds" << index;
  21045. return {};
  21046. }
  21047. }
  21048. /* inherits documentation from base class */
  21049. void QCPBars::draw(QCPPainter *painter)
  21050. {
  21051. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  21052. if (mDataContainer->isEmpty()) return;
  21053. QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  21054. getVisibleDataBounds(visibleBegin, visibleEnd);
  21055. // loop over and draw segments of unselected/selected data:
  21056. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  21057. getDataSegments(selectedSegments, unselectedSegments);
  21058. allSegments << unselectedSegments << selectedSegments;
  21059. for (int i=0; i<allSegments.size(); ++i)
  21060. {
  21061. bool isSelectedSegment = i >= unselectedSegments.size();
  21062. QCPBarsDataContainer::const_iterator begin = visibleBegin;
  21063. QCPBarsDataContainer::const_iterator end = visibleEnd;
  21064. mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
  21065. if (begin == end)
  21066. continue;
  21067. for (QCPBarsDataContainer::const_iterator it=begin; it!=end; ++it)
  21068. {
  21069. // check data validity if flag set:
  21070. #ifdef QCUSTOMPLOT_CHECK_DATA
  21071. if (QCP::isInvalidData(it->key, it->value))
  21072. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range invalid." << "Plottable name:" << name();
  21073. #endif
  21074. // draw bar:
  21075. if (isSelectedSegment && mSelectionDecorator)
  21076. {
  21077. mSelectionDecorator->applyBrush(painter);
  21078. mSelectionDecorator->applyPen(painter);
  21079. } else
  21080. {
  21081. painter->setBrush(mBrush);
  21082. painter->setPen(mPen);
  21083. }
  21084. applyDefaultAntialiasingHint(painter);
  21085. painter->drawPolygon(getBarRect(it->key, it->value));
  21086. }
  21087. }
  21088. // draw other selection decoration that isn't just line/scatter pens and brushes:
  21089. if (mSelectionDecorator)
  21090. mSelectionDecorator->drawDecoration(painter, selection());
  21091. }
  21092. /* inherits documentation from base class */
  21093. void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  21094. {
  21095. // draw filled rect:
  21096. applyDefaultAntialiasingHint(painter);
  21097. painter->setBrush(mBrush);
  21098. painter->setPen(mPen);
  21099. QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
  21100. r.moveCenter(rect.center());
  21101. painter->drawRect(r);
  21102. }
  21103. /*! \internal
  21104. called by \ref draw to determine which data (key) range is visible at the current key axis range
  21105. setting, so only that needs to be processed. It also takes into account the bar width.
  21106. \a begin returns an iterator to the lowest data point that needs to be taken into account when
  21107. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  21108. lower may still be just outside the visible range.
  21109. \a end returns an iterator one higher than the highest visible data point. Same as before, \a end
  21110. may also lie just outside of the visible range.
  21111. if the plottable contains no data, both \a begin and \a end point to constEnd.
  21112. */
  21113. void QCPBars::getVisibleDataBounds(QCPBarsDataContainer::const_iterator &begin, QCPBarsDataContainer::const_iterator &end) const
  21114. {
  21115. if (!mKeyAxis)
  21116. {
  21117. qDebug() << Q_FUNC_INFO << "invalid key axis";
  21118. begin = mDataContainer->constEnd();
  21119. end = mDataContainer->constEnd();
  21120. return;
  21121. }
  21122. if (mDataContainer->isEmpty())
  21123. {
  21124. begin = mDataContainer->constEnd();
  21125. end = mDataContainer->constEnd();
  21126. return;
  21127. }
  21128. // get visible data range as QMap iterators
  21129. begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower);
  21130. end = mDataContainer->findEnd(mKeyAxis.data()->range().upper);
  21131. double lowerPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().lower);
  21132. double upperPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().upper);
  21133. bool isVisible = false;
  21134. // walk left from begin to find lower bar that actually is completely outside visible pixel range:
  21135. QCPBarsDataContainer::const_iterator it = begin;
  21136. while (it != mDataContainer->constBegin())
  21137. {
  21138. --it;
  21139. const QRectF barRect = getBarRect(it->key, it->value);
  21140. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  21141. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.left() <= lowerPixelBound));
  21142. else // keyaxis is vertical
  21143. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.bottom() >= lowerPixelBound));
  21144. if (isVisible)
  21145. begin = it;
  21146. else
  21147. break;
  21148. }
  21149. // walk right from ubound to find upper bar that actually is completely outside visible pixel range:
  21150. it = end;
  21151. while (it != mDataContainer->constEnd())
  21152. {
  21153. const QRectF barRect = getBarRect(it->key, it->value);
  21154. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  21155. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.right() >= upperPixelBound));
  21156. else // keyaxis is vertical
  21157. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.top() <= upperPixelBound));
  21158. if (isVisible)
  21159. end = it+1;
  21160. else
  21161. break;
  21162. ++it;
  21163. }
  21164. }
  21165. /*! \internal
  21166. Returns the rect in pixel coordinates of a single bar with the specified \a key and \a value. The
  21167. rect is shifted according to the bar stacking (see \ref moveAbove) and base value (see \ref
  21168. setBaseValue), and to have non-overlapping border lines with the bars stacked below.
  21169. */
  21170. QRectF QCPBars::getBarRect(double key, double value) const
  21171. {
  21172. QCPAxis *keyAxis = mKeyAxis.data();
  21173. QCPAxis *valueAxis = mValueAxis.data();
  21174. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
  21175. double lowerPixelWidth, upperPixelWidth;
  21176. getPixelWidth(key, lowerPixelWidth, upperPixelWidth);
  21177. double base = getStackedBaseValue(key, value >= 0);
  21178. double basePixel = valueAxis->coordToPixel(base);
  21179. double valuePixel = valueAxis->coordToPixel(base+value);
  21180. double keyPixel = keyAxis->coordToPixel(key);
  21181. if (mBarsGroup)
  21182. keyPixel += mBarsGroup->keyPixelOffset(this, key);
  21183. double bottomOffset = (mBarBelow && mPen != Qt::NoPen ? 1 : 0)*(mPen.isCosmetic() ? 1 : mPen.widthF());
  21184. bottomOffset += mBarBelow ? mStackingGap : 0;
  21185. bottomOffset *= (value<0 ? -1 : 1)*valueAxis->pixelOrientation();
  21186. if (qAbs(valuePixel-basePixel) <= qAbs(bottomOffset))
  21187. bottomOffset = valuePixel-basePixel;
  21188. if (keyAxis->orientation() == Qt::Horizontal)
  21189. {
  21190. return QRectF(QPointF(keyPixel+lowerPixelWidth, valuePixel), QPointF(keyPixel+upperPixelWidth, basePixel+bottomOffset)).normalized();
  21191. } else
  21192. {
  21193. return QRectF(QPointF(basePixel+bottomOffset, keyPixel+lowerPixelWidth), QPointF(valuePixel, keyPixel+upperPixelWidth)).normalized();
  21194. }
  21195. }
  21196. /*! \internal
  21197. This function is used to determine the width of the bar at coordinate \a key, according to the
  21198. specified width (\ref setWidth) and width type (\ref setWidthType).
  21199. The output parameters \a lower and \a upper return the number of pixels the bar extends to lower
  21200. and higher keys, relative to the \a key coordinate (so with a non-reversed horizontal axis, \a
  21201. lower is negative and \a upper positive).
  21202. */
  21203. void QCPBars::getPixelWidth(double key, double &lower, double &upper) const
  21204. {
  21205. lower = 0;
  21206. upper = 0;
  21207. switch (mWidthType)
  21208. {
  21209. case wtAbsolute:
  21210. {
  21211. upper = mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  21212. lower = -upper;
  21213. break;
  21214. }
  21215. case wtAxisRectRatio:
  21216. {
  21217. if (mKeyAxis && mKeyAxis.data()->axisRect())
  21218. {
  21219. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  21220. upper = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  21221. else
  21222. upper = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  21223. lower = -upper;
  21224. } else
  21225. qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined";
  21226. break;
  21227. }
  21228. case wtPlotCoords:
  21229. {
  21230. if (mKeyAxis)
  21231. {
  21232. double keyPixel = mKeyAxis.data()->coordToPixel(key);
  21233. upper = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel;
  21234. lower = mKeyAxis.data()->coordToPixel(key-mWidth*0.5)-keyPixel;
  21235. // no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by
  21236. // coordinate transform which includes range direction
  21237. } else
  21238. qDebug() << Q_FUNC_INFO << "No key axis defined";
  21239. break;
  21240. }
  21241. }
  21242. }
  21243. /*! \internal
  21244. This function is called to find at which value to start drawing the base of a bar at \a key, when
  21245. it is stacked on top of another QCPBars (e.g. with \ref moveAbove).
  21246. positive and negative bars are separated per stack (positive are stacked above baseValue upwards,
  21247. negative are stacked below baseValue downwards). This can be indicated with \a positive. So if the
  21248. bar for which we need the base value is negative, set \a positive to false.
  21249. */
  21250. double QCPBars::getStackedBaseValue(double key, bool positive) const
  21251. {
  21252. if (mBarBelow)
  21253. {
  21254. double max = 0; // don't initialize with mBaseValue here because only base value of bottom-most bar has meaning in a bar stack
  21255. // find bars of mBarBelow that are approximately at key and find largest one:
  21256. double epsilon = qAbs(key)*(sizeof(key)==4 ? 1e-6 : 1e-14); // should be safe even when changed to use float at some point
  21257. if (key == 0)
  21258. epsilon = (sizeof(key)==4 ? 1e-6 : 1e-14);
  21259. QCPBarsDataContainer::const_iterator it = mBarBelow.data()->mDataContainer->findBegin(key-epsilon);
  21260. QCPBarsDataContainer::const_iterator itEnd = mBarBelow.data()->mDataContainer->findEnd(key+epsilon);
  21261. while (it != itEnd)
  21262. {
  21263. if (it->key > key-epsilon && it->key < key+epsilon)
  21264. {
  21265. if ((positive && it->value > max) ||
  21266. (!positive && it->value < max))
  21267. max = it->value;
  21268. }
  21269. ++it;
  21270. }
  21271. // recurse down the bar-stack to find the total height:
  21272. return max + mBarBelow.data()->getStackedBaseValue(key, positive);
  21273. } else
  21274. return mBaseValue;
  21275. }
  21276. /*! \internal
  21277. Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s)
  21278. currently above lower and below upper will become disconnected to lower/upper.
  21279. If lower is zero, upper will be disconnected at the bottom.
  21280. If upper is zero, lower will be disconnected at the top.
  21281. */
  21282. void QCPBars::connectBars(QCPBars *lower, QCPBars *upper)
  21283. {
  21284. if (!lower && !upper) return;
  21285. if (!lower) // disconnect upper at bottom
  21286. {
  21287. // disconnect old bar below upper:
  21288. if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
  21289. upper->mBarBelow.data()->mBarAbove = nullptr;
  21290. upper->mBarBelow = nullptr;
  21291. } else if (!upper) // disconnect lower at top
  21292. {
  21293. // disconnect old bar above lower:
  21294. if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
  21295. lower->mBarAbove.data()->mBarBelow = nullptr;
  21296. lower->mBarAbove = nullptr;
  21297. } else // connect lower and upper
  21298. {
  21299. // disconnect old bar above lower:
  21300. if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
  21301. lower->mBarAbove.data()->mBarBelow = nullptr;
  21302. // disconnect old bar below upper:
  21303. if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
  21304. upper->mBarBelow.data()->mBarAbove = nullptr;
  21305. lower->mBarAbove = upper;
  21306. upper->mBarBelow = lower;
  21307. }
  21308. }
  21309. /* end of 'src/plottables/plottable-bars.cpp' */
  21310. /* including file 'src/plottables/plottable-statisticalbox.cpp' */
  21311. /* modified 2022-11-06T12:45:57, size 28951 */
  21312. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21313. //////////////////// QCPStatisticalBoxData
  21314. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21315. /*! \class QCPStatisticalBoxData
  21316. \brief Holds the data of one single data point for QCPStatisticalBox.
  21317. The stored data is:
  21318. \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
  21319. \li \a minimum: the position of the lower whisker, typically the minimum measurement of the
  21320. sample that's not considered an outlier.
  21321. \li \a lowerQuartile: the lower end of the box. The lower and the upper quartiles are the two
  21322. statistical quartiles around the median of the sample, they should contain 50% of the sample
  21323. data.
  21324. \li \a median: the value of the median mark inside the quartile box. The median separates the
  21325. sample data in half (50% of the sample data is below/above the median). (This is the \a mainValue)
  21326. \li \a upperQuartile: the upper end of the box. The lower and the upper quartiles are the two
  21327. statistical quartiles around the median of the sample, they should contain 50% of the sample
  21328. data.
  21329. \li \a maximum: the position of the upper whisker, typically the maximum measurement of the
  21330. sample that's not considered an outlier.
  21331. \li \a outliers: a QVector of outlier values that will be drawn as scatter points at the \a key
  21332. coordinate of this data point (see \ref QCPStatisticalBox::setOutlierStyle)
  21333. The container for storing multiple data points is \ref QCPStatisticalBoxDataContainer. It is a
  21334. typedef for \ref QCPDataContainer with \ref QCPStatisticalBoxData as the DataType template
  21335. parameter. See the documentation there for an explanation regarding the data type's generic
  21336. methods.
  21337. \see QCPStatisticalBoxDataContainer
  21338. */
  21339. /* start documentation of inline functions */
  21340. /*! \fn double QCPStatisticalBoxData::sortKey() const
  21341. Returns the \a key member of this data point.
  21342. For a general explanation of what this method is good for in the context of the data container,
  21343. see the documentation of \ref QCPDataContainer.
  21344. */
  21345. /*! \fn static QCPStatisticalBoxData QCPStatisticalBoxData::fromSortKey(double sortKey)
  21346. Returns a data point with the specified \a sortKey. All other members are set to zero.
  21347. For a general explanation of what this method is good for in the context of the data container,
  21348. see the documentation of \ref QCPDataContainer.
  21349. */
  21350. /*! \fn static static bool QCPStatisticalBoxData::sortKeyIsMainKey()
  21351. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  21352. this method returns true.
  21353. For a general explanation of what this method is good for in the context of the data container,
  21354. see the documentation of \ref QCPDataContainer.
  21355. */
  21356. /*! \fn double QCPStatisticalBoxData::mainKey() const
  21357. Returns the \a key member of this data point.
  21358. For a general explanation of what this method is good for in the context of the data container,
  21359. see the documentation of \ref QCPDataContainer.
  21360. */
  21361. /*! \fn double QCPStatisticalBoxData::mainValue() const
  21362. Returns the \a median member of this data point.
  21363. For a general explanation of what this method is good for in the context of the data container,
  21364. see the documentation of \ref QCPDataContainer.
  21365. */
  21366. /*! \fn QCPRange QCPStatisticalBoxData::valueRange() const
  21367. Returns a QCPRange spanning from the \a minimum to the \a maximum member of this statistical box
  21368. data point, possibly further expanded by outliers.
  21369. For a general explanation of what this method is good for in the context of the data container,
  21370. see the documentation of \ref QCPDataContainer.
  21371. */
  21372. /* end documentation of inline functions */
  21373. /*!
  21374. Constructs a data point with key and all values set to zero.
  21375. */
  21376. QCPStatisticalBoxData::QCPStatisticalBoxData() :
  21377. key(0),
  21378. minimum(0),
  21379. lowerQuartile(0),
  21380. median(0),
  21381. upperQuartile(0),
  21382. maximum(0)
  21383. {
  21384. }
  21385. /*!
  21386. Constructs a data point with the specified \a key, \a minimum, \a lowerQuartile, \a median, \a
  21387. upperQuartile, \a maximum and optionally a number of \a outliers.
  21388. */
  21389. QCPStatisticalBoxData::QCPStatisticalBoxData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers) :
  21390. key(key),
  21391. minimum(minimum),
  21392. lowerQuartile(lowerQuartile),
  21393. median(median),
  21394. upperQuartile(upperQuartile),
  21395. maximum(maximum),
  21396. outliers(outliers)
  21397. {
  21398. }
  21399. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21400. //////////////////// QCPStatisticalBox
  21401. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21402. /*! \class QCPStatisticalBox
  21403. \brief A plottable representing a single statistical box in a plot.
  21404. \image html QCPStatisticalBox.png
  21405. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
  21406. also access and modify the data via the \ref data method, which returns a pointer to the internal
  21407. \ref QCPStatisticalBoxDataContainer.
  21408. Additionally each data point can itself have a list of outliers, drawn as scatter points at the
  21409. key coordinate of the respective statistical box data point. They can either be set by using the
  21410. respective \ref addData(double,double,double,double,double,double,const QVector<double>&)
  21411. "addData" method or accessing the individual data points through \ref data, and setting the
  21412. <tt>QVector<double> outliers</tt> of the data points directly.
  21413. \section qcpstatisticalbox-appearance Changing the appearance
  21414. The appearance of each data point box, ranging from the lower to the upper quartile, is
  21415. controlled via \ref setPen and \ref setBrush. You may change the width of the boxes with \ref
  21416. setWidth in plot coordinates.
  21417. Each data point's visual representation also consists of two whiskers. Whiskers are the lines
  21418. which reach from the upper quartile to the maximum, and from the lower quartile to the minimum.
  21419. The appearance of the whiskers can be modified with: \ref setWhiskerPen, \ref setWhiskerBarPen,
  21420. \ref setWhiskerWidth. The whisker width is the width of the bar perpendicular to the whisker at
  21421. the top (for maximum) and bottom (for minimum). If the whisker pen is changed, make sure to set
  21422. the \c capStyle to \c Qt::FlatCap. Otherwise the backbone line might exceed the whisker bars by a
  21423. few pixels due to the pen cap being not perfectly flat.
  21424. The median indicator line inside the box has its own pen, \ref setMedianPen.
  21425. The outlier data points are drawn as normal scatter points. Their look can be controlled with
  21426. \ref setOutlierStyle
  21427. \section qcpstatisticalbox-usage Usage
  21428. Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable
  21429. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  21430. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  21431. Usually, you first create an instance:
  21432. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-1
  21433. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  21434. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  21435. The newly created plottable can be modified, e.g.:
  21436. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-2
  21437. */
  21438. /* start documentation of inline functions */
  21439. /*! \fn QSharedPointer<QCPStatisticalBoxDataContainer> QCPStatisticalBox::data() const
  21440. Returns a shared pointer to the internal data storage of type \ref
  21441. QCPStatisticalBoxDataContainer. You may use it to directly manipulate the data, which may be more
  21442. convenient and faster than using the regular \ref setData or \ref addData methods.
  21443. */
  21444. /* end documentation of inline functions */
  21445. /*!
  21446. Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its
  21447. value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and
  21448. not have the same orientation. If either of these restrictions is violated, a corresponding
  21449. message is printed to the debug output (qDebug), the construction is not aborted, though.
  21450. The created QCPStatisticalBox is automatically registered with the QCustomPlot instance inferred
  21451. from \a keyAxis. This QCustomPlot instance takes ownership of the QCPStatisticalBox, so do not
  21452. delete it manually but use QCustomPlot::removePlottable() instead.
  21453. */
  21454. QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  21455. QCPAbstractPlottable1D<QCPStatisticalBoxData>(keyAxis, valueAxis),
  21456. mWidth(0.5),
  21457. mWhiskerWidth(0.2),
  21458. mWhiskerPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap),
  21459. mWhiskerBarPen(Qt::black),
  21460. mWhiskerAntialiased(false),
  21461. mMedianPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap),
  21462. mOutlierStyle(QCPScatterStyle::ssCircle, Qt::blue, 6)
  21463. {
  21464. setPen(QPen(Qt::black));
  21465. setBrush(Qt::NoBrush);
  21466. }
  21467. /*! \overload
  21468. Replaces the current data container with the provided \a data container.
  21469. Since a QSharedPointer is used, multiple QCPStatisticalBoxes may share the same data container
  21470. safely. Modifying the data in the container will then affect all statistical boxes that share the
  21471. container. Sharing can be achieved by simply exchanging the data containers wrapped in shared
  21472. pointers:
  21473. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-datasharing-1
  21474. If you do not wish to share containers, but create a copy from an existing container, rather use
  21475. the \ref QCPDataContainer<DataType>::set method on the statistical box data container directly:
  21476. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-datasharing-2
  21477. \see addData
  21478. */
  21479. void QCPStatisticalBox::setData(QSharedPointer<QCPStatisticalBoxDataContainer> data)
  21480. {
  21481. mDataContainer = data;
  21482. }
  21483. /*! \overload
  21484. Replaces the current data with the provided points in \a keys, \a minimum, \a lowerQuartile, \a
  21485. median, \a upperQuartile and \a maximum. The provided vectors should have equal length. Else, the
  21486. number of added points will be the size of the smallest vector.
  21487. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  21488. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  21489. \see addData
  21490. */
  21491. 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)
  21492. {
  21493. mDataContainer->clear();
  21494. addData(keys, minimum, lowerQuartile, median, upperQuartile, maximum, alreadySorted);
  21495. }
  21496. /*!
  21497. Sets the width of the boxes in key coordinates.
  21498. \see setWhiskerWidth
  21499. */
  21500. void QCPStatisticalBox::setWidth(double width)
  21501. {
  21502. mWidth = width;
  21503. }
  21504. /*!
  21505. Sets the width of the whiskers in key coordinates.
  21506. Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
  21507. quartile to the minimum.
  21508. \see setWidth
  21509. */
  21510. void QCPStatisticalBox::setWhiskerWidth(double width)
  21511. {
  21512. mWhiskerWidth = width;
  21513. }
  21514. /*!
  21515. Sets the pen used for drawing the whisker backbone.
  21516. Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
  21517. quartile to the minimum.
  21518. Make sure to set the \c capStyle of the passed \a pen to \c Qt::FlatCap. Otherwise the backbone
  21519. line might exceed the whisker bars by a few pixels due to the pen cap being not perfectly flat.
  21520. \see setWhiskerBarPen
  21521. */
  21522. void QCPStatisticalBox::setWhiskerPen(const QPen &pen)
  21523. {
  21524. mWhiskerPen = pen;
  21525. }
  21526. /*!
  21527. Sets the pen used for drawing the whisker bars. Those are the lines parallel to the key axis at
  21528. each end of the whisker backbone.
  21529. Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
  21530. quartile to the minimum.
  21531. \see setWhiskerPen
  21532. */
  21533. void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen)
  21534. {
  21535. mWhiskerBarPen = pen;
  21536. }
  21537. /*!
  21538. Sets whether the statistical boxes whiskers are drawn with antialiasing or not.
  21539. Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and
  21540. QCustomPlot::setNotAntialiasedElements.
  21541. */
  21542. void QCPStatisticalBox::setWhiskerAntialiased(bool enabled)
  21543. {
  21544. mWhiskerAntialiased = enabled;
  21545. }
  21546. /*!
  21547. Sets the pen used for drawing the median indicator line inside the statistical boxes.
  21548. */
  21549. void QCPStatisticalBox::setMedianPen(const QPen &pen)
  21550. {
  21551. mMedianPen = pen;
  21552. }
  21553. /*!
  21554. Sets the appearance of the outlier data points.
  21555. Outliers can be specified with the method
  21556. \ref addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers)
  21557. */
  21558. void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style)
  21559. {
  21560. mOutlierStyle = style;
  21561. }
  21562. /*! \overload
  21563. Adds the provided points in \a keys, \a minimum, \a lowerQuartile, \a median, \a upperQuartile and
  21564. \a maximum to the current data. The provided vectors should have equal length. Else, the number
  21565. of added points will be the size of the smallest vector.
  21566. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  21567. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  21568. Alternatively, you can also access and modify the data directly via the \ref data method, which
  21569. returns a pointer to the internal data container.
  21570. */
  21571. 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)
  21572. {
  21573. if (keys.size() != minimum.size() || minimum.size() != lowerQuartile.size() || lowerQuartile.size() != median.size() ||
  21574. median.size() != upperQuartile.size() || upperQuartile.size() != maximum.size() || maximum.size() != keys.size())
  21575. qDebug() << Q_FUNC_INFO << "keys, minimum, lowerQuartile, median, upperQuartile, maximum have different sizes:"
  21576. << keys.size() << minimum.size() << lowerQuartile.size() << median.size() << upperQuartile.size() << maximum.size();
  21577. const int n = qMin(keys.size(), qMin(minimum.size(), qMin(lowerQuartile.size(), qMin(median.size(), qMin(upperQuartile.size(), maximum.size())))));
  21578. QVector<QCPStatisticalBoxData> tempData(n);
  21579. QVector<QCPStatisticalBoxData>::iterator it = tempData.begin();
  21580. const QVector<QCPStatisticalBoxData>::iterator itEnd = tempData.end();
  21581. int i = 0;
  21582. while (it != itEnd)
  21583. {
  21584. it->key = keys[i];
  21585. it->minimum = minimum[i];
  21586. it->lowerQuartile = lowerQuartile[i];
  21587. it->median = median[i];
  21588. it->upperQuartile = upperQuartile[i];
  21589. it->maximum = maximum[i];
  21590. ++it;
  21591. ++i;
  21592. }
  21593. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  21594. }
  21595. /*! \overload
  21596. Adds the provided data point as \a key, \a minimum, \a lowerQuartile, \a median, \a upperQuartile
  21597. and \a maximum to the current data.
  21598. Alternatively, you can also access and modify the data directly via the \ref data method, which
  21599. returns a pointer to the internal data container.
  21600. */
  21601. void QCPStatisticalBox::addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers)
  21602. {
  21603. mDataContainer->add(QCPStatisticalBoxData(key, minimum, lowerQuartile, median, upperQuartile, maximum, outliers));
  21604. }
  21605. /*!
  21606. \copydoc QCPPlottableInterface1D::selectTestRect
  21607. */
  21608. QCPDataSelection QCPStatisticalBox::selectTestRect(const QRectF &rect, bool onlySelectable) const
  21609. {
  21610. QCPDataSelection result;
  21611. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  21612. return result;
  21613. if (!mKeyAxis || !mValueAxis)
  21614. return result;
  21615. QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
  21616. getVisibleDataBounds(visibleBegin, visibleEnd);
  21617. for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  21618. {
  21619. if (rect.intersects(getQuartileBox(it)))
  21620. result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
  21621. }
  21622. result.simplify();
  21623. return result;
  21624. }
  21625. /*!
  21626. Implements a selectTest specific to this plottable's point geometry.
  21627. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  21628. point to \a pos.
  21629. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  21630. */
  21631. double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  21632. {
  21633. Q_UNUSED(details)
  21634. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  21635. return -1;
  21636. if (!mKeyAxis || !mValueAxis)
  21637. return -1;
  21638. if (mKeyAxis->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  21639. {
  21640. // get visible data range:
  21641. QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
  21642. QCPStatisticalBoxDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  21643. getVisibleDataBounds(visibleBegin, visibleEnd);
  21644. double minDistSqr = (std::numeric_limits<double>::max)();
  21645. for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  21646. {
  21647. if (getQuartileBox(it).contains(pos)) // quartile box
  21648. {
  21649. double currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
  21650. if (currentDistSqr < minDistSqr)
  21651. {
  21652. minDistSqr = currentDistSqr;
  21653. closestDataPoint = it;
  21654. }
  21655. } else // whiskers
  21656. {
  21657. const QVector<QLineF> whiskerBackbones = getWhiskerBackboneLines(it);
  21658. const QCPVector2D posVec(pos);
  21659. foreach (const QLineF &backbone, whiskerBackbones)
  21660. {
  21661. double currentDistSqr = posVec.distanceSquaredToLine(backbone);
  21662. if (currentDistSqr < minDistSqr)
  21663. {
  21664. minDistSqr = currentDistSqr;
  21665. closestDataPoint = it;
  21666. }
  21667. }
  21668. }
  21669. }
  21670. if (details)
  21671. {
  21672. int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
  21673. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  21674. }
  21675. return qSqrt(minDistSqr);
  21676. }
  21677. return -1;
  21678. }
  21679. /* inherits documentation from base class */
  21680. QCPRange QCPStatisticalBox::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  21681. {
  21682. QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain);
  21683. // determine exact range by including width of bars/flags:
  21684. if (foundRange)
  21685. {
  21686. if (inSignDomain != QCP::sdPositive || range.lower-mWidth*0.5 > 0)
  21687. range.lower -= mWidth*0.5;
  21688. if (inSignDomain != QCP::sdNegative || range.upper+mWidth*0.5 < 0)
  21689. range.upper += mWidth*0.5;
  21690. }
  21691. return range;
  21692. }
  21693. /* inherits documentation from base class */
  21694. QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  21695. {
  21696. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  21697. }
  21698. /* inherits documentation from base class */
  21699. void QCPStatisticalBox::draw(QCPPainter *painter)
  21700. {
  21701. if (mDataContainer->isEmpty()) return;
  21702. QCPAxis *keyAxis = mKeyAxis.data();
  21703. QCPAxis *valueAxis = mValueAxis.data();
  21704. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  21705. QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
  21706. getVisibleDataBounds(visibleBegin, visibleEnd);
  21707. // loop over and draw segments of unselected/selected data:
  21708. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  21709. getDataSegments(selectedSegments, unselectedSegments);
  21710. allSegments << unselectedSegments << selectedSegments;
  21711. for (int i=0; i<allSegments.size(); ++i)
  21712. {
  21713. bool isSelectedSegment = i >= unselectedSegments.size();
  21714. QCPStatisticalBoxDataContainer::const_iterator begin = visibleBegin;
  21715. QCPStatisticalBoxDataContainer::const_iterator end = visibleEnd;
  21716. mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
  21717. if (begin == end)
  21718. continue;
  21719. for (QCPStatisticalBoxDataContainer::const_iterator it=begin; it!=end; ++it)
  21720. {
  21721. // check data validity if flag set:
  21722. # ifdef QCUSTOMPLOT_CHECK_DATA
  21723. if (QCP::isInvalidData(it->key, it->minimum) ||
  21724. QCP::isInvalidData(it->lowerQuartile, it->median) ||
  21725. QCP::isInvalidData(it->upperQuartile, it->maximum))
  21726. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range has invalid data." << "Plottable name:" << name();
  21727. for (int i=0; i<it->outliers.size(); ++i)
  21728. if (QCP::isInvalidData(it->outliers.at(i)))
  21729. qDebug() << Q_FUNC_INFO << "Data point outlier at" << it->key << "of drawn range invalid." << "Plottable name:" << name();
  21730. # endif
  21731. if (isSelectedSegment && mSelectionDecorator)
  21732. {
  21733. mSelectionDecorator->applyPen(painter);
  21734. mSelectionDecorator->applyBrush(painter);
  21735. } else
  21736. {
  21737. painter->setPen(mPen);
  21738. painter->setBrush(mBrush);
  21739. }
  21740. QCPScatterStyle finalOutlierStyle = mOutlierStyle;
  21741. if (isSelectedSegment && mSelectionDecorator)
  21742. finalOutlierStyle = mSelectionDecorator->getFinalScatterStyle(mOutlierStyle);
  21743. drawStatisticalBox(painter, it, finalOutlierStyle);
  21744. }
  21745. }
  21746. // draw other selection decoration that isn't just line/scatter pens and brushes:
  21747. if (mSelectionDecorator)
  21748. mSelectionDecorator->drawDecoration(painter, selection());
  21749. }
  21750. /* inherits documentation from base class */
  21751. void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  21752. {
  21753. // draw filled rect:
  21754. applyDefaultAntialiasingHint(painter);
  21755. painter->setPen(mPen);
  21756. painter->setBrush(mBrush);
  21757. QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
  21758. r.moveCenter(rect.center());
  21759. painter->drawRect(r);
  21760. }
  21761. /*!
  21762. Draws the graphical representation of a single statistical box with the data given by the
  21763. iterator \a it with the provided \a painter.
  21764. If the statistical box has a set of outlier data points, they are drawn with \a outlierStyle.
  21765. \see getQuartileBox, getWhiskerBackboneLines, getWhiskerBarLines
  21766. */
  21767. void QCPStatisticalBox::drawStatisticalBox(QCPPainter *painter, QCPStatisticalBoxDataContainer::const_iterator it, const QCPScatterStyle &outlierStyle) const
  21768. {
  21769. // draw quartile box:
  21770. applyDefaultAntialiasingHint(painter);
  21771. const QRectF quartileBox = getQuartileBox(it);
  21772. painter->drawRect(quartileBox);
  21773. // draw median line with cliprect set to quartile box:
  21774. painter->save();
  21775. painter->setClipRect(quartileBox, Qt::IntersectClip);
  21776. painter->setPen(mMedianPen);
  21777. painter->drawLine(QLineF(coordsToPixels(it->key-mWidth*0.5, it->median), coordsToPixels(it->key+mWidth*0.5, it->median)));
  21778. painter->restore();
  21779. // draw whisker lines:
  21780. applyAntialiasingHint(painter, mWhiskerAntialiased, QCP::aePlottables);
  21781. painter->setPen(mWhiskerPen);
  21782. painter->drawLines(getWhiskerBackboneLines(it));
  21783. painter->setPen(mWhiskerBarPen);
  21784. painter->drawLines(getWhiskerBarLines(it));
  21785. // draw outliers:
  21786. applyScattersAntialiasingHint(painter);
  21787. outlierStyle.applyTo(painter, mPen);
  21788. for (int i=0; i<it->outliers.size(); ++i)
  21789. outlierStyle.drawShape(painter, coordsToPixels(it->key, it->outliers.at(i)));
  21790. }
  21791. /*! \internal
  21792. called by \ref draw to determine which data (key) range is visible at the current key axis range
  21793. setting, so only that needs to be processed. It also takes into account the bar width.
  21794. \a begin returns an iterator to the lowest data point that needs to be taken into account when
  21795. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  21796. lower may still be just outside the visible range.
  21797. \a end returns an iterator one higher than the highest visible data point. Same as before, \a end
  21798. may also lie just outside of the visible range.
  21799. if the plottable contains no data, both \a begin and \a end point to constEnd.
  21800. */
  21801. void QCPStatisticalBox::getVisibleDataBounds(QCPStatisticalBoxDataContainer::const_iterator &begin, QCPStatisticalBoxDataContainer::const_iterator &end) const
  21802. {
  21803. if (!mKeyAxis)
  21804. {
  21805. qDebug() << Q_FUNC_INFO << "invalid key axis";
  21806. begin = mDataContainer->constEnd();
  21807. end = mDataContainer->constEnd();
  21808. return;
  21809. }
  21810. begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of box to include partially visible data points
  21811. end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of box to include partially visible data points
  21812. }
  21813. /*! \internal
  21814. Returns the box in plot coordinates (keys in x, values in y of the returned rect) that covers the
  21815. value range from the lower to the upper quartile, of the data given by \a it.
  21816. \see drawStatisticalBox, getWhiskerBackboneLines, getWhiskerBarLines
  21817. */
  21818. QRectF QCPStatisticalBox::getQuartileBox(QCPStatisticalBoxDataContainer::const_iterator it) const
  21819. {
  21820. QRectF result;
  21821. result.setTopLeft(coordsToPixels(it->key-mWidth*0.5, it->upperQuartile));
  21822. result.setBottomRight(coordsToPixels(it->key+mWidth*0.5, it->lowerQuartile));
  21823. return result;
  21824. }
  21825. /*! \internal
  21826. Returns the whisker backbones (keys in x, values in y of the returned lines) that cover the value
  21827. range from the minimum to the lower quartile, and from the upper quartile to the maximum of the
  21828. data given by \a it.
  21829. \see drawStatisticalBox, getQuartileBox, getWhiskerBarLines
  21830. */
  21831. QVector<QLineF> QCPStatisticalBox::getWhiskerBackboneLines(QCPStatisticalBoxDataContainer::const_iterator it) const
  21832. {
  21833. QVector<QLineF> result(2);
  21834. result[0].setPoints(coordsToPixels(it->key, it->lowerQuartile), coordsToPixels(it->key, it->minimum)); // min backbone
  21835. result[1].setPoints(coordsToPixels(it->key, it->upperQuartile), coordsToPixels(it->key, it->maximum)); // max backbone
  21836. return result;
  21837. }
  21838. /*! \internal
  21839. Returns the whisker bars (keys in x, values in y of the returned lines) that are placed at the
  21840. end of the whisker backbones, at the minimum and maximum of the data given by \a it.
  21841. \see drawStatisticalBox, getQuartileBox, getWhiskerBackboneLines
  21842. */
  21843. QVector<QLineF> QCPStatisticalBox::getWhiskerBarLines(QCPStatisticalBoxDataContainer::const_iterator it) const
  21844. {
  21845. QVector<QLineF> result(2);
  21846. result[0].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->minimum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->minimum)); // min bar
  21847. result[1].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->maximum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->maximum)); // max bar
  21848. return result;
  21849. }
  21850. /* end of 'src/plottables/plottable-statisticalbox.cpp' */
  21851. /* including file 'src/plottables/plottable-colormap.cpp' */
  21852. /* modified 2022-11-06T12:45:56, size 48189 */
  21853. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21854. //////////////////// QCPColorMapData
  21855. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21856. /*! \class QCPColorMapData
  21857. \brief Holds the two-dimensional data of a QCPColorMap plottable.
  21858. This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref
  21859. QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a
  21860. color, depending on the value.
  21861. The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize).
  21862. Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref
  21863. setKeyRange, \ref setValueRange).
  21864. The data cells can be accessed in two ways: They can be directly addressed by an integer index
  21865. with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot
  21866. coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are
  21867. provided by the functions \ref coordToCell and \ref cellToCoord.
  21868. A \ref QCPColorMapData also holds an on-demand two-dimensional array of alpha values which (if
  21869. allocated) has the same size as the data map. It can be accessed via \ref setAlpha, \ref
  21870. fillAlpha and \ref clearAlpha. The memory for the alpha map is only allocated if needed, i.e. on
  21871. the first call of \ref setAlpha. \ref clearAlpha restores full opacity and frees the alpha map.
  21872. This class also buffers the minimum and maximum values that are in the data set, to provide
  21873. QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value
  21874. that is greater than the current maximum increases this maximum to the new value. However,
  21875. setting the cell that currently holds the maximum value to a smaller value doesn't decrease the
  21876. maximum again, because finding the true new maximum would require going through the entire data
  21877. array, which might be time consuming. The same holds for the data minimum. This functionality is
  21878. given by \ref recalculateDataBounds, such that you can decide when it is sensible to find the
  21879. true current minimum and maximum. The method QCPColorMap::rescaleDataRange offers a convenience
  21880. parameter \a recalculateDataBounds which may be set to true to automatically call \ref
  21881. recalculateDataBounds internally.
  21882. */
  21883. /* start of documentation of inline functions */
  21884. /*! \fn bool QCPColorMapData::isEmpty() const
  21885. Returns whether this instance carries no data. This is equivalent to having a size where at least
  21886. one of the dimensions is 0 (see \ref setSize).
  21887. */
  21888. /* end of documentation of inline functions */
  21889. /*!
  21890. Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction
  21891. and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap
  21892. at the coordinates \a keyRange and \a valueRange.
  21893. \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange
  21894. */
  21895. QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) :
  21896. mKeySize(0),
  21897. mValueSize(0),
  21898. mKeyRange(keyRange),
  21899. mValueRange(valueRange),
  21900. mIsEmpty(true),
  21901. mData(nullptr),
  21902. mAlpha(nullptr),
  21903. mDataModified(true)
  21904. {
  21905. setSize(keySize, valueSize);
  21906. fill(0);
  21907. }
  21908. QCPColorMapData::~QCPColorMapData()
  21909. {
  21910. delete[] mData;
  21911. delete[] mAlpha;
  21912. }
  21913. /*!
  21914. Constructs a new QCPColorMapData instance copying the data and range of \a other.
  21915. */
  21916. QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) :
  21917. mKeySize(0),
  21918. mValueSize(0),
  21919. mIsEmpty(true),
  21920. mData(nullptr),
  21921. mAlpha(nullptr),
  21922. mDataModified(true)
  21923. {
  21924. *this = other;
  21925. }
  21926. /*!
  21927. Overwrites this color map data instance with the data stored in \a other. The alpha map state is
  21928. transferred, too.
  21929. */
  21930. QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other)
  21931. {
  21932. if (&other != this)
  21933. {
  21934. const int keySize = other.keySize();
  21935. const int valueSize = other.valueSize();
  21936. if (!other.mAlpha && mAlpha)
  21937. clearAlpha();
  21938. setSize(keySize, valueSize);
  21939. if (other.mAlpha && !mAlpha)
  21940. createAlpha(false);
  21941. setRange(other.keyRange(), other.valueRange());
  21942. if (!isEmpty())
  21943. {
  21944. memcpy(mData, other.mData, sizeof(mData[0])*size_t(keySize*valueSize));
  21945. if (mAlpha)
  21946. memcpy(mAlpha, other.mAlpha, sizeof(mAlpha[0])*size_t(keySize*valueSize));
  21947. }
  21948. mDataBounds = other.mDataBounds;
  21949. mDataModified = true;
  21950. }
  21951. return *this;
  21952. }
  21953. /* undocumented getter */
  21954. double QCPColorMapData::data(double key, double value)
  21955. {
  21956. int keyCell = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5 );
  21957. int valueCell = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 );
  21958. if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
  21959. return mData[valueCell*mKeySize + keyCell];
  21960. else
  21961. return 0;
  21962. }
  21963. /* undocumented getter */
  21964. double QCPColorMapData::cell(int keyIndex, int valueIndex)
  21965. {
  21966. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  21967. return mData[valueIndex*mKeySize + keyIndex];
  21968. else
  21969. return 0;
  21970. }
  21971. /*!
  21972. Returns the alpha map value of the cell with the indices \a keyIndex and \a valueIndex.
  21973. If this color map data doesn't have an alpha map (because \ref setAlpha was never called after
  21974. creation or after a call to \ref clearAlpha), returns 255, which corresponds to full opacity.
  21975. \see setAlpha
  21976. */
  21977. unsigned char QCPColorMapData::alpha(int keyIndex, int valueIndex)
  21978. {
  21979. if (mAlpha && keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  21980. return mAlpha[valueIndex*mKeySize + keyIndex];
  21981. else
  21982. return 255;
  21983. }
  21984. /*!
  21985. Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in
  21986. the value dimension.
  21987. The current data is discarded and the map cells are set to 0, unless the map had already the
  21988. requested size.
  21989. Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref
  21990. isEmpty returns true.
  21991. \see setRange, setKeySize, setValueSize
  21992. */
  21993. void QCPColorMapData::setSize(int keySize, int valueSize)
  21994. {
  21995. if (keySize != mKeySize || valueSize != mValueSize)
  21996. {
  21997. mKeySize = keySize;
  21998. mValueSize = valueSize;
  21999. delete[] mData;
  22000. mIsEmpty = mKeySize == 0 || mValueSize == 0;
  22001. if (!mIsEmpty)
  22002. {
  22003. #ifdef __EXCEPTIONS
  22004. try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message
  22005. #endif
  22006. mData = new double[size_t(mKeySize*mValueSize)];
  22007. #ifdef __EXCEPTIONS
  22008. } catch (...) { mData = nullptr; }
  22009. #endif
  22010. if (mData)
  22011. fill(0);
  22012. else
  22013. qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize;
  22014. } else
  22015. mData = nullptr;
  22016. if (mAlpha) // if we had an alpha map, recreate it with new size
  22017. createAlpha();
  22018. mDataModified = true;
  22019. }
  22020. }
  22021. /*!
  22022. Resizes the data array to have \a keySize cells in the key dimension.
  22023. The current data is discarded and the map cells are set to 0, unless the map had already the
  22024. requested size.
  22025. Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true.
  22026. \see setKeyRange, setSize, setValueSize
  22027. */
  22028. void QCPColorMapData::setKeySize(int keySize)
  22029. {
  22030. setSize(keySize, mValueSize);
  22031. }
  22032. /*!
  22033. Resizes the data array to have \a valueSize cells in the value dimension.
  22034. The current data is discarded and the map cells are set to 0, unless the map had already the
  22035. requested size.
  22036. Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true.
  22037. \see setValueRange, setSize, setKeySize
  22038. */
  22039. void QCPColorMapData::setValueSize(int valueSize)
  22040. {
  22041. setSize(mKeySize, valueSize);
  22042. }
  22043. /*!
  22044. Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area
  22045. covered by the color map in plot coordinates.
  22046. The outer cells will be centered on the range boundaries given to this function. For example, if
  22047. the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
  22048. be cells centered on the key coordinates 2, 2.5 and 3.
  22049. \see setSize
  22050. */
  22051. void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange)
  22052. {
  22053. setKeyRange(keyRange);
  22054. setValueRange(valueRange);
  22055. }
  22056. /*!
  22057. Sets the coordinate range the data shall be distributed over in the key dimension. Together with
  22058. the value range, This defines the rectangular area covered by the color map in plot coordinates.
  22059. The outer cells will be centered on the range boundaries given to this function. For example, if
  22060. the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
  22061. be cells centered on the key coordinates 2, 2.5 and 3.
  22062. \see setRange, setValueRange, setSize
  22063. */
  22064. void QCPColorMapData::setKeyRange(const QCPRange &keyRange)
  22065. {
  22066. mKeyRange = keyRange;
  22067. }
  22068. /*!
  22069. Sets the coordinate range the data shall be distributed over in the value dimension. Together with
  22070. the key range, This defines the rectangular area covered by the color map in plot coordinates.
  22071. The outer cells will be centered on the range boundaries given to this function. For example, if
  22072. the value size (\ref setValueSize) is 3 and \a valueRange is set to <tt>QCPRange(2, 3)</tt> there
  22073. will be cells centered on the value coordinates 2, 2.5 and 3.
  22074. \see setRange, setKeyRange, setSize
  22075. */
  22076. void QCPColorMapData::setValueRange(const QCPRange &valueRange)
  22077. {
  22078. mValueRange = valueRange;
  22079. }
  22080. /*!
  22081. Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a
  22082. z.
  22083. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  22084. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  22085. you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
  22086. determine the cell index. Rather directly access the cell index with \ref
  22087. QCPColorMapData::setCell.
  22088. \see setCell, setRange
  22089. */
  22090. void QCPColorMapData::setData(double key, double value, double z)
  22091. {
  22092. int keyCell = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5 );
  22093. int valueCell = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 );
  22094. if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
  22095. {
  22096. mData[valueCell*mKeySize + keyCell] = z;
  22097. if (z < mDataBounds.lower)
  22098. mDataBounds.lower = z;
  22099. if (z > mDataBounds.upper)
  22100. mDataBounds.upper = z;
  22101. mDataModified = true;
  22102. }
  22103. }
  22104. /*!
  22105. Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices
  22106. enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see
  22107. \ref setSize).
  22108. In the standard plot configuration (horizontal key axis and vertical value axis, both not
  22109. range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with
  22110. indices (keySize-1, valueSize-1) is in the top right corner of the color map.
  22111. \see setData, setSize
  22112. */
  22113. void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z)
  22114. {
  22115. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  22116. {
  22117. mData[valueIndex*mKeySize + keyIndex] = z;
  22118. if (z < mDataBounds.lower)
  22119. mDataBounds.lower = z;
  22120. if (z > mDataBounds.upper)
  22121. mDataBounds.upper = z;
  22122. mDataModified = true;
  22123. } else
  22124. qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex;
  22125. }
  22126. /*!
  22127. Sets the alpha of the color map cell given by \a keyIndex and \a valueIndex to \a alpha. A value
  22128. of 0 for \a alpha results in a fully transparent cell, and a value of 255 results in a fully
  22129. opaque cell.
  22130. If an alpha map doesn't exist yet for this color map data, it will be created here. If you wish
  22131. to restore full opacity and free any allocated memory of the alpha map, call \ref clearAlpha.
  22132. Note that the cell-wise alpha which can be configured here is independent of any alpha configured
  22133. in the color map's gradient (\ref QCPColorGradient). If a cell is affected both by the cell-wise
  22134. and gradient alpha, the alpha values will be blended accordingly during rendering of the color
  22135. map.
  22136. \see fillAlpha, clearAlpha
  22137. */
  22138. void QCPColorMapData::setAlpha(int keyIndex, int valueIndex, unsigned char alpha)
  22139. {
  22140. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  22141. {
  22142. if (mAlpha || createAlpha())
  22143. {
  22144. mAlpha[valueIndex*mKeySize + keyIndex] = alpha;
  22145. mDataModified = true;
  22146. }
  22147. } else
  22148. qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex;
  22149. }
  22150. /*!
  22151. Goes through the data and updates the buffered minimum and maximum data values.
  22152. Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange
  22153. and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten
  22154. with a smaller or larger value respectively, since the buffered maximum/minimum values have been
  22155. updated the last time. Why this is the case is explained in the class description (\ref
  22156. QCPColorMapData).
  22157. Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a
  22158. recalculateDataBounds for convenience. Setting this to true will call this method for you, before
  22159. doing the rescale.
  22160. */
  22161. void QCPColorMapData::recalculateDataBounds()
  22162. {
  22163. if (mKeySize > 0 && mValueSize > 0)
  22164. {
  22165. double minHeight = std::numeric_limits<double>::max();
  22166. double maxHeight = -std::numeric_limits<double>::max();
  22167. const int dataCount = mValueSize*mKeySize;
  22168. for (int i=0; i<dataCount; ++i)
  22169. {
  22170. if (mData[i] > maxHeight)
  22171. maxHeight = mData[i];
  22172. if (mData[i] < minHeight)
  22173. minHeight = mData[i];
  22174. }
  22175. mDataBounds.lower = minHeight;
  22176. mDataBounds.upper = maxHeight;
  22177. }
  22178. }
  22179. /*!
  22180. Frees the internal data memory.
  22181. This is equivalent to calling \ref setSize "setSize(0, 0)".
  22182. */
  22183. void QCPColorMapData::clear()
  22184. {
  22185. setSize(0, 0);
  22186. }
  22187. /*!
  22188. Frees the internal alpha map. The color map will have full opacity again.
  22189. */
  22190. void QCPColorMapData::clearAlpha()
  22191. {
  22192. if (mAlpha)
  22193. {
  22194. delete[] mAlpha;
  22195. mAlpha = nullptr;
  22196. mDataModified = true;
  22197. }
  22198. }
  22199. /*!
  22200. Sets all cells to the value \a z.
  22201. */
  22202. void QCPColorMapData::fill(double z)
  22203. {
  22204. const int dataCount = mValueSize*mKeySize;
  22205. memset(mData, z, dataCount*sizeof(*mData));
  22206. mDataBounds = QCPRange(z, z);
  22207. mDataModified = true;
  22208. }
  22209. /*!
  22210. Sets the opacity of all color map cells to \a alpha. A value of 0 for \a alpha results in a fully
  22211. transparent color map, and a value of 255 results in a fully opaque color map.
  22212. If you wish to restore opacity to 100% and free any used memory for the alpha map, rather use
  22213. \ref clearAlpha.
  22214. \see setAlpha
  22215. */
  22216. void QCPColorMapData::fillAlpha(unsigned char alpha)
  22217. {
  22218. if (mAlpha || createAlpha(false))
  22219. {
  22220. const int dataCount = mValueSize*mKeySize;
  22221. memset(mAlpha, alpha, dataCount*sizeof(*mAlpha));
  22222. mDataModified = true;
  22223. }
  22224. }
  22225. /*!
  22226. Transforms plot coordinates given by \a key and \a value to cell indices of this QCPColorMapData
  22227. instance. The resulting cell indices are returned via the output parameters \a keyIndex and \a
  22228. valueIndex.
  22229. The retrieved key/value cell indices can then be used for example with \ref setCell.
  22230. If you are only interested in a key or value index, you may pass \c nullptr as \a valueIndex or
  22231. \a keyIndex.
  22232. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  22233. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  22234. you shouldn't use the \ref QCPColorMapData::coordToCell method as it uses a linear transformation to
  22235. determine the cell index.
  22236. \see cellToCoord, QCPAxis::coordToPixel
  22237. */
  22238. void QCPColorMapData::coordToCell(double key, double value, int *keyIndex, int *valueIndex) const
  22239. {
  22240. if (keyIndex)
  22241. *keyIndex = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5 );
  22242. if (valueIndex)
  22243. *valueIndex = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 );
  22244. }
  22245. /*!
  22246. Transforms cell indices given by \a keyIndex and \a valueIndex to cell indices of this QCPColorMapData
  22247. instance. The resulting coordinates are returned via the output parameters \a key and \a
  22248. value.
  22249. If you are only interested in a key or value coordinate, you may pass \c nullptr as \a key or \a
  22250. value.
  22251. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  22252. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  22253. you shouldn't use the \ref QCPColorMapData::cellToCoord method as it uses a linear transformation to
  22254. determine the cell index.
  22255. \see coordToCell, QCPAxis::pixelToCoord
  22256. */
  22257. void QCPColorMapData::cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const
  22258. {
  22259. if (key)
  22260. *key = keyIndex/double(mKeySize-1)*(mKeyRange.upper-mKeyRange.lower)+mKeyRange.lower;
  22261. if (value)
  22262. *value = valueIndex/double(mValueSize-1)*(mValueRange.upper-mValueRange.lower)+mValueRange.lower;
  22263. }
  22264. /*! \internal
  22265. Allocates the internal alpha map with the current data map key/value size and, if \a
  22266. initializeOpaque is true, initializes all values to 255. If \a initializeOpaque is false, the
  22267. values are not initialized at all. In this case, the alpha map should be initialized manually,
  22268. e.g. with \ref fillAlpha.
  22269. If an alpha map exists already, it is deleted first. If this color map is empty (has either key
  22270. or value size zero, see \ref isEmpty), the alpha map is cleared.
  22271. The return value indicates the existence of the alpha map after the call. So this method returns
  22272. true if the data map isn't empty and an alpha map was successfully allocated.
  22273. */
  22274. bool QCPColorMapData::createAlpha(bool initializeOpaque)
  22275. {
  22276. clearAlpha();
  22277. if (isEmpty())
  22278. return false;
  22279. #ifdef __EXCEPTIONS
  22280. try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message
  22281. #endif
  22282. mAlpha = new unsigned char[size_t(mKeySize*mValueSize)];
  22283. #ifdef __EXCEPTIONS
  22284. } catch (...) { mAlpha = nullptr; }
  22285. #endif
  22286. if (mAlpha)
  22287. {
  22288. if (initializeOpaque)
  22289. fillAlpha(255);
  22290. return true;
  22291. } else
  22292. {
  22293. qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize;
  22294. return false;
  22295. }
  22296. }
  22297. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22298. //////////////////// QCPColorMap
  22299. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22300. /*! \class QCPColorMap
  22301. \brief A plottable representing a two-dimensional color map in a plot.
  22302. \image html QCPColorMap.png
  22303. The data is stored in the class \ref QCPColorMapData, which can be accessed via the data()
  22304. method.
  22305. A color map has three dimensions to represent a data point: The \a key dimension, the \a value
  22306. dimension and the \a data dimension. As with other plottables such as graphs, \a key and \a value
  22307. correspond to two orthogonal axes on the QCustomPlot surface that you specify in the QCPColorMap
  22308. constructor. The \a data dimension however is encoded as the color of the point at (\a key, \a
  22309. value).
  22310. Set the number of points (or \a cells) in the key/value dimension via \ref
  22311. QCPColorMapData::setSize. The plot coordinate range over which these points will be displayed is
  22312. specified via \ref QCPColorMapData::setRange. The first cell will be centered on the lower range
  22313. boundary and the last cell will be centered on the upper range boundary. The data can be set by
  22314. either accessing the cells directly with QCPColorMapData::setCell or by addressing the cells via
  22315. their plot coordinates with \ref QCPColorMapData::setData. If possible, you should prefer
  22316. setCell, since it doesn't need to do any coordinate transformation and thus performs a bit
  22317. better.
  22318. The cell with index (0, 0) is at the bottom left, if the color map uses normal (i.e. not reversed)
  22319. key and value axes.
  22320. To show the user which colors correspond to which \a data values, a \ref QCPColorScale is
  22321. typically placed to the right of the axis rect. See the documentation there for details on how to
  22322. add and use a color scale.
  22323. \section qcpcolormap-appearance Changing the appearance
  22324. Most important to the appearance is the color gradient, which can be specified via \ref
  22325. setGradient. See the documentation of \ref QCPColorGradient for details on configuring a color
  22326. gradient.
  22327. The \a data range that is mapped to the colors of the gradient can be specified with \ref
  22328. setDataRange. To make the data range encompass the whole data set minimum to maximum, call \ref
  22329. rescaleDataRange. If your data may contain NaN values, use \ref QCPColorGradient::setNanHandling
  22330. to define how they are displayed.
  22331. \section qcpcolormap-transparency Transparency
  22332. Transparency in color maps can be achieved by two mechanisms. On one hand, you can specify alpha
  22333. values for color stops of the \ref QCPColorGradient, via the regular QColor interface. This will
  22334. cause the color map data which gets mapped to colors around those color stops to appear with the
  22335. accordingly interpolated transparency.
  22336. On the other hand you can also directly apply an alpha value to each cell independent of its
  22337. data, by using the alpha map feature of \ref QCPColorMapData. The relevant methods are \ref
  22338. QCPColorMapData::setAlpha, QCPColorMapData::fillAlpha and \ref QCPColorMapData::clearAlpha().
  22339. The two transparencies will be joined together in the plot and otherwise not interfere with each
  22340. other. They are mixed in a multiplicative matter, so an alpha of e.g. 50% (128/255) in both modes
  22341. simultaneously, will result in a total transparency of 25% (64/255).
  22342. \section qcpcolormap-usage Usage
  22343. Like all data representing objects in QCustomPlot, the QCPColorMap is a plottable
  22344. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  22345. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  22346. Usually, you first create an instance:
  22347. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-1
  22348. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  22349. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  22350. The newly created plottable can be modified, e.g.:
  22351. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-2
  22352. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  22353. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  22354. you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
  22355. determine the cell index. Rather directly access the cell index with \ref
  22356. QCPColorMapData::setCell.
  22357. */
  22358. /* start documentation of inline functions */
  22359. /*! \fn QCPColorMapData *QCPColorMap::data() const
  22360. Returns a pointer to the internal data storage of type \ref QCPColorMapData. Access this to
  22361. modify data points (cells) and the color map key/value range.
  22362. \see setData
  22363. */
  22364. /* end documentation of inline functions */
  22365. /* start documentation of signals */
  22366. /*! \fn void QCPColorMap::dataRangeChanged(const QCPRange &newRange);
  22367. This signal is emitted when the data range changes.
  22368. \see setDataRange
  22369. */
  22370. /*! \fn void QCPColorMap::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
  22371. This signal is emitted when the data scale type changes.
  22372. \see setDataScaleType
  22373. */
  22374. /*! \fn void QCPColorMap::gradientChanged(const QCPColorGradient &newGradient);
  22375. This signal is emitted when the gradient changes.
  22376. \see setGradient
  22377. */
  22378. /* end documentation of signals */
  22379. /*!
  22380. Constructs a color map with the specified \a keyAxis and \a valueAxis.
  22381. The created QCPColorMap is automatically registered with the QCustomPlot instance inferred from
  22382. \a keyAxis. This QCustomPlot instance takes ownership of the QCPColorMap, so do not delete it
  22383. manually but use QCustomPlot::removePlottable() instead.
  22384. */
  22385. QCPColorMap::QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  22386. QCPAbstractPlottable(keyAxis, valueAxis),
  22387. mDataScaleType(QCPAxis::stLinear),
  22388. mMapData(new QCPColorMapData(10, 10, QCPRange(0, 5), QCPRange(0, 5))),
  22389. mGradient(QCPColorGradient::gpCold),
  22390. mInterpolate(true),
  22391. mTightBoundary(false),
  22392. mMapImageInvalidated(true)
  22393. {
  22394. }
  22395. QCPColorMap::~QCPColorMap()
  22396. {
  22397. delete mMapData;
  22398. }
  22399. /*!
  22400. Replaces the current \ref data with the provided \a data.
  22401. If \a copy is set to true, the \a data object will only be copied. if false, the color map
  22402. takes ownership of the passed data and replaces the internal data pointer with it. This is
  22403. significantly faster than copying for large datasets.
  22404. */
  22405. void QCPColorMap::setData(QCPColorMapData *data, bool copy)
  22406. {
  22407. if (mMapData == data)
  22408. {
  22409. qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data);
  22410. return;
  22411. }
  22412. if (copy)
  22413. {
  22414. *mMapData = *data;
  22415. } else
  22416. {
  22417. delete mMapData;
  22418. mMapData = data;
  22419. }
  22420. mMapImageInvalidated = true;
  22421. }
  22422. /*!
  22423. Sets the data range of this color map to \a dataRange. The data range defines which data values
  22424. are mapped to the color gradient.
  22425. To make the data range span the full range of the data set, use \ref rescaleDataRange.
  22426. \see QCPColorScale::setDataRange
  22427. */
  22428. void QCPColorMap::setDataRange(const QCPRange &dataRange)
  22429. {
  22430. if (!QCPRange::validRange(dataRange)) return;
  22431. if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
  22432. {
  22433. if (mDataScaleType == QCPAxis::stLogarithmic)
  22434. mDataRange = dataRange.sanitizedForLogScale();
  22435. else
  22436. mDataRange = dataRange.sanitizedForLinScale();
  22437. mMapImageInvalidated = true;
  22438. emit dataRangeChanged(mDataRange);
  22439. }
  22440. }
  22441. /*!
  22442. Sets whether the data is correlated with the color gradient linearly or logarithmically.
  22443. \see QCPColorScale::setDataScaleType
  22444. */
  22445. void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType)
  22446. {
  22447. if (mDataScaleType != scaleType)
  22448. {
  22449. mDataScaleType = scaleType;
  22450. mMapImageInvalidated = true;
  22451. emit dataScaleTypeChanged(mDataScaleType);
  22452. if (mDataScaleType == QCPAxis::stLogarithmic)
  22453. setDataRange(mDataRange.sanitizedForLogScale());
  22454. }
  22455. }
  22456. /*!
  22457. Sets the color gradient that is used to represent the data. For more details on how to create an
  22458. own gradient or use one of the preset gradients, see \ref QCPColorGradient.
  22459. The colors defined by the gradient will be used to represent data values in the currently set
  22460. data range, see \ref setDataRange. Data points that are outside this data range will either be
  22461. colored uniformly with the respective gradient boundary color, or the gradient will repeat,
  22462. depending on \ref QCPColorGradient::setPeriodic.
  22463. \see QCPColorScale::setGradient
  22464. */
  22465. void QCPColorMap::setGradient(const QCPColorGradient &gradient)
  22466. {
  22467. if (mGradient != gradient)
  22468. {
  22469. mGradient = gradient;
  22470. mMapImageInvalidated = true;
  22471. emit gradientChanged(mGradient);
  22472. }
  22473. }
  22474. /*!
  22475. Sets whether the color map image shall use bicubic interpolation when displaying the color map
  22476. shrinked or expanded, and not at a 1:1 pixel-to-data scale.
  22477. \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled"
  22478. */
  22479. void QCPColorMap::setInterpolate(bool enabled)
  22480. {
  22481. mInterpolate = enabled;
  22482. mMapImageInvalidated = true; // because oversampling factors might need to change
  22483. }
  22484. /*!
  22485. Sets whether the outer most data rows and columns are clipped to the specified key and value
  22486. range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange).
  22487. if \a enabled is set to false, the data points at the border of the color map are drawn with the
  22488. same width and height as all other data points. Since the data points are represented by
  22489. rectangles of one color centered on the data coordinate, this means that the shown color map
  22490. extends by half a data point over the specified key/value range in each direction.
  22491. \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled"
  22492. */
  22493. void QCPColorMap::setTightBoundary(bool enabled)
  22494. {
  22495. mTightBoundary = enabled;
  22496. }
  22497. /*!
  22498. Associates the color scale \a colorScale with this color map.
  22499. This means that both the color scale and the color map synchronize their gradient, data range and
  22500. data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps
  22501. can be associated with one single color scale. This causes the color maps to also synchronize
  22502. those properties, via the mutual color scale.
  22503. This function causes the color map to adopt the current color gradient, data range and data scale
  22504. type of \a colorScale. After this call, you may change these properties at either the color map
  22505. or the color scale, and the setting will be applied to both.
  22506. Pass \c nullptr as \a colorScale to disconnect the color scale from this color map again.
  22507. */
  22508. void QCPColorMap::setColorScale(QCPColorScale *colorScale)
  22509. {
  22510. if (mColorScale) // unconnect signals from old color scale
  22511. {
  22512. disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
  22513. disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
  22514. disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
  22515. disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  22516. disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
  22517. disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  22518. }
  22519. mColorScale = colorScale;
  22520. if (mColorScale) // connect signals to new color scale
  22521. {
  22522. setGradient(mColorScale.data()->gradient());
  22523. setDataRange(mColorScale.data()->dataRange());
  22524. setDataScaleType(mColorScale.data()->dataScaleType());
  22525. connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
  22526. connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
  22527. connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
  22528. connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  22529. connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
  22530. connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  22531. }
  22532. }
  22533. /*!
  22534. Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the
  22535. current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods,
  22536. only for the third data dimension of the color map.
  22537. The minimum and maximum values of the data set are buffered in the internal QCPColorMapData
  22538. instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref
  22539. QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For
  22540. performance reasons, however, they are only updated in an expanding fashion. So the buffered
  22541. maximum can only increase and the buffered minimum can only decrease. In consequence, changes to
  22542. the data that actually lower the maximum of the data set (by overwriting the cell holding the
  22543. current maximum with a smaller value), aren't recognized and the buffered maximum overestimates
  22544. the true maximum of the data set. The same happens for the buffered minimum. To recalculate the
  22545. true minimum and maximum by explicitly looking at each cell, the method
  22546. QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a
  22547. recalculateDataBounds calls this method before setting the data range to the buffered minimum and
  22548. maximum.
  22549. \see setDataRange
  22550. */
  22551. void QCPColorMap::rescaleDataRange(bool recalculateDataBounds)
  22552. {
  22553. if (recalculateDataBounds)
  22554. mMapData->recalculateDataBounds();
  22555. setDataRange(mMapData->dataBounds());
  22556. }
  22557. /*!
  22558. Takes the current appearance of the color map and updates the legend icon, which is used to
  22559. represent this color map in the legend (see \ref QCPLegend).
  22560. The \a transformMode specifies whether the rescaling is done by a faster, low quality image
  22561. scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm
  22562. (Qt::SmoothTransformation).
  22563. The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to
  22564. the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured
  22565. legend icon size, the thumb will be rescaled during drawing of the legend item.
  22566. \see setDataRange
  22567. */
  22568. void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize)
  22569. {
  22570. if (mMapImage.isNull() && !data()->isEmpty())
  22571. updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet)
  22572. if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again
  22573. {
  22574. bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
  22575. bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
  22576. mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode);
  22577. }
  22578. }
  22579. /* inherits documentation from base class */
  22580. double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  22581. {
  22582. Q_UNUSED(details)
  22583. if ((onlySelectable && mSelectable == QCP::stNone) || mMapData->isEmpty())
  22584. return -1;
  22585. if (!mKeyAxis || !mValueAxis)
  22586. return -1;
  22587. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  22588. {
  22589. double posKey, posValue;
  22590. pixelsToCoords(pos, posKey, posValue);
  22591. if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue))
  22592. {
  22593. if (details)
  22594. details->setValue(QCPDataSelection(QCPDataRange(0, 1))); // temporary solution, to facilitate whole-plottable selection. Replace in future version with segmented 2D selection.
  22595. return mParentPlot->selectionTolerance()*0.99;
  22596. }
  22597. }
  22598. return -1;
  22599. }
  22600. /* inherits documentation from base class */
  22601. QCPRange QCPColorMap::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  22602. {
  22603. foundRange = true;
  22604. QCPRange result = mMapData->keyRange();
  22605. result.normalize();
  22606. if (inSignDomain == QCP::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::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. /* inherits documentation from base class */
  22622. QCPRange QCPColorMap::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  22623. {
  22624. if (inKeyRange != QCPRange())
  22625. {
  22626. if (mMapData->keyRange().upper < inKeyRange.lower || mMapData->keyRange().lower > inKeyRange.upper)
  22627. {
  22628. foundRange = false;
  22629. return {};
  22630. }
  22631. }
  22632. foundRange = true;
  22633. QCPRange result = mMapData->valueRange();
  22634. result.normalize();
  22635. if (inSignDomain == QCP::sdPositive)
  22636. {
  22637. if (result.lower <= 0 && result.upper > 0)
  22638. result.lower = result.upper*1e-3;
  22639. else if (result.lower <= 0 && result.upper <= 0)
  22640. foundRange = false;
  22641. } else if (inSignDomain == QCP::sdNegative)
  22642. {
  22643. if (result.upper >= 0 && result.lower < 0)
  22644. result.upper = result.lower*1e-3;
  22645. else if (result.upper >= 0 && result.lower >= 0)
  22646. foundRange = false;
  22647. }
  22648. return result;
  22649. }
  22650. /*! \internal
  22651. Updates the internal map image buffer by going through the internal \ref QCPColorMapData and
  22652. turning the data values into color pixels with \ref QCPColorGradient::colorize.
  22653. This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image
  22654. has been invalidated for a different reason (e.g. a change of the data range with \ref
  22655. setDataRange).
  22656. If the map cell count is low, the image created will be oversampled in order to avoid a
  22657. QPainter::drawImage bug which makes inner pixel boundaries jitter when stretch-drawing images
  22658. without smooth transform enabled. Accordingly, oversampling isn't performed if \ref
  22659. setInterpolate is true.
  22660. */
  22661. void QCPColorMap::updateMapImage()
  22662. {
  22663. QCPAxis *keyAxis = mKeyAxis.data();
  22664. if (!keyAxis) return;
  22665. if (mMapData->isEmpty()) return;
  22666. const QImage::Format format = QImage::Format_ARGB32_Premultiplied;
  22667. const int keySize = mMapData->keySize();
  22668. const int valueSize = mMapData->valueSize();
  22669. 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
  22670. 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
  22671. // resize mMapImage to correct dimensions including possible oversampling factors, according to key/value axes orientation:
  22672. if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.width() != keySize*keyOversamplingFactor || mMapImage.height() != valueSize*valueOversamplingFactor))
  22673. mMapImage = QImage(QSize(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor), format);
  22674. else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize*valueOversamplingFactor || mMapImage.height() != keySize*keyOversamplingFactor))
  22675. mMapImage = QImage(QSize(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor), format);
  22676. if (mMapImage.isNull())
  22677. {
  22678. qDebug() << Q_FUNC_INFO << "Couldn't create map image (possibly too large for memory)";
  22679. mMapImage = QImage(QSize(10, 10), format);
  22680. mMapImage.fill(Qt::black);
  22681. } else
  22682. {
  22683. QImage *localMapImage = &mMapImage; // this is the image on which the colorization operates. Either the final mMapImage, or if we need oversampling, mUndersampledMapImage
  22684. if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1)
  22685. {
  22686. // resize undersampled map image to actual key/value cell sizes:
  22687. if (keyAxis->orientation() == Qt::Horizontal && (mUndersampledMapImage.width() != keySize || mUndersampledMapImage.height() != valueSize))
  22688. mUndersampledMapImage = QImage(QSize(keySize, valueSize), format);
  22689. else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize))
  22690. mUndersampledMapImage = QImage(QSize(valueSize, keySize), format);
  22691. localMapImage = &mUndersampledMapImage; // make the colorization run on the undersampled image
  22692. } else if (!mUndersampledMapImage.isNull())
  22693. mUndersampledMapImage = QImage(); // don't need oversampling mechanism anymore (map size has changed) but mUndersampledMapImage still has nonzero size, free it
  22694. const double *rawData = mMapData->mData;
  22695. const unsigned char *rawAlpha = mMapData->mAlpha;
  22696. if (keyAxis->orientation() == Qt::Horizontal)
  22697. {
  22698. const int lineCount = valueSize;
  22699. const int rowCount = keySize;
  22700. for (int line=0; line<lineCount; ++line)
  22701. {
  22702. 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)
  22703. if (rawAlpha)
  22704. mGradient.colorize(rawData+line*rowCount, rawAlpha+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic);
  22705. else
  22706. mGradient.colorize(rawData+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic);
  22707. }
  22708. } else // keyAxis->orientation() == Qt::Vertical
  22709. {
  22710. const int lineCount = keySize;
  22711. const int rowCount = valueSize;
  22712. for (int line=0; line<lineCount; ++line)
  22713. {
  22714. 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)
  22715. if (rawAlpha)
  22716. mGradient.colorize(rawData+line, rawAlpha+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic);
  22717. else
  22718. mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic);
  22719. }
  22720. }
  22721. if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1)
  22722. {
  22723. if (keyAxis->orientation() == Qt::Horizontal)
  22724. mMapImage = mUndersampledMapImage.scaled(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation);
  22725. else
  22726. mMapImage = mUndersampledMapImage.scaled(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation);
  22727. }
  22728. }
  22729. mMapData->mDataModified = false;
  22730. mMapImageInvalidated = false;
  22731. }
  22732. /* inherits documentation from base class */
  22733. void QCPColorMap::draw(QCPPainter *painter)
  22734. {
  22735. if (mMapData->isEmpty()) return;
  22736. if (!mKeyAxis || !mValueAxis) return;
  22737. applyDefaultAntialiasingHint(painter);
  22738. if (mMapData->mDataModified || mMapImageInvalidated)
  22739. updateMapImage();
  22740. // use buffer if painting vectorized (PDF):
  22741. const bool useBuffer = painter->modes().testFlag(QCPPainter::pmVectorized);
  22742. QCPPainter *localPainter = painter; // will be redirected to paint on mapBuffer if painting vectorized
  22743. QRectF mapBufferTarget; // the rect in absolute widget coordinates where the visible map portion/buffer will end up in
  22744. QPixmap mapBuffer;
  22745. if (useBuffer)
  22746. {
  22747. const double mapBufferPixelRatio = 3; // factor by which DPI is increased in embedded bitmaps
  22748. mapBufferTarget = painter->clipRegion().boundingRect();
  22749. mapBuffer = QPixmap((mapBufferTarget.size()*mapBufferPixelRatio).toSize());
  22750. mapBuffer.fill(Qt::transparent);
  22751. localPainter = new QCPPainter(&mapBuffer);
  22752. localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio);
  22753. localPainter->translate(-mapBufferTarget.topLeft());
  22754. }
  22755. QRectF imageRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
  22756. coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized();
  22757. // extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are centered on map range boundary):
  22758. double halfCellWidth = 0; // in pixels
  22759. double halfCellHeight = 0; // in pixels
  22760. if (keyAxis()->orientation() == Qt::Horizontal)
  22761. {
  22762. if (mMapData->keySize() > 1)
  22763. halfCellWidth = 0.5*imageRect.width()/double(mMapData->keySize()-1);
  22764. if (mMapData->valueSize() > 1)
  22765. halfCellHeight = 0.5*imageRect.height()/double(mMapData->valueSize()-1);
  22766. } else // keyAxis orientation is Qt::Vertical
  22767. {
  22768. if (mMapData->keySize() > 1)
  22769. halfCellHeight = 0.5*imageRect.height()/double(mMapData->keySize()-1);
  22770. if (mMapData->valueSize() > 1)
  22771. halfCellWidth = 0.5*imageRect.width()/double(mMapData->valueSize()-1);
  22772. }
  22773. imageRect.adjust(-halfCellWidth, -halfCellHeight, halfCellWidth, halfCellHeight);
  22774. const bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
  22775. const bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
  22776. const bool smoothBackup = localPainter->renderHints().testFlag(QPainter::SmoothPixmapTransform);
  22777. localPainter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate);
  22778. QRegion clipBackup;
  22779. if (mTightBoundary)
  22780. {
  22781. clipBackup = localPainter->clipRegion();
  22782. QRectF tightClipRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
  22783. coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized();
  22784. localPainter->setClipRect(tightClipRect, Qt::IntersectClip);
  22785. }
  22786. localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY));
  22787. if (mTightBoundary)
  22788. localPainter->setClipRegion(clipBackup);
  22789. localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup);
  22790. if (useBuffer) // localPainter painted to mapBuffer, so now draw buffer with original painter
  22791. {
  22792. delete localPainter;
  22793. painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer);
  22794. }
  22795. }
  22796. /* inherits documentation from base class */
  22797. void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  22798. {
  22799. applyDefaultAntialiasingHint(painter);
  22800. // draw map thumbnail:
  22801. if (!mLegendIcon.isNull())
  22802. {
  22803. QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation);
  22804. QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height());
  22805. iconRect.moveCenter(rect.center());
  22806. painter->drawPixmap(iconRect.topLeft(), scaledIcon);
  22807. }
  22808. /*
  22809. // draw frame:
  22810. painter->setBrush(Qt::NoBrush);
  22811. painter->setPen(Qt::black);
  22812. painter->drawRect(rect.adjusted(1, 1, 0, 0));
  22813. */
  22814. }
  22815. /* end of 'src/plottables/plottable-colormap.cpp' */
  22816. /* including file 'src/plottables/plottable-financial.cpp' */
  22817. /* modified 2022-11-06T12:45:57, size 42914 */
  22818. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22819. //////////////////// QCPFinancialData
  22820. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22821. /*! \class QCPFinancialData
  22822. \brief Holds the data of one single data point for QCPFinancial.
  22823. The stored data is:
  22824. \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
  22825. \li \a open: The opening value at the data point (this is the \a mainValue)
  22826. \li \a high: The high/maximum value at the data point
  22827. \li \a low: The low/minimum value at the data point
  22828. \li \a close: The closing value at the data point
  22829. The container for storing multiple data points is \ref QCPFinancialDataContainer. It is a typedef
  22830. for \ref QCPDataContainer with \ref QCPFinancialData as the DataType template parameter. See the
  22831. documentation there for an explanation regarding the data type's generic methods.
  22832. \see QCPFinancialDataContainer
  22833. */
  22834. /* start documentation of inline functions */
  22835. /*! \fn double QCPFinancialData::sortKey() const
  22836. Returns the \a key member of this data point.
  22837. For a general explanation of what this method is good for in the context of the data container,
  22838. see the documentation of \ref QCPDataContainer.
  22839. */
  22840. /*! \fn static QCPFinancialData QCPFinancialData::fromSortKey(double sortKey)
  22841. Returns a data point with the specified \a sortKey. All other members are set to zero.
  22842. For a general explanation of what this method is good for in the context of the data container,
  22843. see the documentation of \ref QCPDataContainer.
  22844. */
  22845. /*! \fn static static bool QCPFinancialData::sortKeyIsMainKey()
  22846. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  22847. this method returns true.
  22848. For a general explanation of what this method is good for in the context of the data container,
  22849. see the documentation of \ref QCPDataContainer.
  22850. */
  22851. /*! \fn double QCPFinancialData::mainKey() const
  22852. Returns the \a key member of this data point.
  22853. For a general explanation of what this method is good for in the context of the data container,
  22854. see the documentation of \ref QCPDataContainer.
  22855. */
  22856. /*! \fn double QCPFinancialData::mainValue() const
  22857. Returns the \a open member of this data point.
  22858. For a general explanation of what this method is good for in the context of the data container,
  22859. see the documentation of \ref QCPDataContainer.
  22860. */
  22861. /*! \fn QCPRange QCPFinancialData::valueRange() const
  22862. Returns a QCPRange spanning from the \a low to the \a high value of this data point.
  22863. For a general explanation of what this method is good for in the context of the data container,
  22864. see the documentation of \ref QCPDataContainer.
  22865. */
  22866. /* end documentation of inline functions */
  22867. /*!
  22868. Constructs a data point with key and all values set to zero.
  22869. */
  22870. QCPFinancialData::QCPFinancialData() :
  22871. key(0),
  22872. open(0),
  22873. high(0),
  22874. low(0),
  22875. close(0)
  22876. {
  22877. }
  22878. /*!
  22879. Constructs a data point with the specified \a key and OHLC values.
  22880. */
  22881. QCPFinancialData::QCPFinancialData(double key, double open, double high, double low, double close) :
  22882. key(key),
  22883. open(open),
  22884. high(high),
  22885. low(low),
  22886. close(close)
  22887. {
  22888. }
  22889. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22890. //////////////////// QCPFinancial
  22891. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22892. /*! \class QCPFinancial
  22893. \brief A plottable representing a financial stock chart
  22894. \image html QCPFinancial.png
  22895. This plottable represents time series data binned to certain intervals, mainly used for stock
  22896. charts. The two common representations OHLC (Open-High-Low-Close) bars and Candlesticks can be
  22897. set via \ref setChartStyle.
  22898. The data is passed via \ref setData as a set of open/high/low/close values at certain keys
  22899. (typically times). This means the data must be already binned appropriately. If data is only
  22900. available as a series of values (e.g. \a price against \a time), you can use the static
  22901. convenience function \ref timeSeriesToOhlc to generate binned OHLC-data which can then be passed
  22902. to \ref setData.
  22903. The width of the OHLC bars/candlesticks can be controlled with \ref setWidth and \ref
  22904. setWidthType. A typical choice is to set the width type to \ref wtPlotCoords (the default) and
  22905. the width to (or slightly less than) one time bin interval width.
  22906. \section qcpfinancial-appearance Changing the appearance
  22907. Charts can be either single- or two-colored (\ref setTwoColored). If set to be single-colored,
  22908. lines are drawn with the plottable's pen (\ref setPen) and fills with the brush (\ref setBrush).
  22909. If set to two-colored, positive changes of the value during an interval (\a close >= \a open) are
  22910. represented with a different pen and brush than negative changes (\a close < \a open). These can
  22911. be configured with \ref setPenPositive, \ref setPenNegative, \ref setBrushPositive, and \ref
  22912. setBrushNegative. In two-colored mode, the normal plottable pen/brush is ignored. Upon selection
  22913. however, the normal selected pen/brush (provided by the \ref selectionDecorator) is used,
  22914. irrespective of whether the chart is single- or two-colored.
  22915. \section qcpfinancial-usage Usage
  22916. Like all data representing objects in QCustomPlot, the QCPFinancial is a plottable
  22917. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  22918. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  22919. Usually, you first create an instance:
  22920. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-creation-1
  22921. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot
  22922. instance takes ownership of the plottable, so do not delete it manually but use
  22923. QCustomPlot::removePlottable() instead. The newly created plottable can be modified, e.g.:
  22924. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-creation-2
  22925. Here we have used the static helper method \ref timeSeriesToOhlc, to turn a time-price data
  22926. series into a 24-hour binned open-high-low-close data series as QCPFinancial uses.
  22927. */
  22928. /* start of documentation of inline functions */
  22929. /*! \fn QCPFinancialDataContainer *QCPFinancial::data() const
  22930. Returns a pointer to the internal data storage of type \ref QCPFinancialDataContainer. You may
  22931. use it to directly manipulate the data, which may be more convenient and faster than using the
  22932. regular \ref setData or \ref addData methods, in certain situations.
  22933. */
  22934. /* end of documentation of inline functions */
  22935. /*!
  22936. Constructs a financial chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  22937. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  22938. the same orientation. If either of these restrictions is violated, a corresponding message is
  22939. printed to the debug output (qDebug), the construction is not aborted, though.
  22940. The created QCPFinancial is automatically registered with the QCustomPlot instance inferred from \a
  22941. keyAxis. This QCustomPlot instance takes ownership of the QCPFinancial, so do not delete it manually
  22942. but use QCustomPlot::removePlottable() instead.
  22943. */
  22944. QCPFinancial::QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  22945. QCPAbstractPlottable1D<QCPFinancialData>(keyAxis, valueAxis),
  22946. mChartStyle(csCandlestick),
  22947. mWidth(0.5),
  22948. mWidthType(wtPlotCoords),
  22949. mTwoColored(true),
  22950. mBrushPositive(QBrush(QColor(50, 160, 0))),
  22951. mBrushNegative(QBrush(QColor(180, 0, 15))),
  22952. mPenPositive(QPen(QColor(40, 150, 0))),
  22953. mPenNegative(QPen(QColor(170, 5, 5)))
  22954. {
  22955. mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255)));
  22956. }
  22957. QCPFinancial::~QCPFinancial()
  22958. {
  22959. }
  22960. /*! \overload
  22961. Replaces the current data container with the provided \a data container.
  22962. Since a QSharedPointer is used, multiple QCPFinancials may share the same data container safely.
  22963. Modifying the data in the container will then affect all financials that share the container.
  22964. Sharing can be achieved by simply exchanging the data containers wrapped in shared pointers:
  22965. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-datasharing-1
  22966. If you do not wish to share containers, but create a copy from an existing container, rather use
  22967. the \ref QCPDataContainer<DataType>::set method on the financial's data container directly:
  22968. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-datasharing-2
  22969. \see addData, timeSeriesToOhlc
  22970. */
  22971. void QCPFinancial::setData(QSharedPointer<QCPFinancialDataContainer> data)
  22972. {
  22973. mDataContainer = data;
  22974. }
  22975. /*! \overload
  22976. Replaces the current data with the provided points in \a keys, \a open, \a high, \a low and \a
  22977. close. The provided vectors should have equal length. Else, the number of added points will be
  22978. the size of the smallest vector.
  22979. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  22980. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  22981. \see addData, timeSeriesToOhlc
  22982. */
  22983. 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)
  22984. {
  22985. mDataContainer->clear();
  22986. addData(keys, open, high, low, close, alreadySorted);
  22987. }
  22988. /*!
  22989. Sets which representation style shall be used to display the OHLC data.
  22990. */
  22991. void QCPFinancial::setChartStyle(QCPFinancial::ChartStyle style)
  22992. {
  22993. mChartStyle = style;
  22994. }
  22995. /*!
  22996. Sets the width of the individual bars/candlesticks to \a width in plot key coordinates.
  22997. A typical choice is to set it to (or slightly less than) one bin interval width.
  22998. */
  22999. void QCPFinancial::setWidth(double width)
  23000. {
  23001. mWidth = width;
  23002. }
  23003. /*!
  23004. Sets how the width of the financial bars is defined. See the documentation of \ref WidthType for
  23005. an explanation of the possible values for \a widthType.
  23006. The default value is \ref wtPlotCoords.
  23007. \see setWidth
  23008. */
  23009. void QCPFinancial::setWidthType(QCPFinancial::WidthType widthType)
  23010. {
  23011. mWidthType = widthType;
  23012. }
  23013. /*!
  23014. Sets whether this chart shall contrast positive from negative trends per data point by using two
  23015. separate colors to draw the respective bars/candlesticks.
  23016. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  23017. setBrush).
  23018. \see setPenPositive, setPenNegative, setBrushPositive, setBrushNegative
  23019. */
  23020. void QCPFinancial::setTwoColored(bool twoColored)
  23021. {
  23022. mTwoColored = twoColored;
  23023. }
  23024. /*!
  23025. If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
  23026. of data points with a positive trend (i.e. bars/candlesticks with close >= open).
  23027. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  23028. setBrush).
  23029. \see setBrushNegative, setPenPositive, setPenNegative
  23030. */
  23031. void QCPFinancial::setBrushPositive(const QBrush &brush)
  23032. {
  23033. mBrushPositive = brush;
  23034. }
  23035. /*!
  23036. If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
  23037. of data points with a negative trend (i.e. bars/candlesticks with close < open).
  23038. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  23039. setBrush).
  23040. \see setBrushPositive, setPenNegative, setPenPositive
  23041. */
  23042. void QCPFinancial::setBrushNegative(const QBrush &brush)
  23043. {
  23044. mBrushNegative = brush;
  23045. }
  23046. /*!
  23047. If \ref setTwoColored is set to true, this function controls the pen that is used to draw
  23048. outlines of data points with a positive trend (i.e. bars/candlesticks with close >= open).
  23049. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  23050. setBrush).
  23051. \see setPenNegative, setBrushPositive, setBrushNegative
  23052. */
  23053. void QCPFinancial::setPenPositive(const QPen &pen)
  23054. {
  23055. mPenPositive = pen;
  23056. }
  23057. /*!
  23058. If \ref setTwoColored is set to true, this function controls the pen that is used to draw
  23059. outlines of data points with a negative trend (i.e. bars/candlesticks with close < open).
  23060. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  23061. setBrush).
  23062. \see setPenPositive, setBrushNegative, setBrushPositive
  23063. */
  23064. void QCPFinancial::setPenNegative(const QPen &pen)
  23065. {
  23066. mPenNegative = pen;
  23067. }
  23068. /*! \overload
  23069. Adds the provided points in \a keys, \a open, \a high, \a low and \a close to the current data.
  23070. The provided vectors should have equal length. Else, the number of added points will be the size
  23071. of the smallest vector.
  23072. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  23073. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  23074. Alternatively, you can also access and modify the data directly via the \ref data method, which
  23075. returns a pointer to the internal data container.
  23076. \see timeSeriesToOhlc
  23077. */
  23078. 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)
  23079. {
  23080. if (keys.size() != open.size() || open.size() != high.size() || high.size() != low.size() || low.size() != close.size() || close.size() != keys.size())
  23081. qDebug() << Q_FUNC_INFO << "keys, open, high, low, close have different sizes:" << keys.size() << open.size() << high.size() << low.size() << close.size();
  23082. const int n = qMin(keys.size(), qMin(open.size(), qMin(high.size(), qMin(low.size(), close.size()))));
  23083. QVector<QCPFinancialData> tempData(n);
  23084. QVector<QCPFinancialData>::iterator it = tempData.begin();
  23085. const QVector<QCPFinancialData>::iterator itEnd = tempData.end();
  23086. int i = 0;
  23087. while (it != itEnd)
  23088. {
  23089. it->key = keys[i];
  23090. it->open = open[i];
  23091. it->high = high[i];
  23092. it->low = low[i];
  23093. it->close = close[i];
  23094. ++it;
  23095. ++i;
  23096. }
  23097. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  23098. }
  23099. /*! \overload
  23100. Adds the provided data point as \a key, \a open, \a high, \a low and \a close to the current
  23101. data.
  23102. Alternatively, you can also access and modify the data directly via the \ref data method, which
  23103. returns a pointer to the internal data container.
  23104. \see timeSeriesToOhlc
  23105. */
  23106. void QCPFinancial::addData(double key, double open, double high, double low, double close)
  23107. {
  23108. mDataContainer->add(QCPFinancialData(key, open, high, low, close));
  23109. }
  23110. /*!
  23111. \copydoc QCPPlottableInterface1D::selectTestRect
  23112. */
  23113. QCPDataSelection QCPFinancial::selectTestRect(const QRectF &rect, bool onlySelectable) const
  23114. {
  23115. QCPDataSelection result;
  23116. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  23117. return result;
  23118. if (!mKeyAxis || !mValueAxis)
  23119. return result;
  23120. QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
  23121. getVisibleDataBounds(visibleBegin, visibleEnd);
  23122. for (QCPFinancialDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  23123. {
  23124. if (rect.intersects(selectionHitBox(it)))
  23125. result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
  23126. }
  23127. result.simplify();
  23128. return result;
  23129. }
  23130. /*!
  23131. Implements a selectTest specific to this plottable's point geometry.
  23132. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  23133. point to \a pos.
  23134. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  23135. */
  23136. double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  23137. {
  23138. Q_UNUSED(details)
  23139. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  23140. return -1;
  23141. if (!mKeyAxis || !mValueAxis)
  23142. return -1;
  23143. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  23144. {
  23145. // get visible data range:
  23146. QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
  23147. QCPFinancialDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  23148. getVisibleDataBounds(visibleBegin, visibleEnd);
  23149. // perform select test according to configured style:
  23150. double result = -1;
  23151. switch (mChartStyle)
  23152. {
  23153. case QCPFinancial::csOhlc:
  23154. result = ohlcSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break;
  23155. case QCPFinancial::csCandlestick:
  23156. result = candlestickSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break;
  23157. }
  23158. if (details)
  23159. {
  23160. int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
  23161. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  23162. }
  23163. return result;
  23164. }
  23165. return -1;
  23166. }
  23167. /* inherits documentation from base class */
  23168. QCPRange QCPFinancial::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  23169. {
  23170. QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain);
  23171. // determine exact range by including width of bars/flags:
  23172. if (foundRange)
  23173. {
  23174. if (inSignDomain != QCP::sdPositive || range.lower-mWidth*0.5 > 0)
  23175. range.lower -= mWidth*0.5;
  23176. if (inSignDomain != QCP::sdNegative || range.upper+mWidth*0.5 < 0)
  23177. range.upper += mWidth*0.5;
  23178. }
  23179. return range;
  23180. }
  23181. /* inherits documentation from base class */
  23182. QCPRange QCPFinancial::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  23183. {
  23184. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  23185. }
  23186. /*!
  23187. A convenience function that converts time series data (\a value against \a time) to OHLC binned
  23188. data points. The return value can then be passed on to \ref QCPFinancialDataContainer::set(const
  23189. QCPFinancialDataContainer&).
  23190. The size of the bins can be controlled with \a timeBinSize in the same units as \a time is given.
  23191. For example, if the unit of \a time is seconds and single OHLC/Candlesticks should span an hour
  23192. each, set \a timeBinSize to 3600.
  23193. \a timeBinOffset allows to control precisely at what \a time coordinate a bin should start. The
  23194. value passed as \a timeBinOffset doesn't need to be in the range encompassed by the \a time keys.
  23195. It merely defines the mathematical offset/phase of the bins that will be used to process the
  23196. data.
  23197. */
  23198. QCPFinancialDataContainer QCPFinancial::timeSeriesToOhlc(const QVector<double> &time, const QVector<double> &value, double timeBinSize, double timeBinOffset)
  23199. {
  23200. QCPFinancialDataContainer data;
  23201. int count = qMin(time.size(), value.size());
  23202. if (count == 0)
  23203. return QCPFinancialDataContainer();
  23204. QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first());
  23205. int currentBinIndex = qFloor((time.first()-timeBinOffset)/timeBinSize+0.5);
  23206. for (int i=0; i<count; ++i)
  23207. {
  23208. int index = qFloor((time.at(i)-timeBinOffset)/timeBinSize+0.5);
  23209. if (currentBinIndex == index) // data point still in current bin, extend high/low:
  23210. {
  23211. if (value.at(i) < currentBinData.low) currentBinData.low = value.at(i);
  23212. if (value.at(i) > currentBinData.high) currentBinData.high = value.at(i);
  23213. if (i == count-1) // last data point is in current bin, finalize bin:
  23214. {
  23215. currentBinData.close = value.at(i);
  23216. currentBinData.key = timeBinOffset+(index)*timeBinSize;
  23217. data.add(currentBinData);
  23218. }
  23219. } else // data point not anymore in current bin, set close of old and open of new bin, and add old to map:
  23220. {
  23221. // finalize current bin:
  23222. currentBinData.close = value.at(i-1);
  23223. currentBinData.key = timeBinOffset+(index-1)*timeBinSize;
  23224. data.add(currentBinData);
  23225. // start next bin:
  23226. currentBinIndex = index;
  23227. currentBinData.open = value.at(i);
  23228. currentBinData.high = value.at(i);
  23229. currentBinData.low = value.at(i);
  23230. }
  23231. }
  23232. return data;
  23233. }
  23234. /* inherits documentation from base class */
  23235. void QCPFinancial::draw(QCPPainter *painter)
  23236. {
  23237. // get visible data range:
  23238. QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
  23239. getVisibleDataBounds(visibleBegin, visibleEnd);
  23240. // loop over and draw segments of unselected/selected data:
  23241. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  23242. getDataSegments(selectedSegments, unselectedSegments);
  23243. allSegments << unselectedSegments << selectedSegments;
  23244. for (int i=0; i<allSegments.size(); ++i)
  23245. {
  23246. bool isSelectedSegment = i >= unselectedSegments.size();
  23247. QCPFinancialDataContainer::const_iterator begin = visibleBegin;
  23248. QCPFinancialDataContainer::const_iterator end = visibleEnd;
  23249. mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
  23250. if (begin == end)
  23251. continue;
  23252. // draw data segment according to configured style:
  23253. switch (mChartStyle)
  23254. {
  23255. case QCPFinancial::csOhlc:
  23256. drawOhlcPlot(painter, begin, end, isSelectedSegment); break;
  23257. case QCPFinancial::csCandlestick:
  23258. drawCandlestickPlot(painter, begin, end, isSelectedSegment); break;
  23259. }
  23260. }
  23261. // draw other selection decoration that isn't just line/scatter pens and brushes:
  23262. if (mSelectionDecorator)
  23263. mSelectionDecorator->drawDecoration(painter, selection());
  23264. }
  23265. /* inherits documentation from base class */
  23266. void QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  23267. {
  23268. painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing
  23269. if (mChartStyle == csOhlc)
  23270. {
  23271. if (mTwoColored)
  23272. {
  23273. // draw upper left half icon with positive color:
  23274. painter->setBrush(mBrushPositive);
  23275. painter->setPen(mPenPositive);
  23276. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint()));
  23277. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23278. painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
  23279. painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
  23280. // draw bottom right half icon with negative color:
  23281. painter->setBrush(mBrushNegative);
  23282. painter->setPen(mPenNegative);
  23283. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint()));
  23284. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23285. painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
  23286. painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
  23287. } else
  23288. {
  23289. painter->setBrush(mBrush);
  23290. painter->setPen(mPen);
  23291. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23292. painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
  23293. painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
  23294. }
  23295. } else if (mChartStyle == csCandlestick)
  23296. {
  23297. if (mTwoColored)
  23298. {
  23299. // draw upper left half icon with positive color:
  23300. painter->setBrush(mBrushPositive);
  23301. painter->setPen(mPenPositive);
  23302. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint()));
  23303. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
  23304. painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23305. painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
  23306. // draw bottom right half icon with negative color:
  23307. painter->setBrush(mBrushNegative);
  23308. painter->setPen(mPenNegative);
  23309. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint()));
  23310. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
  23311. painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23312. painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
  23313. } else
  23314. {
  23315. painter->setBrush(mBrush);
  23316. painter->setPen(mPen);
  23317. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
  23318. painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23319. painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
  23320. }
  23321. }
  23322. }
  23323. /*! \internal
  23324. Draws the data from \a begin to \a end-1 as OHLC bars with the provided \a painter.
  23325. This method is a helper function for \ref draw. It is used when the chart style is \ref csOhlc.
  23326. */
  23327. void QCPFinancial::drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected)
  23328. {
  23329. QCPAxis *keyAxis = mKeyAxis.data();
  23330. QCPAxis *valueAxis = mValueAxis.data();
  23331. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  23332. if (keyAxis->orientation() == Qt::Horizontal)
  23333. {
  23334. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  23335. {
  23336. if (isSelected && mSelectionDecorator)
  23337. mSelectionDecorator->applyPen(painter);
  23338. else if (mTwoColored)
  23339. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  23340. else
  23341. painter->setPen(mPen);
  23342. double keyPixel = keyAxis->coordToPixel(it->key);
  23343. double openPixel = valueAxis->coordToPixel(it->open);
  23344. double closePixel = valueAxis->coordToPixel(it->close);
  23345. // draw backbone:
  23346. painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(it->low)));
  23347. // draw open:
  23348. double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides
  23349. painter->drawLine(QPointF(keyPixel-pixelWidth, openPixel), QPointF(keyPixel, openPixel));
  23350. // draw close:
  23351. painter->drawLine(QPointF(keyPixel, closePixel), QPointF(keyPixel+pixelWidth, closePixel));
  23352. }
  23353. } else
  23354. {
  23355. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  23356. {
  23357. if (isSelected && mSelectionDecorator)
  23358. mSelectionDecorator->applyPen(painter);
  23359. else if (mTwoColored)
  23360. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  23361. else
  23362. painter->setPen(mPen);
  23363. double keyPixel = keyAxis->coordToPixel(it->key);
  23364. double openPixel = valueAxis->coordToPixel(it->open);
  23365. double closePixel = valueAxis->coordToPixel(it->close);
  23366. // draw backbone:
  23367. painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(it->low), keyPixel));
  23368. // draw open:
  23369. double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides
  23370. painter->drawLine(QPointF(openPixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel));
  23371. // draw close:
  23372. painter->drawLine(QPointF(closePixel, keyPixel), QPointF(closePixel, keyPixel+pixelWidth));
  23373. }
  23374. }
  23375. }
  23376. /*! \internal
  23377. Draws the data from \a begin to \a end-1 as Candlesticks with the provided \a painter.
  23378. This method is a helper function for \ref draw. It is used when the chart style is \ref csCandlestick.
  23379. */
  23380. void QCPFinancial::drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected)
  23381. {
  23382. QCPAxis *keyAxis = mKeyAxis.data();
  23383. QCPAxis *valueAxis = mValueAxis.data();
  23384. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  23385. if (keyAxis->orientation() == Qt::Horizontal)
  23386. {
  23387. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  23388. {
  23389. if (isSelected && mSelectionDecorator)
  23390. {
  23391. mSelectionDecorator->applyPen(painter);
  23392. mSelectionDecorator->applyBrush(painter);
  23393. } else if (mTwoColored)
  23394. {
  23395. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  23396. painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative);
  23397. } else
  23398. {
  23399. painter->setPen(mPen);
  23400. painter->setBrush(mBrush);
  23401. }
  23402. double keyPixel = keyAxis->coordToPixel(it->key);
  23403. double openPixel = valueAxis->coordToPixel(it->open);
  23404. double closePixel = valueAxis->coordToPixel(it->close);
  23405. // draw high:
  23406. painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close))));
  23407. // draw low:
  23408. painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close))));
  23409. // draw open-close box:
  23410. double pixelWidth = getPixelWidth(it->key, keyPixel);
  23411. painter->drawRect(QRectF(QPointF(keyPixel-pixelWidth, closePixel), QPointF(keyPixel+pixelWidth, openPixel)));
  23412. }
  23413. } else // keyAxis->orientation() == Qt::Vertical
  23414. {
  23415. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  23416. {
  23417. if (isSelected && mSelectionDecorator)
  23418. {
  23419. mSelectionDecorator->applyPen(painter);
  23420. mSelectionDecorator->applyBrush(painter);
  23421. } else if (mTwoColored)
  23422. {
  23423. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  23424. painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative);
  23425. } else
  23426. {
  23427. painter->setPen(mPen);
  23428. painter->setBrush(mBrush);
  23429. }
  23430. double keyPixel = keyAxis->coordToPixel(it->key);
  23431. double openPixel = valueAxis->coordToPixel(it->open);
  23432. double closePixel = valueAxis->coordToPixel(it->close);
  23433. // draw high:
  23434. painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel));
  23435. // draw low:
  23436. painter->drawLine(QPointF(valueAxis->coordToPixel(it->low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel));
  23437. // draw open-close box:
  23438. double pixelWidth = getPixelWidth(it->key, keyPixel);
  23439. painter->drawRect(QRectF(QPointF(closePixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel+pixelWidth)));
  23440. }
  23441. }
  23442. }
  23443. /*! \internal
  23444. This function is used to determine the width of the bar at coordinate \a key, according to the
  23445. specified width (\ref setWidth) and width type (\ref setWidthType). Provide the pixel position of
  23446. \a key in \a keyPixel (because usually this was already calculated via \ref QCPAxis::coordToPixel
  23447. when this function is called).
  23448. It returns the number of pixels the bar extends to higher keys, relative to the \a key
  23449. coordinate. So with a non-reversed horizontal axis, the return value is positive. With a reversed
  23450. horizontal axis, the return value is negative. This is important so the open/close flags on the
  23451. \ref csOhlc bar are drawn to the correct side.
  23452. */
  23453. double QCPFinancial::getPixelWidth(double key, double keyPixel) const
  23454. {
  23455. double result = 0;
  23456. switch (mWidthType)
  23457. {
  23458. case wtAbsolute:
  23459. {
  23460. if (mKeyAxis)
  23461. result = mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  23462. break;
  23463. }
  23464. case wtAxisRectRatio:
  23465. {
  23466. if (mKeyAxis && mKeyAxis.data()->axisRect())
  23467. {
  23468. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  23469. result = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  23470. else
  23471. result = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  23472. } else
  23473. qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined";
  23474. break;
  23475. }
  23476. case wtPlotCoords:
  23477. {
  23478. if (mKeyAxis)
  23479. result = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel;
  23480. else
  23481. qDebug() << Q_FUNC_INFO << "No key axis defined";
  23482. break;
  23483. }
  23484. }
  23485. return result;
  23486. }
  23487. /*! \internal
  23488. This method is a helper function for \ref selectTest. It is used to test for selection when the
  23489. chart style is \ref csOhlc. It only tests against the data points between \a begin and \a end.
  23490. Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical
  23491. representation of the plottable, and \a closestDataPoint will point to the respective data point.
  23492. */
  23493. double QCPFinancial::ohlcSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const
  23494. {
  23495. closestDataPoint = mDataContainer->constEnd();
  23496. QCPAxis *keyAxis = mKeyAxis.data();
  23497. QCPAxis *valueAxis = mValueAxis.data();
  23498. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  23499. double minDistSqr = (std::numeric_limits<double>::max)();
  23500. if (keyAxis->orientation() == Qt::Horizontal)
  23501. {
  23502. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  23503. {
  23504. double keyPixel = keyAxis->coordToPixel(it->key);
  23505. // calculate distance to backbone:
  23506. double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low)));
  23507. if (currentDistSqr < minDistSqr)
  23508. {
  23509. minDistSqr = currentDistSqr;
  23510. closestDataPoint = it;
  23511. }
  23512. }
  23513. } else // keyAxis->orientation() == Qt::Vertical
  23514. {
  23515. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  23516. {
  23517. double keyPixel = keyAxis->coordToPixel(it->key);
  23518. // calculate distance to backbone:
  23519. double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel));
  23520. if (currentDistSqr < minDistSqr)
  23521. {
  23522. minDistSqr = currentDistSqr;
  23523. closestDataPoint = it;
  23524. }
  23525. }
  23526. }
  23527. return qSqrt(minDistSqr);
  23528. }
  23529. /*! \internal
  23530. This method is a helper function for \ref selectTest. It is used to test for selection when the
  23531. chart style is \ref csCandlestick. It only tests against the data points between \a begin and \a
  23532. end.
  23533. Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical
  23534. representation of the plottable, and \a closestDataPoint will point to the respective data point.
  23535. */
  23536. double QCPFinancial::candlestickSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const
  23537. {
  23538. closestDataPoint = mDataContainer->constEnd();
  23539. QCPAxis *keyAxis = mKeyAxis.data();
  23540. QCPAxis *valueAxis = mValueAxis.data();
  23541. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  23542. double minDistSqr = (std::numeric_limits<double>::max)();
  23543. if (keyAxis->orientation() == Qt::Horizontal)
  23544. {
  23545. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  23546. {
  23547. double currentDistSqr;
  23548. // determine whether pos is in open-close-box:
  23549. QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5);
  23550. QCPRange boxValueRange(it->close, it->open);
  23551. double posKey, posValue;
  23552. pixelsToCoords(pos, posKey, posValue);
  23553. if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box
  23554. {
  23555. currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
  23556. } else
  23557. {
  23558. // calculate distance to high/low lines:
  23559. double keyPixel = keyAxis->coordToPixel(it->key);
  23560. double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close))));
  23561. double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close))));
  23562. currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
  23563. }
  23564. if (currentDistSqr < minDistSqr)
  23565. {
  23566. minDistSqr = currentDistSqr;
  23567. closestDataPoint = it;
  23568. }
  23569. }
  23570. } else // keyAxis->orientation() == Qt::Vertical
  23571. {
  23572. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  23573. {
  23574. double currentDistSqr;
  23575. // determine whether pos is in open-close-box:
  23576. QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5);
  23577. QCPRange boxValueRange(it->close, it->open);
  23578. double posKey, posValue;
  23579. pixelsToCoords(pos, posKey, posValue);
  23580. if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box
  23581. {
  23582. currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
  23583. } else
  23584. {
  23585. // calculate distance to high/low lines:
  23586. double keyPixel = keyAxis->coordToPixel(it->key);
  23587. double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel));
  23588. double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel));
  23589. currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
  23590. }
  23591. if (currentDistSqr < minDistSqr)
  23592. {
  23593. minDistSqr = currentDistSqr;
  23594. closestDataPoint = it;
  23595. }
  23596. }
  23597. }
  23598. return qSqrt(minDistSqr);
  23599. }
  23600. /*! \internal
  23601. called by the drawing methods to determine which data (key) range is visible at the current key
  23602. axis range setting, so only that needs to be processed.
  23603. \a begin returns an iterator to the lowest data point that needs to be taken into account when
  23604. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  23605. begin may still be just outside the visible range.
  23606. \a end returns the iterator just above the highest data point that needs to be taken into
  23607. account. Same as before, \a end may also lie just outside of the visible range
  23608. if the plottable contains no data, both \a begin and \a end point to \c constEnd.
  23609. */
  23610. void QCPFinancial::getVisibleDataBounds(QCPFinancialDataContainer::const_iterator &begin, QCPFinancialDataContainer::const_iterator &end) const
  23611. {
  23612. if (!mKeyAxis)
  23613. {
  23614. qDebug() << Q_FUNC_INFO << "invalid key axis";
  23615. begin = mDataContainer->constEnd();
  23616. end = mDataContainer->constEnd();
  23617. return;
  23618. }
  23619. begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of ohlc/candlestick to include partially visible data points
  23620. end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of ohlc/candlestick to include partially visible data points
  23621. }
  23622. /*! \internal
  23623. Returns the hit box in pixel coordinates that will be used for data selection with the selection
  23624. rect (\ref selectTestRect), of the data point given by \a it.
  23625. */
  23626. QRectF QCPFinancial::selectionHitBox(QCPFinancialDataContainer::const_iterator it) const
  23627. {
  23628. QCPAxis *keyAxis = mKeyAxis.data();
  23629. QCPAxis *valueAxis = mValueAxis.data();
  23630. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
  23631. double keyPixel = keyAxis->coordToPixel(it->key);
  23632. double highPixel = valueAxis->coordToPixel(it->high);
  23633. double lowPixel = valueAxis->coordToPixel(it->low);
  23634. double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it->key-mWidth*0.5);
  23635. if (keyAxis->orientation() == Qt::Horizontal)
  23636. return QRectF(keyPixel-keyWidthPixels, highPixel, keyWidthPixels*2, lowPixel-highPixel).normalized();
  23637. else
  23638. return QRectF(highPixel, keyPixel-keyWidthPixels, lowPixel-highPixel, keyWidthPixels*2).normalized();
  23639. }
  23640. /* end of 'src/plottables/plottable-financial.cpp' */
  23641. /* including file 'src/plottables/plottable-errorbar.cpp' */
  23642. /* modified 2022-11-06T12:45:56, size 37679 */
  23643. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23644. //////////////////// QCPErrorBarsData
  23645. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23646. /*! \class QCPErrorBarsData
  23647. \brief Holds the data of one single error bar for QCPErrorBars.
  23648. The stored data is:
  23649. \li \a errorMinus: how much the error bar extends towards negative coordinates from the data
  23650. point position
  23651. \li \a errorPlus: how much the error bar extends towards positive coordinates from the data point
  23652. position
  23653. The container for storing the error bar information is \ref QCPErrorBarsDataContainer. It is a
  23654. typedef for <tt>QVector<\ref QCPErrorBarsData></tt>.
  23655. \see QCPErrorBarsDataContainer
  23656. */
  23657. /*!
  23658. Constructs an error bar with errors set to zero.
  23659. */
  23660. QCPErrorBarsData::QCPErrorBarsData() :
  23661. errorMinus(0),
  23662. errorPlus(0)
  23663. {
  23664. }
  23665. /*!
  23666. Constructs an error bar with equal \a error in both negative and positive direction.
  23667. */
  23668. QCPErrorBarsData::QCPErrorBarsData(double error) :
  23669. errorMinus(error),
  23670. errorPlus(error)
  23671. {
  23672. }
  23673. /*!
  23674. Constructs an error bar with negative and positive errors set to \a errorMinus and \a errorPlus,
  23675. respectively.
  23676. */
  23677. QCPErrorBarsData::QCPErrorBarsData(double errorMinus, double errorPlus) :
  23678. errorMinus(errorMinus),
  23679. errorPlus(errorPlus)
  23680. {
  23681. }
  23682. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23683. //////////////////// QCPErrorBars
  23684. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23685. /*! \class QCPErrorBars
  23686. \brief A plottable that adds a set of error bars to other plottables.
  23687. \image html QCPErrorBars.png
  23688. The \ref QCPErrorBars plottable can be attached to other one-dimensional plottables (e.g. \ref
  23689. QCPGraph, \ref QCPCurve, \ref QCPBars, etc.) and equips them with error bars.
  23690. Use \ref setDataPlottable to define for which plottable the \ref QCPErrorBars shall display the
  23691. error bars. The orientation of the error bars can be controlled with \ref setErrorType.
  23692. By using \ref setData, you can supply the actual error data, either as symmetric error or
  23693. plus/minus asymmetric errors. \ref QCPErrorBars only stores the error data. The absolute
  23694. key/value position of each error bar will be adopted from the configured data plottable. The
  23695. error data of the \ref QCPErrorBars are associated one-to-one via their index to the data points
  23696. of the data plottable. You can directly access and manipulate the error bar data via \ref data.
  23697. Set either of the plus/minus errors to NaN (<tt>qQNaN()</tt> or
  23698. <tt>std::numeric_limits<double>::quiet_NaN()</tt>) to not show the respective error bar on the data point at
  23699. that index.
  23700. \section qcperrorbars-appearance Changing the appearance
  23701. The appearance of the error bars is defined by the pen (\ref setPen), and the width of the
  23702. whiskers (\ref setWhiskerWidth). Further, the error bar backbones may leave a gap around the data
  23703. point center to prevent that error bars are drawn too close to or even through scatter points.
  23704. This gap size can be controlled via \ref setSymbolGap.
  23705. */
  23706. /* start of documentation of inline functions */
  23707. /*! \fn QSharedPointer<QCPErrorBarsDataContainer> QCPErrorBars::data() const
  23708. Returns a shared pointer to the internal data storage of type \ref QCPErrorBarsDataContainer. You
  23709. may use it to directly manipulate the error values, which may be more convenient and faster than
  23710. using the regular \ref setData methods.
  23711. */
  23712. /* end of documentation of inline functions */
  23713. /*!
  23714. Constructs an error bars plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  23715. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  23716. the same orientation. If either of these restrictions is violated, a corresponding message is
  23717. printed to the debug output (qDebug), the construction is not aborted, though.
  23718. It is also important that the \a keyAxis and \a valueAxis are the same for the error bars
  23719. plottable and the data plottable that the error bars shall be drawn on (\ref setDataPlottable).
  23720. The created \ref QCPErrorBars is automatically registered with the QCustomPlot instance inferred
  23721. from \a keyAxis. This QCustomPlot instance takes ownership of the \ref QCPErrorBars, so do not
  23722. delete it manually but use \ref QCustomPlot::removePlottable() instead.
  23723. */
  23724. QCPErrorBars::QCPErrorBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  23725. QCPAbstractPlottable(keyAxis, valueAxis),
  23726. mDataContainer(new QVector<QCPErrorBarsData>),
  23727. mErrorType(etValueError),
  23728. mWhiskerWidth(9),
  23729. mSymbolGap(10)
  23730. {
  23731. setPen(QPen(Qt::black, 0));
  23732. setBrush(Qt::NoBrush);
  23733. }
  23734. QCPErrorBars::~QCPErrorBars()
  23735. {
  23736. }
  23737. /*! \overload
  23738. Replaces the current data container with the provided \a data container.
  23739. Since a QSharedPointer is used, multiple \ref QCPErrorBars instances may share the same data
  23740. container safely. Modifying the data in the container will then affect all \ref QCPErrorBars
  23741. instances that share the container. Sharing can be achieved by simply exchanging the data
  23742. containers wrapped in shared pointers:
  23743. \snippet documentation/doc-code-snippets/mainwindow.cpp qcperrorbars-datasharing-1
  23744. If you do not wish to share containers, but create a copy from an existing container, assign the
  23745. data containers directly:
  23746. \snippet documentation/doc-code-snippets/mainwindow.cpp qcperrorbars-datasharing-2
  23747. (This uses different notation compared with other plottables, because the \ref QCPErrorBars
  23748. uses a \c QVector<QCPErrorBarsData> as its data container, instead of a \ref QCPDataContainer.)
  23749. \see addData
  23750. */
  23751. void QCPErrorBars::setData(QSharedPointer<QCPErrorBarsDataContainer> data)
  23752. {
  23753. mDataContainer = data;
  23754. }
  23755. /*! \overload
  23756. Sets symmetrical error values as specified in \a error. The errors will be associated one-to-one
  23757. by the data point index to the associated data plottable (\ref setDataPlottable).
  23758. You can directly access and manipulate the error bar data via \ref data.
  23759. \see addData
  23760. */
  23761. void QCPErrorBars::setData(const QVector<double> &error)
  23762. {
  23763. mDataContainer->clear();
  23764. addData(error);
  23765. }
  23766. /*! \overload
  23767. Sets asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be
  23768. associated one-to-one by the data point index to the associated data plottable (\ref
  23769. setDataPlottable).
  23770. You can directly access and manipulate the error bar data via \ref data.
  23771. \see addData
  23772. */
  23773. void QCPErrorBars::setData(const QVector<double> &errorMinus, const QVector<double> &errorPlus)
  23774. {
  23775. mDataContainer->clear();
  23776. addData(errorMinus, errorPlus);
  23777. }
  23778. /*!
  23779. Sets the data plottable to which the error bars will be applied. The error values specified e.g.
  23780. via \ref setData will be associated one-to-one by the data point index to the data points of \a
  23781. plottable. This means that the error bars will adopt the key/value coordinates of the data point
  23782. with the same index.
  23783. The passed \a plottable must be a one-dimensional plottable, i.e. it must implement the \ref
  23784. QCPPlottableInterface1D. Further, it must not be a \ref QCPErrorBars instance itself. If either
  23785. of these restrictions is violated, a corresponding qDebug output is generated, and the data
  23786. plottable of this \ref QCPErrorBars instance is set to zero.
  23787. For proper display, care must also be taken that the key and value axes of the \a plottable match
  23788. those configured for this \ref QCPErrorBars instance.
  23789. */
  23790. void QCPErrorBars::setDataPlottable(QCPAbstractPlottable *plottable)
  23791. {
  23792. if (plottable && qobject_cast<QCPErrorBars*>(plottable))
  23793. {
  23794. mDataPlottable = nullptr;
  23795. qDebug() << Q_FUNC_INFO << "can't set another QCPErrorBars instance as data plottable";
  23796. return;
  23797. }
  23798. if (plottable && !plottable->interface1D())
  23799. {
  23800. mDataPlottable = nullptr;
  23801. qDebug() << Q_FUNC_INFO << "passed plottable doesn't implement 1d interface, can't associate with QCPErrorBars";
  23802. return;
  23803. }
  23804. mDataPlottable = plottable;
  23805. }
  23806. /*!
  23807. Sets in which orientation the error bars shall appear on the data points. If your data needs both
  23808. error dimensions, create two \ref QCPErrorBars with different \a type.
  23809. */
  23810. void QCPErrorBars::setErrorType(ErrorType type)
  23811. {
  23812. mErrorType = type;
  23813. }
  23814. /*!
  23815. Sets the width of the whiskers (the short bars at the end of the actual error bar backbones) to
  23816. \a pixels.
  23817. */
  23818. void QCPErrorBars::setWhiskerWidth(double pixels)
  23819. {
  23820. mWhiskerWidth = pixels;
  23821. }
  23822. /*!
  23823. Sets the gap diameter around the data points that will be left out when drawing the error bar
  23824. backbones. This gap prevents that error bars are drawn too close to or even through scatter
  23825. points.
  23826. */
  23827. void QCPErrorBars::setSymbolGap(double pixels)
  23828. {
  23829. mSymbolGap = pixels;
  23830. }
  23831. /*! \overload
  23832. Adds symmetrical error values as specified in \a error. The errors will be associated one-to-one
  23833. by the data point index to the associated data plottable (\ref setDataPlottable).
  23834. You can directly access and manipulate the error bar data via \ref data.
  23835. \see setData
  23836. */
  23837. void QCPErrorBars::addData(const QVector<double> &error)
  23838. {
  23839. addData(error, error);
  23840. }
  23841. /*! \overload
  23842. Adds asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be
  23843. associated one-to-one by the data point index to the associated data plottable (\ref
  23844. setDataPlottable).
  23845. You can directly access and manipulate the error bar data via \ref data.
  23846. \see setData
  23847. */
  23848. void QCPErrorBars::addData(const QVector<double> &errorMinus, const QVector<double> &errorPlus)
  23849. {
  23850. if (errorMinus.size() != errorPlus.size())
  23851. qDebug() << Q_FUNC_INFO << "minus and plus error vectors have different sizes:" << errorMinus.size() << errorPlus.size();
  23852. const int n = qMin(errorMinus.size(), errorPlus.size());
  23853. mDataContainer->reserve(n);
  23854. for (int i=0; i<n; ++i)
  23855. mDataContainer->append(QCPErrorBarsData(errorMinus.at(i), errorPlus.at(i)));
  23856. }
  23857. /*! \overload
  23858. Adds a single symmetrical error bar as specified in \a error. The errors will be associated
  23859. one-to-one by the data point index to the associated data plottable (\ref setDataPlottable).
  23860. You can directly access and manipulate the error bar data via \ref data.
  23861. \see setData
  23862. */
  23863. void QCPErrorBars::addData(double error)
  23864. {
  23865. mDataContainer->append(QCPErrorBarsData(error));
  23866. }
  23867. /*! \overload
  23868. Adds a single asymmetrical error bar as specified in \a errorMinus and \a errorPlus. The errors
  23869. will be associated one-to-one by the data point index to the associated data plottable (\ref
  23870. setDataPlottable).
  23871. You can directly access and manipulate the error bar data via \ref data.
  23872. \see setData
  23873. */
  23874. void QCPErrorBars::addData(double errorMinus, double errorPlus)
  23875. {
  23876. mDataContainer->append(QCPErrorBarsData(errorMinus, errorPlus));
  23877. }
  23878. /* inherits documentation from base class */
  23879. int QCPErrorBars::dataCount() const
  23880. {
  23881. return mDataContainer->size();
  23882. }
  23883. /* inherits documentation from base class */
  23884. double QCPErrorBars::dataMainKey(int index) const
  23885. {
  23886. if (mDataPlottable)
  23887. return mDataPlottable->interface1D()->dataMainKey(index);
  23888. else
  23889. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23890. return 0;
  23891. }
  23892. /* inherits documentation from base class */
  23893. double QCPErrorBars::dataSortKey(int index) const
  23894. {
  23895. if (mDataPlottable)
  23896. return mDataPlottable->interface1D()->dataSortKey(index);
  23897. else
  23898. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23899. return 0;
  23900. }
  23901. /* inherits documentation from base class */
  23902. double QCPErrorBars::dataMainValue(int index) const
  23903. {
  23904. if (mDataPlottable)
  23905. return mDataPlottable->interface1D()->dataMainValue(index);
  23906. else
  23907. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23908. return 0;
  23909. }
  23910. /* inherits documentation from base class */
  23911. QCPRange QCPErrorBars::dataValueRange(int index) const
  23912. {
  23913. if (mDataPlottable)
  23914. {
  23915. const double value = mDataPlottable->interface1D()->dataMainValue(index);
  23916. if (index >= 0 && index < mDataContainer->size() && mErrorType == etValueError)
  23917. return {value-mDataContainer->at(index).errorMinus, value+mDataContainer->at(index).errorPlus};
  23918. else
  23919. return {value, value};
  23920. } else
  23921. {
  23922. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23923. return {};
  23924. }
  23925. }
  23926. /* inherits documentation from base class */
  23927. QPointF QCPErrorBars::dataPixelPosition(int index) const
  23928. {
  23929. if (mDataPlottable)
  23930. return mDataPlottable->interface1D()->dataPixelPosition(index);
  23931. else
  23932. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23933. return {};
  23934. }
  23935. /* inherits documentation from base class */
  23936. bool QCPErrorBars::sortKeyIsMainKey() const
  23937. {
  23938. if (mDataPlottable)
  23939. {
  23940. return mDataPlottable->interface1D()->sortKeyIsMainKey();
  23941. } else
  23942. {
  23943. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23944. return true;
  23945. }
  23946. }
  23947. /*!
  23948. \copydoc QCPPlottableInterface1D::selectTestRect
  23949. */
  23950. QCPDataSelection QCPErrorBars::selectTestRect(const QRectF &rect, bool onlySelectable) const
  23951. {
  23952. QCPDataSelection result;
  23953. if (!mDataPlottable)
  23954. return result;
  23955. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  23956. return result;
  23957. if (!mKeyAxis || !mValueAxis)
  23958. return result;
  23959. QCPErrorBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  23960. getVisibleDataBounds(visibleBegin, visibleEnd, QCPDataRange(0, dataCount()));
  23961. QVector<QLineF> backbones, whiskers;
  23962. for (QCPErrorBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  23963. {
  23964. backbones.clear();
  23965. whiskers.clear();
  23966. getErrorBarLines(it, backbones, whiskers);
  23967. foreach (const QLineF &backbone, backbones)
  23968. {
  23969. if (rectIntersectsLine(rect, backbone))
  23970. {
  23971. result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
  23972. break;
  23973. }
  23974. }
  23975. }
  23976. result.simplify();
  23977. return result;
  23978. }
  23979. /* inherits documentation from base class */
  23980. int QCPErrorBars::findBegin(double sortKey, bool expandedRange) const
  23981. {
  23982. if (mDataPlottable)
  23983. {
  23984. if (mDataContainer->isEmpty())
  23985. return 0;
  23986. int beginIndex = mDataPlottable->interface1D()->findBegin(sortKey, expandedRange);
  23987. if (beginIndex >= mDataContainer->size())
  23988. beginIndex = mDataContainer->size()-1;
  23989. return beginIndex;
  23990. } else
  23991. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23992. return 0;
  23993. }
  23994. /* inherits documentation from base class */
  23995. int QCPErrorBars::findEnd(double sortKey, bool expandedRange) const
  23996. {
  23997. if (mDataPlottable)
  23998. {
  23999. if (mDataContainer->isEmpty())
  24000. return 0;
  24001. int endIndex = mDataPlottable->interface1D()->findEnd(sortKey, expandedRange);
  24002. if (endIndex > mDataContainer->size())
  24003. endIndex = mDataContainer->size();
  24004. return endIndex;
  24005. } else
  24006. qDebug() << Q_FUNC_INFO << "no data plottable set";
  24007. return 0;
  24008. }
  24009. /*!
  24010. Implements a selectTest specific to this plottable's point geometry.
  24011. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  24012. point to \a pos.
  24013. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  24014. */
  24015. double QCPErrorBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  24016. {
  24017. if (!mDataPlottable) return -1;
  24018. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  24019. return -1;
  24020. if (!mKeyAxis || !mValueAxis)
  24021. return -1;
  24022. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  24023. {
  24024. QCPErrorBarsDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  24025. double result = pointDistance(pos, closestDataPoint);
  24026. if (details)
  24027. {
  24028. int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
  24029. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  24030. }
  24031. return result;
  24032. } else
  24033. return -1;
  24034. }
  24035. /* inherits documentation from base class */
  24036. void QCPErrorBars::draw(QCPPainter *painter)
  24037. {
  24038. if (!mDataPlottable) return;
  24039. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  24040. if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
  24041. // if the sort key isn't the main key, we must check the visibility for each data point/error bar individually
  24042. // (getVisibleDataBounds applies range restriction, but otherwise can only return full data range):
  24043. bool checkPointVisibility = !mDataPlottable->interface1D()->sortKeyIsMainKey();
  24044. // check data validity if flag set:
  24045. #ifdef QCUSTOMPLOT_CHECK_DATA
  24046. QCPErrorBarsDataContainer::const_iterator it;
  24047. for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  24048. {
  24049. if (QCP::isInvalidData(it->errorMinus, it->errorPlus))
  24050. qDebug() << Q_FUNC_INFO << "Data point at index" << it-mDataContainer->constBegin() << "invalid." << "Plottable name:" << name();
  24051. }
  24052. #endif
  24053. applyDefaultAntialiasingHint(painter);
  24054. painter->setBrush(Qt::NoBrush);
  24055. // loop over and draw segments of unselected/selected data:
  24056. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  24057. getDataSegments(selectedSegments, unselectedSegments);
  24058. allSegments << unselectedSegments << selectedSegments;
  24059. QVector<QLineF> backbones, whiskers;
  24060. for (int i=0; i<allSegments.size(); ++i)
  24061. {
  24062. QCPErrorBarsDataContainer::const_iterator begin, end;
  24063. getVisibleDataBounds(begin, end, allSegments.at(i));
  24064. if (begin == end)
  24065. continue;
  24066. bool isSelectedSegment = i >= unselectedSegments.size();
  24067. if (isSelectedSegment && mSelectionDecorator)
  24068. mSelectionDecorator->applyPen(painter);
  24069. else
  24070. painter->setPen(mPen);
  24071. if (painter->pen().capStyle() == Qt::SquareCap)
  24072. {
  24073. QPen capFixPen(painter->pen());
  24074. capFixPen.setCapStyle(Qt::FlatCap);
  24075. painter->setPen(capFixPen);
  24076. }
  24077. backbones.clear();
  24078. whiskers.clear();
  24079. for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it)
  24080. {
  24081. if (!checkPointVisibility || errorBarVisible(int(it-mDataContainer->constBegin())))
  24082. getErrorBarLines(it, backbones, whiskers);
  24083. }
  24084. painter->drawLines(backbones);
  24085. painter->drawLines(whiskers);
  24086. }
  24087. // draw other selection decoration that isn't just line/scatter pens and brushes:
  24088. if (mSelectionDecorator)
  24089. mSelectionDecorator->drawDecoration(painter, selection());
  24090. }
  24091. /* inherits documentation from base class */
  24092. void QCPErrorBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  24093. {
  24094. applyDefaultAntialiasingHint(painter);
  24095. painter->setPen(mPen);
  24096. if (mErrorType == etValueError && mValueAxis && mValueAxis->orientation() == Qt::Vertical)
  24097. {
  24098. painter->drawLine(QLineF(rect.center().x(), rect.top()+2, rect.center().x(), rect.bottom()-1));
  24099. painter->drawLine(QLineF(rect.center().x()-4, rect.top()+2, rect.center().x()+4, rect.top()+2));
  24100. painter->drawLine(QLineF(rect.center().x()-4, rect.bottom()-1, rect.center().x()+4, rect.bottom()-1));
  24101. } else
  24102. {
  24103. painter->drawLine(QLineF(rect.left()+2, rect.center().y(), rect.right()-2, rect.center().y()));
  24104. painter->drawLine(QLineF(rect.left()+2, rect.center().y()-4, rect.left()+2, rect.center().y()+4));
  24105. painter->drawLine(QLineF(rect.right()-2, rect.center().y()-4, rect.right()-2, rect.center().y()+4));
  24106. }
  24107. }
  24108. /* inherits documentation from base class */
  24109. QCPRange QCPErrorBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  24110. {
  24111. if (!mDataPlottable)
  24112. {
  24113. foundRange = false;
  24114. return {};
  24115. }
  24116. QCPRange range;
  24117. bool haveLower = false;
  24118. bool haveUpper = false;
  24119. QCPErrorBarsDataContainer::const_iterator it;
  24120. for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  24121. {
  24122. if (mErrorType == etValueError)
  24123. {
  24124. // error bar doesn't extend in key dimension (except whisker but we ignore that here), so only use data point center
  24125. const double current = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin()));
  24126. if (qIsNaN(current)) continue;
  24127. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  24128. {
  24129. if (current < range.lower || !haveLower)
  24130. {
  24131. range.lower = current;
  24132. haveLower = true;
  24133. }
  24134. if (current > range.upper || !haveUpper)
  24135. {
  24136. range.upper = current;
  24137. haveUpper = true;
  24138. }
  24139. }
  24140. } else // mErrorType == etKeyError
  24141. {
  24142. const double dataKey = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin()));
  24143. if (qIsNaN(dataKey)) continue;
  24144. // plus error:
  24145. double current = dataKey + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus);
  24146. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  24147. {
  24148. if (current > range.upper || !haveUpper)
  24149. {
  24150. range.upper = current;
  24151. haveUpper = true;
  24152. }
  24153. }
  24154. // minus error:
  24155. current = dataKey - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus);
  24156. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  24157. {
  24158. if (current < range.lower || !haveLower)
  24159. {
  24160. range.lower = current;
  24161. haveLower = true;
  24162. }
  24163. }
  24164. }
  24165. }
  24166. if (haveUpper && !haveLower)
  24167. {
  24168. range.lower = range.upper;
  24169. haveLower = true;
  24170. } else if (haveLower && !haveUpper)
  24171. {
  24172. range.upper = range.lower;
  24173. haveUpper = true;
  24174. }
  24175. foundRange = haveLower && haveUpper;
  24176. return range;
  24177. }
  24178. /* inherits documentation from base class */
  24179. QCPRange QCPErrorBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  24180. {
  24181. if (!mDataPlottable)
  24182. {
  24183. foundRange = false;
  24184. return {};
  24185. }
  24186. QCPRange range;
  24187. const bool restrictKeyRange = inKeyRange != QCPRange();
  24188. bool haveLower = false;
  24189. bool haveUpper = false;
  24190. QCPErrorBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin();
  24191. QCPErrorBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd();
  24192. if (mDataPlottable->interface1D()->sortKeyIsMainKey() && restrictKeyRange)
  24193. {
  24194. itBegin = mDataContainer->constBegin()+findBegin(inKeyRange.lower, false);
  24195. itEnd = mDataContainer->constBegin()+findEnd(inKeyRange.upper, false);
  24196. }
  24197. for (QCPErrorBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it)
  24198. {
  24199. if (restrictKeyRange)
  24200. {
  24201. const double dataKey = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin()));
  24202. if (dataKey < inKeyRange.lower || dataKey > inKeyRange.upper)
  24203. continue;
  24204. }
  24205. if (mErrorType == etValueError)
  24206. {
  24207. const double dataValue = mDataPlottable->interface1D()->dataMainValue(int(it-mDataContainer->constBegin()));
  24208. if (qIsNaN(dataValue)) continue;
  24209. // plus error:
  24210. double current = dataValue + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus);
  24211. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  24212. {
  24213. if (current > range.upper || !haveUpper)
  24214. {
  24215. range.upper = current;
  24216. haveUpper = true;
  24217. }
  24218. }
  24219. // minus error:
  24220. current = dataValue - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus);
  24221. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  24222. {
  24223. if (current < range.lower || !haveLower)
  24224. {
  24225. range.lower = current;
  24226. haveLower = true;
  24227. }
  24228. }
  24229. } else // mErrorType == etKeyError
  24230. {
  24231. // error bar doesn't extend in value dimension (except whisker but we ignore that here), so only use data point center
  24232. const double current = mDataPlottable->interface1D()->dataMainValue(int(it-mDataContainer->constBegin()));
  24233. if (qIsNaN(current)) continue;
  24234. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  24235. {
  24236. if (current < range.lower || !haveLower)
  24237. {
  24238. range.lower = current;
  24239. haveLower = true;
  24240. }
  24241. if (current > range.upper || !haveUpper)
  24242. {
  24243. range.upper = current;
  24244. haveUpper = true;
  24245. }
  24246. }
  24247. }
  24248. }
  24249. if (haveUpper && !haveLower)
  24250. {
  24251. range.lower = range.upper;
  24252. haveLower = true;
  24253. } else if (haveLower && !haveUpper)
  24254. {
  24255. range.upper = range.lower;
  24256. haveUpper = true;
  24257. }
  24258. foundRange = haveLower && haveUpper;
  24259. return range;
  24260. }
  24261. /*! \internal
  24262. Calculates the lines that make up the error bar belonging to the data point \a it.
  24263. The resulting lines are added to \a backbones and \a whiskers. The vectors are not cleared, so
  24264. calling this method with different \a it but the same \a backbones and \a whiskers allows to
  24265. accumulate lines for multiple data points.
  24266. This method assumes that \a it is a valid iterator within the bounds of this \ref QCPErrorBars
  24267. instance and within the bounds of the associated data plottable.
  24268. */
  24269. void QCPErrorBars::getErrorBarLines(QCPErrorBarsDataContainer::const_iterator it, QVector<QLineF> &backbones, QVector<QLineF> &whiskers) const
  24270. {
  24271. if (!mDataPlottable) return;
  24272. int index = int(it-mDataContainer->constBegin());
  24273. QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index);
  24274. if (qIsNaN(centerPixel.x()) || qIsNaN(centerPixel.y()))
  24275. return;
  24276. QCPAxis *errorAxis = mErrorType == etValueError ? mValueAxis.data() : mKeyAxis.data();
  24277. QCPAxis *orthoAxis = mErrorType == etValueError ? mKeyAxis.data() : mValueAxis.data();
  24278. const double centerErrorAxisPixel = errorAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
  24279. const double centerOrthoAxisPixel = orthoAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
  24280. const double centerErrorAxisCoord = errorAxis->pixelToCoord(centerErrorAxisPixel); // depending on plottable, this might be different from just mDataPlottable->interface1D()->dataMainKey/Value
  24281. const double symbolGap = mSymbolGap*0.5*errorAxis->pixelOrientation();
  24282. // plus error:
  24283. double errorStart, errorEnd;
  24284. if (!qIsNaN(it->errorPlus))
  24285. {
  24286. errorStart = centerErrorAxisPixel+symbolGap;
  24287. errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord+it->errorPlus);
  24288. if (errorAxis->orientation() == Qt::Vertical)
  24289. {
  24290. if ((errorStart > errorEnd) != errorAxis->rangeReversed())
  24291. backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd));
  24292. whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd));
  24293. } else
  24294. {
  24295. if ((errorStart < errorEnd) != errorAxis->rangeReversed())
  24296. backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel));
  24297. whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5));
  24298. }
  24299. }
  24300. // minus error:
  24301. if (!qIsNaN(it->errorMinus))
  24302. {
  24303. errorStart = centerErrorAxisPixel-symbolGap;
  24304. errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord-it->errorMinus);
  24305. if (errorAxis->orientation() == Qt::Vertical)
  24306. {
  24307. if ((errorStart < errorEnd) != errorAxis->rangeReversed())
  24308. backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd));
  24309. whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd));
  24310. } else
  24311. {
  24312. if ((errorStart > errorEnd) != errorAxis->rangeReversed())
  24313. backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel));
  24314. whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5));
  24315. }
  24316. }
  24317. }
  24318. /*! \internal
  24319. This method outputs the currently visible data range via \a begin and \a end. The returned range
  24320. will also never exceed \a rangeRestriction.
  24321. Since error bars with type \ref etKeyError may extend to arbitrarily positive and negative key
  24322. coordinates relative to their data point key, this method checks all outer error bars whether
  24323. they truly don't reach into the visible portion of the axis rect, by calling \ref
  24324. errorBarVisible. On the other hand error bars with type \ref etValueError that are associated
  24325. with data plottables whose sort key is equal to the main key (see \ref qcpdatacontainer-datatype
  24326. "QCPDataContainer DataType") can be handled very efficiently by finding the visible range of
  24327. error bars through binary search (\ref QCPPlottableInterface1D::findBegin and \ref
  24328. QCPPlottableInterface1D::findEnd).
  24329. If the plottable's sort key is not equal to the main key, this method returns the full data
  24330. range, only restricted by \a rangeRestriction. Drawing optimization then has to be done on a
  24331. point-by-point basis in the \ref draw method.
  24332. */
  24333. void QCPErrorBars::getVisibleDataBounds(QCPErrorBarsDataContainer::const_iterator &begin, QCPErrorBarsDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
  24334. {
  24335. QCPAxis *keyAxis = mKeyAxis.data();
  24336. QCPAxis *valueAxis = mValueAxis.data();
  24337. if (!keyAxis || !valueAxis)
  24338. {
  24339. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  24340. end = mDataContainer->constEnd();
  24341. begin = end;
  24342. return;
  24343. }
  24344. if (!mDataPlottable || rangeRestriction.isEmpty())
  24345. {
  24346. end = mDataContainer->constEnd();
  24347. begin = end;
  24348. return;
  24349. }
  24350. if (!mDataPlottable->interface1D()->sortKeyIsMainKey())
  24351. {
  24352. // if the sort key isn't the main key, it's not possible to find a contiguous range of visible
  24353. // data points, so this method then only applies the range restriction and otherwise returns
  24354. // the full data range. Visibility checks must be done on a per-datapoin-basis during drawing
  24355. QCPDataRange dataRange(0, mDataContainer->size());
  24356. dataRange = dataRange.bounded(rangeRestriction);
  24357. begin = mDataContainer->constBegin()+dataRange.begin();
  24358. end = mDataContainer->constBegin()+dataRange.end();
  24359. return;
  24360. }
  24361. // get visible data range via interface from data plottable, and then restrict to available error data points:
  24362. const int n = qMin(mDataContainer->size(), mDataPlottable->interface1D()->dataCount());
  24363. int beginIndex = mDataPlottable->interface1D()->findBegin(keyAxis->range().lower);
  24364. int endIndex = mDataPlottable->interface1D()->findEnd(keyAxis->range().upper);
  24365. int i = beginIndex;
  24366. while (i > 0 && i < n && i > rangeRestriction.begin())
  24367. {
  24368. if (errorBarVisible(i))
  24369. beginIndex = i;
  24370. --i;
  24371. }
  24372. i = endIndex;
  24373. while (i >= 0 && i < n && i < rangeRestriction.end())
  24374. {
  24375. if (errorBarVisible(i))
  24376. endIndex = i+1;
  24377. ++i;
  24378. }
  24379. QCPDataRange dataRange(beginIndex, endIndex);
  24380. dataRange = dataRange.bounded(rangeRestriction.bounded(QCPDataRange(0, mDataContainer->size())));
  24381. begin = mDataContainer->constBegin()+dataRange.begin();
  24382. end = mDataContainer->constBegin()+dataRange.end();
  24383. }
  24384. /*! \internal
  24385. Calculates the minimum distance in pixels the error bars' representation has from the given \a
  24386. pixelPoint. This is used to determine whether the error bar was clicked or not, e.g. in \ref
  24387. selectTest. The closest data point to \a pixelPoint is returned in \a closestData.
  24388. */
  24389. double QCPErrorBars::pointDistance(const QPointF &pixelPoint, QCPErrorBarsDataContainer::const_iterator &closestData) const
  24390. {
  24391. closestData = mDataContainer->constEnd();
  24392. if (!mDataPlottable || mDataContainer->isEmpty())
  24393. return -1.0;
  24394. if (!mKeyAxis || !mValueAxis)
  24395. {
  24396. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  24397. return -1.0;
  24398. }
  24399. QCPErrorBarsDataContainer::const_iterator begin, end;
  24400. getVisibleDataBounds(begin, end, QCPDataRange(0, dataCount()));
  24401. // calculate minimum distances to error backbones (whiskers are ignored for speed) and find closestData iterator:
  24402. double minDistSqr = (std::numeric_limits<double>::max)();
  24403. QVector<QLineF> backbones, whiskers;
  24404. for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it)
  24405. {
  24406. getErrorBarLines(it, backbones, whiskers);
  24407. foreach (const QLineF &backbone, backbones)
  24408. {
  24409. const double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(backbone);
  24410. if (currentDistSqr < minDistSqr)
  24411. {
  24412. minDistSqr = currentDistSqr;
  24413. closestData = it;
  24414. }
  24415. }
  24416. }
  24417. return qSqrt(minDistSqr);
  24418. }
  24419. /*! \internal
  24420. \note This method is identical to \ref QCPAbstractPlottable1D::getDataSegments but needs to be
  24421. reproduced here since the \ref QCPErrorBars plottable, as a special case that doesn't have its
  24422. own key/value data coordinates, doesn't derive from \ref QCPAbstractPlottable1D. See the
  24423. documentation there for details.
  24424. */
  24425. void QCPErrorBars::getDataSegments(QList<QCPDataRange> &selectedSegments, QList<QCPDataRange> &unselectedSegments) const
  24426. {
  24427. selectedSegments.clear();
  24428. unselectedSegments.clear();
  24429. if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty
  24430. {
  24431. if (selected())
  24432. selectedSegments << QCPDataRange(0, dataCount());
  24433. else
  24434. unselectedSegments << QCPDataRange(0, dataCount());
  24435. } else
  24436. {
  24437. QCPDataSelection sel(selection());
  24438. sel.simplify();
  24439. selectedSegments = sel.dataRanges();
  24440. unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges();
  24441. }
  24442. }
  24443. /*! \internal
  24444. Returns whether the error bar at the specified \a index is visible within the current key axis
  24445. range.
  24446. This method assumes for performance reasons without checking that the key axis, the value axis,
  24447. and the data plottable (\ref setDataPlottable) are not \c nullptr and that \a index is within
  24448. valid bounds of this \ref QCPErrorBars instance and the bounds of the data plottable.
  24449. */
  24450. bool QCPErrorBars::errorBarVisible(int index) const
  24451. {
  24452. QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index);
  24453. const double centerKeyPixel = mKeyAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
  24454. if (qIsNaN(centerKeyPixel))
  24455. return false;
  24456. double keyMin, keyMax;
  24457. if (mErrorType == etKeyError)
  24458. {
  24459. const double centerKey = mKeyAxis->pixelToCoord(centerKeyPixel);
  24460. const double errorPlus = mDataContainer->at(index).errorPlus;
  24461. const double errorMinus = mDataContainer->at(index).errorMinus;
  24462. keyMax = centerKey+(qIsNaN(errorPlus) ? 0 : errorPlus);
  24463. keyMin = centerKey-(qIsNaN(errorMinus) ? 0 : errorMinus);
  24464. } else // mErrorType == etValueError
  24465. {
  24466. keyMax = mKeyAxis->pixelToCoord(centerKeyPixel+mWhiskerWidth*0.5*mKeyAxis->pixelOrientation());
  24467. keyMin = mKeyAxis->pixelToCoord(centerKeyPixel-mWhiskerWidth*0.5*mKeyAxis->pixelOrientation());
  24468. }
  24469. return ((keyMax > mKeyAxis->range().lower) && (keyMin < mKeyAxis->range().upper));
  24470. }
  24471. /*! \internal
  24472. Returns whether \a line intersects (or is contained in) \a pixelRect.
  24473. \a line is assumed to be either perfectly horizontal or perfectly vertical, as is the case for
  24474. error bar lines.
  24475. */
  24476. bool QCPErrorBars::rectIntersectsLine(const QRectF &pixelRect, const QLineF &line) const
  24477. {
  24478. if (pixelRect.left() > line.x1() && pixelRect.left() > line.x2())
  24479. return false;
  24480. else if (pixelRect.right() < line.x1() && pixelRect.right() < line.x2())
  24481. return false;
  24482. else if (pixelRect.top() > line.y1() && pixelRect.top() > line.y2())
  24483. return false;
  24484. else if (pixelRect.bottom() < line.y1() && pixelRect.bottom() < line.y2())
  24485. return false;
  24486. else
  24487. return true;
  24488. }
  24489. /* end of 'src/plottables/plottable-errorbar.cpp' */
  24490. /* including file 'src/items/item-straightline.cpp' */
  24491. /* modified 2022-11-06T12:45:56, size 7596 */
  24492. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24493. //////////////////// QCPItemStraightLine
  24494. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24495. /*! \class QCPItemStraightLine
  24496. \brief A straight line that spans infinitely in both directions
  24497. \image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid blue discs are positions."
  24498. It has two positions, \a point1 and \a point2, which define the straight line.
  24499. */
  24500. /*!
  24501. Creates a straight line item and sets default values.
  24502. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24503. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24504. */
  24505. QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) :
  24506. QCPAbstractItem(parentPlot),
  24507. point1(createPosition(QLatin1String("point1"))),
  24508. point2(createPosition(QLatin1String("point2")))
  24509. {
  24510. point1->setCoords(0, 0);
  24511. point2->setCoords(1, 1);
  24512. setPen(QPen(Qt::black));
  24513. setSelectedPen(QPen(Qt::blue,2));
  24514. }
  24515. QCPItemStraightLine::~QCPItemStraightLine()
  24516. {
  24517. }
  24518. /*!
  24519. Sets the pen that will be used to draw the line
  24520. \see setSelectedPen
  24521. */
  24522. void QCPItemStraightLine::setPen(const QPen &pen)
  24523. {
  24524. mPen = pen;
  24525. }
  24526. /*!
  24527. Sets the pen that will be used to draw the line when selected
  24528. \see setPen, setSelected
  24529. */
  24530. void QCPItemStraightLine::setSelectedPen(const QPen &pen)
  24531. {
  24532. mSelectedPen = pen;
  24533. }
  24534. /* inherits documentation from base class */
  24535. double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  24536. {
  24537. Q_UNUSED(details)
  24538. if (onlySelectable && !mSelectable)
  24539. return -1;
  24540. return QCPVector2D(pos).distanceToStraightLine(point1->pixelPosition(), point2->pixelPosition()-point1->pixelPosition());
  24541. }
  24542. /* inherits documentation from base class */
  24543. void QCPItemStraightLine::draw(QCPPainter *painter)
  24544. {
  24545. QCPVector2D start(point1->pixelPosition());
  24546. QCPVector2D end(point2->pixelPosition());
  24547. // get visible segment of straight line inside clipRect:
  24548. int clipPad = qCeil(mainPen().widthF());
  24549. QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
  24550. // paint visible segment, if existent:
  24551. if (!line.isNull())
  24552. {
  24553. painter->setPen(mainPen());
  24554. painter->drawLine(line);
  24555. }
  24556. }
  24557. /*! \internal
  24558. Returns the section of the straight line defined by \a base and direction vector \a
  24559. vec, that is visible in the specified \a rect.
  24560. This is a helper function for \ref draw.
  24561. */
  24562. QLineF QCPItemStraightLine::getRectClippedStraightLine(const QCPVector2D &base, const QCPVector2D &vec, const QRect &rect) const
  24563. {
  24564. double bx, by;
  24565. double gamma;
  24566. QLineF result;
  24567. if (vec.x() == 0 && vec.y() == 0)
  24568. return result;
  24569. if (qFuzzyIsNull(vec.x())) // line is vertical
  24570. {
  24571. // check top of rect:
  24572. bx = rect.left();
  24573. by = rect.top();
  24574. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  24575. if (gamma >= 0 && gamma <= rect.width())
  24576. result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical
  24577. } else if (qFuzzyIsNull(vec.y())) // line is horizontal
  24578. {
  24579. // check left of rect:
  24580. bx = rect.left();
  24581. by = rect.top();
  24582. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  24583. if (gamma >= 0 && gamma <= rect.height())
  24584. result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal
  24585. } else // line is skewed
  24586. {
  24587. QList<QCPVector2D> pointVectors;
  24588. // check top of rect:
  24589. bx = rect.left();
  24590. by = rect.top();
  24591. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  24592. if (gamma >= 0 && gamma <= rect.width())
  24593. pointVectors.append(QCPVector2D(bx+gamma, by));
  24594. // check bottom of rect:
  24595. bx = rect.left();
  24596. by = rect.bottom();
  24597. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  24598. if (gamma >= 0 && gamma <= rect.width())
  24599. pointVectors.append(QCPVector2D(bx+gamma, by));
  24600. // check left of rect:
  24601. bx = rect.left();
  24602. by = rect.top();
  24603. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  24604. if (gamma >= 0 && gamma <= rect.height())
  24605. pointVectors.append(QCPVector2D(bx, by+gamma));
  24606. // check right of rect:
  24607. bx = rect.right();
  24608. by = rect.top();
  24609. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  24610. if (gamma >= 0 && gamma <= rect.height())
  24611. pointVectors.append(QCPVector2D(bx, by+gamma));
  24612. // evaluate points:
  24613. if (pointVectors.size() == 2)
  24614. {
  24615. result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
  24616. } else if (pointVectors.size() > 2)
  24617. {
  24618. // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
  24619. double distSqrMax = 0;
  24620. QCPVector2D pv1, pv2;
  24621. for (int i=0; i<pointVectors.size()-1; ++i)
  24622. {
  24623. for (int k=i+1; k<pointVectors.size(); ++k)
  24624. {
  24625. double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
  24626. if (distSqr > distSqrMax)
  24627. {
  24628. pv1 = pointVectors.at(i);
  24629. pv2 = pointVectors.at(k);
  24630. distSqrMax = distSqr;
  24631. }
  24632. }
  24633. }
  24634. result.setPoints(pv1.toPointF(), pv2.toPointF());
  24635. }
  24636. }
  24637. return result;
  24638. }
  24639. /*! \internal
  24640. Returns the pen that should be used for drawing lines. Returns mPen when the
  24641. item is not selected and mSelectedPen when it is.
  24642. */
  24643. QPen QCPItemStraightLine::mainPen() const
  24644. {
  24645. return mSelected ? mSelectedPen : mPen;
  24646. }
  24647. /* end of 'src/items/item-straightline.cpp' */
  24648. /* including file 'src/items/item-line.cpp' */
  24649. /* modified 2022-11-06T12:45:56, size 8525 */
  24650. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24651. //////////////////// QCPItemLine
  24652. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24653. /*! \class QCPItemLine
  24654. \brief A line from one point to another
  24655. \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions."
  24656. It has two positions, \a start and \a end, which define the end points of the line.
  24657. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow.
  24658. */
  24659. /*!
  24660. Creates a line item and sets default values.
  24661. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24662. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24663. */
  24664. QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) :
  24665. QCPAbstractItem(parentPlot),
  24666. start(createPosition(QLatin1String("start"))),
  24667. end(createPosition(QLatin1String("end")))
  24668. {
  24669. start->setCoords(0, 0);
  24670. end->setCoords(1, 1);
  24671. setPen(QPen(Qt::black));
  24672. setSelectedPen(QPen(Qt::blue,2));
  24673. }
  24674. QCPItemLine::~QCPItemLine()
  24675. {
  24676. }
  24677. /*!
  24678. Sets the pen that will be used to draw the line
  24679. \see setSelectedPen
  24680. */
  24681. void QCPItemLine::setPen(const QPen &pen)
  24682. {
  24683. mPen = pen;
  24684. }
  24685. /*!
  24686. Sets the pen that will be used to draw the line when selected
  24687. \see setPen, setSelected
  24688. */
  24689. void QCPItemLine::setSelectedPen(const QPen &pen)
  24690. {
  24691. mSelectedPen = pen;
  24692. }
  24693. /*!
  24694. Sets the line ending style of the head. The head corresponds to the \a end position.
  24695. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  24696. a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
  24697. \see setTail
  24698. */
  24699. void QCPItemLine::setHead(const QCPLineEnding &head)
  24700. {
  24701. mHead = head;
  24702. }
  24703. /*!
  24704. Sets the line ending style of the tail. The tail corresponds to the \a start position.
  24705. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  24706. a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
  24707. \see setHead
  24708. */
  24709. void QCPItemLine::setTail(const QCPLineEnding &tail)
  24710. {
  24711. mTail = tail;
  24712. }
  24713. /* inherits documentation from base class */
  24714. double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  24715. {
  24716. Q_UNUSED(details)
  24717. if (onlySelectable && !mSelectable)
  24718. return -1;
  24719. return qSqrt(QCPVector2D(pos).distanceSquaredToLine(start->pixelPosition(), end->pixelPosition()));
  24720. }
  24721. /* inherits documentation from base class */
  24722. void QCPItemLine::draw(QCPPainter *painter)
  24723. {
  24724. QCPVector2D startVec(start->pixelPosition());
  24725. QCPVector2D endVec(end->pixelPosition());
  24726. if (qFuzzyIsNull((startVec-endVec).lengthSquared()))
  24727. return;
  24728. // get visible segment of straight line inside clipRect:
  24729. int clipPad = int(qMax(mHead.boundingDistance(), mTail.boundingDistance()));
  24730. clipPad = qMax(clipPad, qCeil(mainPen().widthF()));
  24731. QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
  24732. // paint visible segment, if existent:
  24733. if (!line.isNull())
  24734. {
  24735. painter->setPen(mainPen());
  24736. painter->drawLine(line);
  24737. painter->setBrush(Qt::SolidPattern);
  24738. if (mTail.style() != QCPLineEnding::esNone)
  24739. mTail.draw(painter, startVec, startVec-endVec);
  24740. if (mHead.style() != QCPLineEnding::esNone)
  24741. mHead.draw(painter, endVec, endVec-startVec);
  24742. }
  24743. }
  24744. /*! \internal
  24745. Returns the section of the line defined by \a start and \a end, that is visible in the specified
  24746. \a rect.
  24747. This is a helper function for \ref draw.
  24748. */
  24749. QLineF QCPItemLine::getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRect &rect) const
  24750. {
  24751. bool containsStart = rect.contains(qRound(start.x()), qRound(start.y()));
  24752. bool containsEnd = rect.contains(qRound(end.x()), qRound(end.y()));
  24753. if (containsStart && containsEnd)
  24754. return {start.toPointF(), end.toPointF()};
  24755. QCPVector2D base = start;
  24756. QCPVector2D vec = end-start;
  24757. double bx, by;
  24758. double gamma, mu;
  24759. QLineF result;
  24760. QList<QCPVector2D> pointVectors;
  24761. if (!qFuzzyIsNull(vec.y())) // line is not horizontal
  24762. {
  24763. // check top of rect:
  24764. bx = rect.left();
  24765. by = rect.top();
  24766. mu = (by-base.y())/vec.y();
  24767. if (mu >= 0 && mu <= 1)
  24768. {
  24769. gamma = base.x()-bx + mu*vec.x();
  24770. if (gamma >= 0 && gamma <= rect.width())
  24771. pointVectors.append(QCPVector2D(bx+gamma, by));
  24772. }
  24773. // check bottom of rect:
  24774. bx = rect.left();
  24775. by = rect.bottom();
  24776. mu = (by-base.y())/vec.y();
  24777. if (mu >= 0 && mu <= 1)
  24778. {
  24779. gamma = base.x()-bx + mu*vec.x();
  24780. if (gamma >= 0 && gamma <= rect.width())
  24781. pointVectors.append(QCPVector2D(bx+gamma, by));
  24782. }
  24783. }
  24784. if (!qFuzzyIsNull(vec.x())) // line is not vertical
  24785. {
  24786. // check left of rect:
  24787. bx = rect.left();
  24788. by = rect.top();
  24789. mu = (bx-base.x())/vec.x();
  24790. if (mu >= 0 && mu <= 1)
  24791. {
  24792. gamma = base.y()-by + mu*vec.y();
  24793. if (gamma >= 0 && gamma <= rect.height())
  24794. pointVectors.append(QCPVector2D(bx, by+gamma));
  24795. }
  24796. // check right of rect:
  24797. bx = rect.right();
  24798. by = rect.top();
  24799. mu = (bx-base.x())/vec.x();
  24800. if (mu >= 0 && mu <= 1)
  24801. {
  24802. gamma = base.y()-by + mu*vec.y();
  24803. if (gamma >= 0 && gamma <= rect.height())
  24804. pointVectors.append(QCPVector2D(bx, by+gamma));
  24805. }
  24806. }
  24807. if (containsStart)
  24808. pointVectors.append(start);
  24809. if (containsEnd)
  24810. pointVectors.append(end);
  24811. // evaluate points:
  24812. if (pointVectors.size() == 2)
  24813. {
  24814. result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
  24815. } else if (pointVectors.size() > 2)
  24816. {
  24817. // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
  24818. double distSqrMax = 0;
  24819. QCPVector2D pv1, pv2;
  24820. for (int i=0; i<pointVectors.size()-1; ++i)
  24821. {
  24822. for (int k=i+1; k<pointVectors.size(); ++k)
  24823. {
  24824. double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
  24825. if (distSqr > distSqrMax)
  24826. {
  24827. pv1 = pointVectors.at(i);
  24828. pv2 = pointVectors.at(k);
  24829. distSqrMax = distSqr;
  24830. }
  24831. }
  24832. }
  24833. result.setPoints(pv1.toPointF(), pv2.toPointF());
  24834. }
  24835. return result;
  24836. }
  24837. /*! \internal
  24838. Returns the pen that should be used for drawing lines. Returns mPen when the
  24839. item is not selected and mSelectedPen when it is.
  24840. */
  24841. QPen QCPItemLine::mainPen() const
  24842. {
  24843. return mSelected ? mSelectedPen : mPen;
  24844. }
  24845. /* end of 'src/items/item-line.cpp' */
  24846. /* including file 'src/items/item-curve.cpp' */
  24847. /* modified 2022-11-06T12:45:56, size 7273 */
  24848. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24849. //////////////////// QCPItemCurve
  24850. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24851. /*! \class QCPItemCurve
  24852. \brief A curved line from one point to another
  24853. \image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are positions."
  24854. It has four positions, \a start and \a end, which define the end points of the line, and two
  24855. control points which define the direction the line exits from the start and the direction from
  24856. which it approaches the end: \a startDir and \a endDir.
  24857. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an
  24858. arrow.
  24859. Often it is desirable for the control points to stay at fixed relative positions to the start/end
  24860. point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start,
  24861. and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir.
  24862. */
  24863. /*!
  24864. Creates a curve item and sets default values.
  24865. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24866. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24867. */
  24868. QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) :
  24869. QCPAbstractItem(parentPlot),
  24870. start(createPosition(QLatin1String("start"))),
  24871. startDir(createPosition(QLatin1String("startDir"))),
  24872. endDir(createPosition(QLatin1String("endDir"))),
  24873. end(createPosition(QLatin1String("end")))
  24874. {
  24875. start->setCoords(0, 0);
  24876. startDir->setCoords(0.5, 0);
  24877. endDir->setCoords(0, 0.5);
  24878. end->setCoords(1, 1);
  24879. setPen(QPen(Qt::black));
  24880. setSelectedPen(QPen(Qt::blue,2));
  24881. }
  24882. QCPItemCurve::~QCPItemCurve()
  24883. {
  24884. }
  24885. /*!
  24886. Sets the pen that will be used to draw the line
  24887. \see setSelectedPen
  24888. */
  24889. void QCPItemCurve::setPen(const QPen &pen)
  24890. {
  24891. mPen = pen;
  24892. }
  24893. /*!
  24894. Sets the pen that will be used to draw the line when selected
  24895. \see setPen, setSelected
  24896. */
  24897. void QCPItemCurve::setSelectedPen(const QPen &pen)
  24898. {
  24899. mSelectedPen = pen;
  24900. }
  24901. /*!
  24902. Sets the line ending style of the head. The head corresponds to the \a end position.
  24903. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  24904. a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
  24905. \see setTail
  24906. */
  24907. void QCPItemCurve::setHead(const QCPLineEnding &head)
  24908. {
  24909. mHead = head;
  24910. }
  24911. /*!
  24912. Sets the line ending style of the tail. The tail corresponds to the \a start position.
  24913. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  24914. a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
  24915. \see setHead
  24916. */
  24917. void QCPItemCurve::setTail(const QCPLineEnding &tail)
  24918. {
  24919. mTail = tail;
  24920. }
  24921. /* inherits documentation from base class */
  24922. double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  24923. {
  24924. Q_UNUSED(details)
  24925. if (onlySelectable && !mSelectable)
  24926. return -1;
  24927. QPointF startVec(start->pixelPosition());
  24928. QPointF startDirVec(startDir->pixelPosition());
  24929. QPointF endDirVec(endDir->pixelPosition());
  24930. QPointF endVec(end->pixelPosition());
  24931. QPainterPath cubicPath(startVec);
  24932. cubicPath.cubicTo(startDirVec, endDirVec, endVec);
  24933. QList<QPolygonF> polygons = cubicPath.toSubpathPolygons();
  24934. if (polygons.isEmpty())
  24935. return -1;
  24936. const QPolygonF polygon = polygons.first();
  24937. QCPVector2D p(pos);
  24938. double minDistSqr = (std::numeric_limits<double>::max)();
  24939. for (int i=1; i<polygon.size(); ++i)
  24940. {
  24941. double distSqr = p.distanceSquaredToLine(polygon.at(i-1), polygon.at(i));
  24942. if (distSqr < minDistSqr)
  24943. minDistSqr = distSqr;
  24944. }
  24945. return qSqrt(minDistSqr);
  24946. }
  24947. /* inherits documentation from base class */
  24948. void QCPItemCurve::draw(QCPPainter *painter)
  24949. {
  24950. QCPVector2D startVec(start->pixelPosition());
  24951. QCPVector2D startDirVec(startDir->pixelPosition());
  24952. QCPVector2D endDirVec(endDir->pixelPosition());
  24953. QCPVector2D endVec(end->pixelPosition());
  24954. if ((endVec-startVec).length() > 1e10) // too large curves cause crash
  24955. return;
  24956. QPainterPath cubicPath(startVec.toPointF());
  24957. cubicPath.cubicTo(startDirVec.toPointF(), endDirVec.toPointF(), endVec.toPointF());
  24958. // paint visible segment, if existent:
  24959. const int clipEnlarge = qCeil(mainPen().widthF());
  24960. QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge);
  24961. QRect cubicRect = cubicPath.controlPointRect().toRect();
  24962. if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position
  24963. cubicRect.adjust(0, 0, 1, 1);
  24964. if (clip.intersects(cubicRect))
  24965. {
  24966. painter->setPen(mainPen());
  24967. painter->drawPath(cubicPath);
  24968. painter->setBrush(Qt::SolidPattern);
  24969. if (mTail.style() != QCPLineEnding::esNone)
  24970. mTail.draw(painter, startVec, M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI);
  24971. if (mHead.style() != QCPLineEnding::esNone)
  24972. mHead.draw(painter, endVec, -cubicPath.angleAtPercent(1)/180.0*M_PI);
  24973. }
  24974. }
  24975. /*! \internal
  24976. Returns the pen that should be used for drawing lines. Returns mPen when the
  24977. item is not selected and mSelectedPen when it is.
  24978. */
  24979. QPen QCPItemCurve::mainPen() const
  24980. {
  24981. return mSelected ? mSelectedPen : mPen;
  24982. }
  24983. /* end of 'src/items/item-curve.cpp' */
  24984. /* including file 'src/items/item-rect.cpp' */
  24985. /* modified 2022-11-06T12:45:56, size 6472 */
  24986. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24987. //////////////////// QCPItemRect
  24988. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24989. /*! \class QCPItemRect
  24990. \brief A rectangle
  24991. \image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions."
  24992. It has two positions, \a topLeft and \a bottomRight, which define the rectangle.
  24993. */
  24994. /*!
  24995. Creates a rectangle item and sets default values.
  24996. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24997. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24998. */
  24999. QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) :
  25000. QCPAbstractItem(parentPlot),
  25001. topLeft(createPosition(QLatin1String("topLeft"))),
  25002. bottomRight(createPosition(QLatin1String("bottomRight"))),
  25003. top(createAnchor(QLatin1String("top"), aiTop)),
  25004. topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
  25005. right(createAnchor(QLatin1String("right"), aiRight)),
  25006. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  25007. bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
  25008. left(createAnchor(QLatin1String("left"), aiLeft))
  25009. {
  25010. topLeft->setCoords(0, 1);
  25011. bottomRight->setCoords(1, 0);
  25012. setPen(QPen(Qt::black));
  25013. setSelectedPen(QPen(Qt::blue,2));
  25014. setBrush(Qt::NoBrush);
  25015. setSelectedBrush(Qt::NoBrush);
  25016. }
  25017. QCPItemRect::~QCPItemRect()
  25018. {
  25019. }
  25020. /*!
  25021. Sets the pen that will be used to draw the line of the rectangle
  25022. \see setSelectedPen, setBrush
  25023. */
  25024. void QCPItemRect::setPen(const QPen &pen)
  25025. {
  25026. mPen = pen;
  25027. }
  25028. /*!
  25029. Sets the pen that will be used to draw the line of the rectangle when selected
  25030. \see setPen, setSelected
  25031. */
  25032. void QCPItemRect::setSelectedPen(const QPen &pen)
  25033. {
  25034. mSelectedPen = pen;
  25035. }
  25036. /*!
  25037. Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to
  25038. Qt::NoBrush.
  25039. \see setSelectedBrush, setPen
  25040. */
  25041. void QCPItemRect::setBrush(const QBrush &brush)
  25042. {
  25043. mBrush = brush;
  25044. }
  25045. /*!
  25046. Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a
  25047. brush to Qt::NoBrush.
  25048. \see setBrush
  25049. */
  25050. void QCPItemRect::setSelectedBrush(const QBrush &brush)
  25051. {
  25052. mSelectedBrush = brush;
  25053. }
  25054. /* inherits documentation from base class */
  25055. double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25056. {
  25057. Q_UNUSED(details)
  25058. if (onlySelectable && !mSelectable)
  25059. return -1;
  25060. QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()).normalized();
  25061. bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
  25062. return rectDistance(rect, pos, filledRect);
  25063. }
  25064. /* inherits documentation from base class */
  25065. void QCPItemRect::draw(QCPPainter *painter)
  25066. {
  25067. QPointF p1 = topLeft->pixelPosition();
  25068. QPointF p2 = bottomRight->pixelPosition();
  25069. if (p1.toPoint() == p2.toPoint())
  25070. return;
  25071. QRectF rect = QRectF(p1, p2).normalized();
  25072. double clipPad = mainPen().widthF();
  25073. QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  25074. if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect
  25075. {
  25076. painter->setPen(mainPen());
  25077. painter->setBrush(mainBrush());
  25078. painter->drawRect(rect);
  25079. }
  25080. }
  25081. /* inherits documentation from base class */
  25082. QPointF QCPItemRect::anchorPixelPosition(int anchorId) const
  25083. {
  25084. QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition());
  25085. switch (anchorId)
  25086. {
  25087. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  25088. case aiTopRight: return rect.topRight();
  25089. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  25090. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  25091. case aiBottomLeft: return rect.bottomLeft();
  25092. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
  25093. }
  25094. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  25095. return {};
  25096. }
  25097. /*! \internal
  25098. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  25099. and mSelectedPen when it is.
  25100. */
  25101. QPen QCPItemRect::mainPen() const
  25102. {
  25103. return mSelected ? mSelectedPen : mPen;
  25104. }
  25105. /*! \internal
  25106. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  25107. is not selected and mSelectedBrush when it is.
  25108. */
  25109. QBrush QCPItemRect::mainBrush() const
  25110. {
  25111. return mSelected ? mSelectedBrush : mBrush;
  25112. }
  25113. /* end of 'src/items/item-rect.cpp' */
  25114. /* including file 'src/items/item-text.cpp' */
  25115. /* modified 2022-11-06T12:45:56, size 13335 */
  25116. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25117. //////////////////// QCPItemText
  25118. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25119. /*! \class QCPItemText
  25120. \brief A text label
  25121. \image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions."
  25122. Its position is defined by the member \a position and the setting of \ref setPositionAlignment.
  25123. The latter controls which part of the text rect shall be aligned with \a position.
  25124. The text alignment itself (i.e. left, center, right) can be controlled with \ref
  25125. setTextAlignment.
  25126. The text may be rotated around the \a position point with \ref setRotation.
  25127. */
  25128. /*!
  25129. Creates a text item and sets default values.
  25130. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  25131. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  25132. */
  25133. QCPItemText::QCPItemText(QCustomPlot *parentPlot) :
  25134. QCPAbstractItem(parentPlot),
  25135. position(createPosition(QLatin1String("position"))),
  25136. topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft)),
  25137. top(createAnchor(QLatin1String("top"), aiTop)),
  25138. topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
  25139. right(createAnchor(QLatin1String("right"), aiRight)),
  25140. bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)),
  25141. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  25142. bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
  25143. left(createAnchor(QLatin1String("left"), aiLeft)),
  25144. mText(QLatin1String("text")),
  25145. mPositionAlignment(Qt::AlignCenter),
  25146. mTextAlignment(Qt::AlignTop|Qt::AlignHCenter),
  25147. mRotation(0)
  25148. {
  25149. position->setCoords(0, 0);
  25150. setPen(Qt::NoPen);
  25151. setSelectedPen(Qt::NoPen);
  25152. setBrush(Qt::NoBrush);
  25153. setSelectedBrush(Qt::NoBrush);
  25154. setColor(Qt::black);
  25155. setSelectedColor(Qt::blue);
  25156. }
  25157. QCPItemText::~QCPItemText()
  25158. {
  25159. }
  25160. /*!
  25161. Sets the color of the text.
  25162. */
  25163. void QCPItemText::setColor(const QColor &color)
  25164. {
  25165. mColor = color;
  25166. }
  25167. /*!
  25168. Sets the color of the text that will be used when the item is selected.
  25169. */
  25170. void QCPItemText::setSelectedColor(const QColor &color)
  25171. {
  25172. mSelectedColor = color;
  25173. }
  25174. /*!
  25175. Sets the pen that will be used do draw a rectangular border around the text. To disable the
  25176. border, set \a pen to Qt::NoPen.
  25177. \see setSelectedPen, setBrush, setPadding
  25178. */
  25179. void QCPItemText::setPen(const QPen &pen)
  25180. {
  25181. mPen = pen;
  25182. }
  25183. /*!
  25184. Sets the pen that will be used do draw a rectangular border around the text, when the item is
  25185. selected. To disable the border, set \a pen to Qt::NoPen.
  25186. \see setPen
  25187. */
  25188. void QCPItemText::setSelectedPen(const QPen &pen)
  25189. {
  25190. mSelectedPen = pen;
  25191. }
  25192. /*!
  25193. Sets the brush that will be used do fill the background of the text. To disable the
  25194. background, set \a brush to Qt::NoBrush.
  25195. \see setSelectedBrush, setPen, setPadding
  25196. */
  25197. void QCPItemText::setBrush(const QBrush &brush)
  25198. {
  25199. mBrush = brush;
  25200. }
  25201. /*!
  25202. Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the
  25203. background, set \a brush to Qt::NoBrush.
  25204. \see setBrush
  25205. */
  25206. void QCPItemText::setSelectedBrush(const QBrush &brush)
  25207. {
  25208. mSelectedBrush = brush;
  25209. }
  25210. /*!
  25211. Sets the font of the text.
  25212. \see setSelectedFont, setColor
  25213. */
  25214. void QCPItemText::setFont(const QFont &font)
  25215. {
  25216. mFont = font;
  25217. }
  25218. /*!
  25219. Sets the font of the text that will be used when the item is selected.
  25220. \see setFont
  25221. */
  25222. void QCPItemText::setSelectedFont(const QFont &font)
  25223. {
  25224. mSelectedFont = font;
  25225. }
  25226. /*!
  25227. Sets the text that will be displayed. Multi-line texts are supported by inserting a line break
  25228. character, e.g. '\n'.
  25229. \see setFont, setColor, setTextAlignment
  25230. */
  25231. void QCPItemText::setText(const QString &text)
  25232. {
  25233. mText = text;
  25234. }
  25235. /*!
  25236. Sets which point of the text rect shall be aligned with \a position.
  25237. Examples:
  25238. \li If \a alignment is <tt>Qt::AlignHCenter | Qt::AlignTop</tt>, the text will be positioned such
  25239. that the top of the text rect will be horizontally centered on \a position.
  25240. \li If \a alignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt>, \a position will indicate the
  25241. bottom left corner of the text rect.
  25242. If you want to control the alignment of (multi-lined) text within the text rect, use \ref
  25243. setTextAlignment.
  25244. */
  25245. void QCPItemText::setPositionAlignment(Qt::Alignment alignment)
  25246. {
  25247. mPositionAlignment = alignment;
  25248. }
  25249. /*!
  25250. Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or Qt::AlignRight).
  25251. */
  25252. void QCPItemText::setTextAlignment(Qt::Alignment alignment)
  25253. {
  25254. mTextAlignment = alignment;
  25255. }
  25256. /*!
  25257. Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated
  25258. around \a position.
  25259. */
  25260. void QCPItemText::setRotation(double degrees)
  25261. {
  25262. mRotation = degrees;
  25263. }
  25264. /*!
  25265. Sets the distance between the border of the text rectangle and the text. The appearance (and
  25266. visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush.
  25267. */
  25268. void QCPItemText::setPadding(const QMargins &padding)
  25269. {
  25270. mPadding = padding;
  25271. }
  25272. /* inherits documentation from base class */
  25273. double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25274. {
  25275. Q_UNUSED(details)
  25276. if (onlySelectable && !mSelectable)
  25277. return -1;
  25278. // The rect may be rotated, so we transform the actual clicked pos to the rotated
  25279. // coordinate system, so we can use the normal rectDistance function for non-rotated rects:
  25280. QPointF positionPixels(position->pixelPosition());
  25281. QTransform inputTransform;
  25282. inputTransform.translate(positionPixels.x(), positionPixels.y());
  25283. inputTransform.rotate(-mRotation);
  25284. inputTransform.translate(-positionPixels.x(), -positionPixels.y());
  25285. QPointF rotatedPos = inputTransform.map(pos);
  25286. QFontMetrics fontMetrics(mFont);
  25287. QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  25288. QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  25289. QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment);
  25290. textBoxRect.moveTopLeft(textPos.toPoint());
  25291. return rectDistance(textBoxRect, rotatedPos, true);
  25292. }
  25293. /* inherits documentation from base class */
  25294. void QCPItemText::draw(QCPPainter *painter)
  25295. {
  25296. QPointF pos(position->pixelPosition());
  25297. QTransform transform = painter->transform();
  25298. transform.translate(pos.x(), pos.y());
  25299. if (!qFuzzyIsNull(mRotation))
  25300. transform.rotate(mRotation);
  25301. painter->setFont(mainFont());
  25302. QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  25303. QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  25304. QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
  25305. textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top()));
  25306. textBoxRect.moveTopLeft(textPos.toPoint());
  25307. int clipPad = qCeil(mainPen().widthF());
  25308. QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  25309. if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect())))
  25310. {
  25311. painter->setTransform(transform);
  25312. if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) ||
  25313. (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0))
  25314. {
  25315. painter->setPen(mainPen());
  25316. painter->setBrush(mainBrush());
  25317. painter->drawRect(textBoxRect);
  25318. }
  25319. painter->setBrush(Qt::NoBrush);
  25320. painter->setPen(QPen(mainColor()));
  25321. painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText);
  25322. }
  25323. }
  25324. /* inherits documentation from base class */
  25325. QPointF QCPItemText::anchorPixelPosition(int anchorId) const
  25326. {
  25327. // get actual rect points (pretty much copied from draw function):
  25328. QPointF pos(position->pixelPosition());
  25329. QTransform transform;
  25330. transform.translate(pos.x(), pos.y());
  25331. if (!qFuzzyIsNull(mRotation))
  25332. transform.rotate(mRotation);
  25333. QFontMetrics fontMetrics(mainFont());
  25334. QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  25335. QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  25336. QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
  25337. textBoxRect.moveTopLeft(textPos.toPoint());
  25338. QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect));
  25339. switch (anchorId)
  25340. {
  25341. case aiTopLeft: return rectPoly.at(0);
  25342. case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5;
  25343. case aiTopRight: return rectPoly.at(1);
  25344. case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5;
  25345. case aiBottomRight: return rectPoly.at(2);
  25346. case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5;
  25347. case aiBottomLeft: return rectPoly.at(3);
  25348. case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5;
  25349. }
  25350. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  25351. return {};
  25352. }
  25353. /*! \internal
  25354. Returns the point that must be given to the QPainter::drawText function (which expects the top
  25355. left point of the text rect), according to the position \a pos, the text bounding box \a rect and
  25356. the requested \a positionAlignment.
  25357. For example, if \a positionAlignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt> the returned point
  25358. will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally
  25359. drawn at that point, the lower left corner of the resulting text rect is at \a pos.
  25360. */
  25361. QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const
  25362. {
  25363. if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop))
  25364. return pos;
  25365. QPointF result = pos; // start at top left
  25366. if (positionAlignment.testFlag(Qt::AlignHCenter))
  25367. result.rx() -= rect.width()/2.0;
  25368. else if (positionAlignment.testFlag(Qt::AlignRight))
  25369. result.rx() -= rect.width();
  25370. if (positionAlignment.testFlag(Qt::AlignVCenter))
  25371. result.ry() -= rect.height()/2.0;
  25372. else if (positionAlignment.testFlag(Qt::AlignBottom))
  25373. result.ry() -= rect.height();
  25374. return result;
  25375. }
  25376. /*! \internal
  25377. Returns the font that should be used for drawing text. Returns mFont when the item is not selected
  25378. and mSelectedFont when it is.
  25379. */
  25380. QFont QCPItemText::mainFont() const
  25381. {
  25382. return mSelected ? mSelectedFont : mFont;
  25383. }
  25384. /*! \internal
  25385. Returns the color that should be used for drawing text. Returns mColor when the item is not
  25386. selected and mSelectedColor when it is.
  25387. */
  25388. QColor QCPItemText::mainColor() const
  25389. {
  25390. return mSelected ? mSelectedColor : mColor;
  25391. }
  25392. /*! \internal
  25393. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  25394. and mSelectedPen when it is.
  25395. */
  25396. QPen QCPItemText::mainPen() const
  25397. {
  25398. return mSelected ? mSelectedPen : mPen;
  25399. }
  25400. /*! \internal
  25401. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  25402. is not selected and mSelectedBrush when it is.
  25403. */
  25404. QBrush QCPItemText::mainBrush() const
  25405. {
  25406. return mSelected ? mSelectedBrush : mBrush;
  25407. }
  25408. /* end of 'src/items/item-text.cpp' */
  25409. /* including file 'src/items/item-ellipse.cpp' */
  25410. /* modified 2022-11-06T12:45:56, size 7881 */
  25411. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25412. //////////////////// QCPItemEllipse
  25413. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25414. /*! \class QCPItemEllipse
  25415. \brief An ellipse
  25416. \image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions."
  25417. It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be drawn in.
  25418. */
  25419. /*!
  25420. Creates an ellipse item and sets default values.
  25421. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  25422. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  25423. */
  25424. QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) :
  25425. QCPAbstractItem(parentPlot),
  25426. topLeft(createPosition(QLatin1String("topLeft"))),
  25427. bottomRight(createPosition(QLatin1String("bottomRight"))),
  25428. topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim)),
  25429. top(createAnchor(QLatin1String("top"), aiTop)),
  25430. topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim)),
  25431. right(createAnchor(QLatin1String("right"), aiRight)),
  25432. bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim)),
  25433. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  25434. bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim)),
  25435. left(createAnchor(QLatin1String("left"), aiLeft)),
  25436. center(createAnchor(QLatin1String("center"), aiCenter))
  25437. {
  25438. topLeft->setCoords(0, 1);
  25439. bottomRight->setCoords(1, 0);
  25440. setPen(QPen(Qt::black));
  25441. setSelectedPen(QPen(Qt::blue, 2));
  25442. setBrush(Qt::NoBrush);
  25443. setSelectedBrush(Qt::NoBrush);
  25444. }
  25445. QCPItemEllipse::~QCPItemEllipse()
  25446. {
  25447. }
  25448. /*!
  25449. Sets the pen that will be used to draw the line of the ellipse
  25450. \see setSelectedPen, setBrush
  25451. */
  25452. void QCPItemEllipse::setPen(const QPen &pen)
  25453. {
  25454. mPen = pen;
  25455. }
  25456. /*!
  25457. Sets the pen that will be used to draw the line of the ellipse when selected
  25458. \see setPen, setSelected
  25459. */
  25460. void QCPItemEllipse::setSelectedPen(const QPen &pen)
  25461. {
  25462. mSelectedPen = pen;
  25463. }
  25464. /*!
  25465. Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to
  25466. Qt::NoBrush.
  25467. \see setSelectedBrush, setPen
  25468. */
  25469. void QCPItemEllipse::setBrush(const QBrush &brush)
  25470. {
  25471. mBrush = brush;
  25472. }
  25473. /*!
  25474. Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a
  25475. brush to Qt::NoBrush.
  25476. \see setBrush
  25477. */
  25478. void QCPItemEllipse::setSelectedBrush(const QBrush &brush)
  25479. {
  25480. mSelectedBrush = brush;
  25481. }
  25482. /* inherits documentation from base class */
  25483. double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25484. {
  25485. Q_UNUSED(details)
  25486. if (onlySelectable && !mSelectable)
  25487. return -1;
  25488. QPointF p1 = topLeft->pixelPosition();
  25489. QPointF p2 = bottomRight->pixelPosition();
  25490. QPointF center((p1+p2)/2.0);
  25491. double a = qAbs(p1.x()-p2.x())/2.0;
  25492. double b = qAbs(p1.y()-p2.y())/2.0;
  25493. double x = pos.x()-center.x();
  25494. double y = pos.y()-center.y();
  25495. // distance to border:
  25496. double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b));
  25497. double result = qAbs(c-1)*qSqrt(x*x+y*y);
  25498. // filled ellipse, allow click inside to count as hit:
  25499. if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
  25500. {
  25501. if (x*x/(a*a) + y*y/(b*b) <= 1)
  25502. result = mParentPlot->selectionTolerance()*0.99;
  25503. }
  25504. return result;
  25505. }
  25506. /* inherits documentation from base class */
  25507. void QCPItemEllipse::draw(QCPPainter *painter)
  25508. {
  25509. QPointF p1 = topLeft->pixelPosition();
  25510. QPointF p2 = bottomRight->pixelPosition();
  25511. if (p1.toPoint() == p2.toPoint())
  25512. return;
  25513. QRectF ellipseRect = QRectF(p1, p2).normalized();
  25514. const int clipEnlarge = qCeil(mainPen().widthF());
  25515. QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge);
  25516. if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect
  25517. {
  25518. painter->setPen(mainPen());
  25519. painter->setBrush(mainBrush());
  25520. #ifdef __EXCEPTIONS
  25521. try // drawEllipse sometimes throws exceptions if ellipse is too big
  25522. {
  25523. #endif
  25524. painter->drawEllipse(ellipseRect);
  25525. #ifdef __EXCEPTIONS
  25526. } catch (...)
  25527. {
  25528. qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible";
  25529. setVisible(false);
  25530. }
  25531. #endif
  25532. }
  25533. }
  25534. /* inherits documentation from base class */
  25535. QPointF QCPItemEllipse::anchorPixelPosition(int anchorId) const
  25536. {
  25537. QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition());
  25538. switch (anchorId)
  25539. {
  25540. case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2);
  25541. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  25542. case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2);
  25543. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  25544. case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2);
  25545. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  25546. case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2);
  25547. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
  25548. case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5;
  25549. }
  25550. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  25551. return {};
  25552. }
  25553. /*! \internal
  25554. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  25555. and mSelectedPen when it is.
  25556. */
  25557. QPen QCPItemEllipse::mainPen() const
  25558. {
  25559. return mSelected ? mSelectedPen : mPen;
  25560. }
  25561. /*! \internal
  25562. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  25563. is not selected and mSelectedBrush when it is.
  25564. */
  25565. QBrush QCPItemEllipse::mainBrush() const
  25566. {
  25567. return mSelected ? mSelectedBrush : mBrush;
  25568. }
  25569. /* end of 'src/items/item-ellipse.cpp' */
  25570. /* including file 'src/items/item-pixmap.cpp' */
  25571. /* modified 2022-11-06T12:45:56, size 10622 */
  25572. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25573. //////////////////// QCPItemPixmap
  25574. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25575. /*! \class QCPItemPixmap
  25576. \brief An arbitrary pixmap
  25577. \image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions."
  25578. It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will
  25579. be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to
  25580. fit the rectangle or be drawn aligned to the topLeft position.
  25581. If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown
  25582. on the right side of the example image), the pixmap will be flipped in the respective
  25583. orientations.
  25584. */
  25585. /*!
  25586. Creates a rectangle item and sets default values.
  25587. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  25588. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  25589. */
  25590. QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) :
  25591. QCPAbstractItem(parentPlot),
  25592. topLeft(createPosition(QLatin1String("topLeft"))),
  25593. bottomRight(createPosition(QLatin1String("bottomRight"))),
  25594. top(createAnchor(QLatin1String("top"), aiTop)),
  25595. topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
  25596. right(createAnchor(QLatin1String("right"), aiRight)),
  25597. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  25598. bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
  25599. left(createAnchor(QLatin1String("left"), aiLeft)),
  25600. mScaled(false),
  25601. mScaledPixmapInvalidated(true),
  25602. mAspectRatioMode(Qt::KeepAspectRatio),
  25603. mTransformationMode(Qt::SmoothTransformation)
  25604. {
  25605. topLeft->setCoords(0, 1);
  25606. bottomRight->setCoords(1, 0);
  25607. setPen(Qt::NoPen);
  25608. setSelectedPen(QPen(Qt::blue));
  25609. }
  25610. QCPItemPixmap::~QCPItemPixmap()
  25611. {
  25612. }
  25613. /*!
  25614. Sets the pixmap that will be displayed.
  25615. */
  25616. void QCPItemPixmap::setPixmap(const QPixmap &pixmap)
  25617. {
  25618. mPixmap = pixmap;
  25619. mScaledPixmapInvalidated = true;
  25620. if (mPixmap.isNull())
  25621. qDebug() << Q_FUNC_INFO << "pixmap is null";
  25622. }
  25623. /*!
  25624. Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a
  25625. bottomRight positions.
  25626. */
  25627. void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformationMode)
  25628. {
  25629. mScaled = scaled;
  25630. mAspectRatioMode = aspectRatioMode;
  25631. mTransformationMode = transformationMode;
  25632. mScaledPixmapInvalidated = true;
  25633. }
  25634. /*!
  25635. Sets the pen that will be used to draw a border around the pixmap.
  25636. \see setSelectedPen, setBrush
  25637. */
  25638. void QCPItemPixmap::setPen(const QPen &pen)
  25639. {
  25640. mPen = pen;
  25641. }
  25642. /*!
  25643. Sets the pen that will be used to draw a border around the pixmap when selected
  25644. \see setPen, setSelected
  25645. */
  25646. void QCPItemPixmap::setSelectedPen(const QPen &pen)
  25647. {
  25648. mSelectedPen = pen;
  25649. }
  25650. /* inherits documentation from base class */
  25651. double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25652. {
  25653. Q_UNUSED(details)
  25654. if (onlySelectable && !mSelectable)
  25655. return -1;
  25656. return rectDistance(getFinalRect(), pos, true);
  25657. }
  25658. /* inherits documentation from base class */
  25659. void QCPItemPixmap::draw(QCPPainter *painter)
  25660. {
  25661. bool flipHorz = false;
  25662. bool flipVert = false;
  25663. QRect rect = getFinalRect(&flipHorz, &flipVert);
  25664. int clipPad = mainPen().style() == Qt::NoPen ? 0 : qCeil(mainPen().widthF());
  25665. QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  25666. if (boundingRect.intersects(clipRect()))
  25667. {
  25668. updateScaledPixmap(rect, flipHorz, flipVert);
  25669. painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap);
  25670. QPen pen = mainPen();
  25671. if (pen.style() != Qt::NoPen)
  25672. {
  25673. painter->setPen(pen);
  25674. painter->setBrush(Qt::NoBrush);
  25675. painter->drawRect(rect);
  25676. }
  25677. }
  25678. }
  25679. /* inherits documentation from base class */
  25680. QPointF QCPItemPixmap::anchorPixelPosition(int anchorId) const
  25681. {
  25682. bool flipHorz = false;
  25683. bool flipVert = false;
  25684. QRect rect = getFinalRect(&flipHorz, &flipVert);
  25685. // we actually want denormal rects (negative width/height) here, so restore
  25686. // the flipped state:
  25687. if (flipHorz)
  25688. rect.adjust(rect.width(), 0, -rect.width(), 0);
  25689. if (flipVert)
  25690. rect.adjust(0, rect.height(), 0, -rect.height());
  25691. switch (anchorId)
  25692. {
  25693. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  25694. case aiTopRight: return rect.topRight();
  25695. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  25696. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  25697. case aiBottomLeft: return rect.bottomLeft();
  25698. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
  25699. }
  25700. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  25701. return {};
  25702. }
  25703. /*! \internal
  25704. Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The
  25705. parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped
  25706. horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a
  25707. bottomRight.)
  25708. This function only creates the scaled pixmap when the buffered pixmap has a different size than
  25709. the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does
  25710. not cause expensive rescaling every time.
  25711. If scaling is disabled, sets mScaledPixmap to a null QPixmap.
  25712. */
  25713. void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert)
  25714. {
  25715. if (mPixmap.isNull())
  25716. return;
  25717. if (mScaled)
  25718. {
  25719. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  25720. double devicePixelRatio = mPixmap.devicePixelRatio();
  25721. #else
  25722. double devicePixelRatio = 1.0;
  25723. #endif
  25724. if (finalRect.isNull())
  25725. finalRect = getFinalRect(&flipHorz, &flipVert);
  25726. if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size()/devicePixelRatio)
  25727. {
  25728. mScaledPixmap = mPixmap.scaled(finalRect.size()*devicePixelRatio, mAspectRatioMode, mTransformationMode);
  25729. if (flipHorz || flipVert)
  25730. mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert));
  25731. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  25732. mScaledPixmap.setDevicePixelRatio(devicePixelRatio);
  25733. #endif
  25734. }
  25735. } else if (!mScaledPixmap.isNull())
  25736. mScaledPixmap = QPixmap();
  25737. mScaledPixmapInvalidated = false;
  25738. }
  25739. /*! \internal
  25740. Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions
  25741. and scaling settings.
  25742. The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn
  25743. flipped horizontally or vertically in the returned rect. (The returned rect itself is always
  25744. normalized, i.e. the top left corner of the rect is actually further to the top/left than the
  25745. bottom right corner). This is the case when the item position \a topLeft is further to the
  25746. bottom/right than \a bottomRight.
  25747. If scaling is disabled, returns a rect with size of the original pixmap and the top left corner
  25748. aligned with the item position \a topLeft. The position \a bottomRight is ignored.
  25749. */
  25750. QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const
  25751. {
  25752. QRect result;
  25753. bool flipHorz = false;
  25754. bool flipVert = false;
  25755. QPoint p1 = topLeft->pixelPosition().toPoint();
  25756. QPoint p2 = bottomRight->pixelPosition().toPoint();
  25757. if (p1 == p2)
  25758. return {p1, QSize(0, 0)};
  25759. if (mScaled)
  25760. {
  25761. QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y());
  25762. QPoint topLeft = p1;
  25763. if (newSize.width() < 0)
  25764. {
  25765. flipHorz = true;
  25766. newSize.rwidth() *= -1;
  25767. topLeft.setX(p2.x());
  25768. }
  25769. if (newSize.height() < 0)
  25770. {
  25771. flipVert = true;
  25772. newSize.rheight() *= -1;
  25773. topLeft.setY(p2.y());
  25774. }
  25775. QSize scaledSize = mPixmap.size();
  25776. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  25777. scaledSize /= mPixmap.devicePixelRatio();
  25778. scaledSize.scale(newSize*mPixmap.devicePixelRatio(), mAspectRatioMode);
  25779. #else
  25780. scaledSize.scale(newSize, mAspectRatioMode);
  25781. #endif
  25782. result = QRect(topLeft, scaledSize);
  25783. } else
  25784. {
  25785. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  25786. result = QRect(p1, mPixmap.size()/mPixmap.devicePixelRatio());
  25787. #else
  25788. result = QRect(p1, mPixmap.size());
  25789. #endif
  25790. }
  25791. if (flippedHorz)
  25792. *flippedHorz = flipHorz;
  25793. if (flippedVert)
  25794. *flippedVert = flipVert;
  25795. return result;
  25796. }
  25797. /*! \internal
  25798. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  25799. and mSelectedPen when it is.
  25800. */
  25801. QPen QCPItemPixmap::mainPen() const
  25802. {
  25803. return mSelected ? mSelectedPen : mPen;
  25804. }
  25805. /* end of 'src/items/item-pixmap.cpp' */
  25806. /* including file 'src/items/item-tracer.cpp' */
  25807. /* modified 2022-11-06T12:45:56, size 14645 */
  25808. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25809. //////////////////// QCPItemTracer
  25810. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25811. /*! \class QCPItemTracer
  25812. \brief Item that sticks to QCPGraph data points
  25813. \image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs are positions."
  25814. The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt
  25815. the coordinate axes of the graph and update its \a position to be on the graph's data. This means
  25816. the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a
  25817. QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a
  25818. position will have no effect because they will be overriden in the next redraw (this is when the
  25819. coordinate update happens).
  25820. If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will
  25821. stay at the corresponding end of the graph.
  25822. With \ref setInterpolating you may specify whether the tracer may only stay exactly on data
  25823. points or whether it interpolates data points linearly, if given a key that lies between two data
  25824. points of the graph.
  25825. The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer
  25826. have no own visual appearance (set the style to \ref tsNone), and just connect other item
  25827. positions to the tracer \a position (used as an anchor) via \ref
  25828. QCPItemPosition::setParentAnchor.
  25829. \note The tracer position is only automatically updated upon redraws. So when the data of the
  25830. graph changes and immediately afterwards (without a redraw) the position coordinates of the
  25831. tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref
  25832. updatePosition must be called manually, prior to reading the tracer coordinates.
  25833. */
  25834. /*!
  25835. Creates a tracer item and sets default values.
  25836. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  25837. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  25838. */
  25839. QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) :
  25840. QCPAbstractItem(parentPlot),
  25841. position(createPosition(QLatin1String("position"))),
  25842. mSize(6),
  25843. mStyle(tsCrosshair),
  25844. mGraph(nullptr),
  25845. mGraphKey(0),
  25846. mInterpolating(false)
  25847. {
  25848. position->setCoords(0, 0);
  25849. setBrush(Qt::NoBrush);
  25850. setSelectedBrush(Qt::NoBrush);
  25851. setPen(QPen(Qt::black));
  25852. setSelectedPen(QPen(Qt::blue, 2));
  25853. }
  25854. QCPItemTracer::~QCPItemTracer()
  25855. {
  25856. }
  25857. /*!
  25858. Sets the pen that will be used to draw the line of the tracer
  25859. \see setSelectedPen, setBrush
  25860. */
  25861. void QCPItemTracer::setPen(const QPen &pen)
  25862. {
  25863. mPen = pen;
  25864. }
  25865. /*!
  25866. Sets the pen that will be used to draw the line of the tracer when selected
  25867. \see setPen, setSelected
  25868. */
  25869. void QCPItemTracer::setSelectedPen(const QPen &pen)
  25870. {
  25871. mSelectedPen = pen;
  25872. }
  25873. /*!
  25874. Sets the brush that will be used to draw any fills of the tracer
  25875. \see setSelectedBrush, setPen
  25876. */
  25877. void QCPItemTracer::setBrush(const QBrush &brush)
  25878. {
  25879. mBrush = brush;
  25880. }
  25881. /*!
  25882. Sets the brush that will be used to draw any fills of the tracer, when selected.
  25883. \see setBrush, setSelected
  25884. */
  25885. void QCPItemTracer::setSelectedBrush(const QBrush &brush)
  25886. {
  25887. mSelectedBrush = brush;
  25888. }
  25889. /*!
  25890. Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare
  25891. does, \ref tsCrosshair does not).
  25892. */
  25893. void QCPItemTracer::setSize(double size)
  25894. {
  25895. mSize = size;
  25896. }
  25897. /*!
  25898. Sets the style/visual appearance of the tracer.
  25899. If you only want to use the tracer \a position as an anchor for other items, set \a style to
  25900. \ref tsNone.
  25901. */
  25902. void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style)
  25903. {
  25904. mStyle = style;
  25905. }
  25906. /*!
  25907. Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type
  25908. QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph.
  25909. To free the tracer from any graph, set \a graph to \c nullptr. The tracer \a position can then be
  25910. placed freely like any other item position. This is the state the tracer will assume when its
  25911. graph gets deleted while still attached to it.
  25912. \see setGraphKey
  25913. */
  25914. void QCPItemTracer::setGraph(QCPGraph *graph)
  25915. {
  25916. if (graph)
  25917. {
  25918. if (graph->parentPlot() == mParentPlot)
  25919. {
  25920. position->setType(QCPItemPosition::ptPlotCoords);
  25921. position->setAxes(graph->keyAxis(), graph->valueAxis());
  25922. mGraph = graph;
  25923. updatePosition();
  25924. } else
  25925. qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item";
  25926. } else
  25927. {
  25928. mGraph = nullptr;
  25929. }
  25930. }
  25931. /*!
  25932. Sets the key of the graph's data point the tracer will be positioned at. This is the only free
  25933. coordinate of a tracer when attached to a graph.
  25934. Depending on \ref setInterpolating, the tracer will be either positioned on the data point
  25935. closest to \a key, or will stay exactly at \a key and interpolate the value linearly.
  25936. \see setGraph, setInterpolating
  25937. */
  25938. void QCPItemTracer::setGraphKey(double key)
  25939. {
  25940. mGraphKey = key;
  25941. }
  25942. /*!
  25943. Sets whether the value of the graph's data points shall be interpolated, when positioning the
  25944. tracer.
  25945. If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on
  25946. the data point of the graph which is closest to the key, but which is not necessarily exactly
  25947. there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and
  25948. the appropriate value will be interpolated from the graph's data points linearly.
  25949. \see setGraph, setGraphKey
  25950. */
  25951. void QCPItemTracer::setInterpolating(bool enabled)
  25952. {
  25953. mInterpolating = enabled;
  25954. }
  25955. /* inherits documentation from base class */
  25956. double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25957. {
  25958. Q_UNUSED(details)
  25959. if (onlySelectable && !mSelectable)
  25960. return -1;
  25961. QPointF center(position->pixelPosition());
  25962. double w = mSize/2.0;
  25963. QRect clip = clipRect();
  25964. switch (mStyle)
  25965. {
  25966. case tsNone: return -1;
  25967. case tsPlus:
  25968. {
  25969. if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  25970. return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(center+QPointF(-w, 0), center+QPointF(w, 0)),
  25971. QCPVector2D(pos).distanceSquaredToLine(center+QPointF(0, -w), center+QPointF(0, w))));
  25972. break;
  25973. }
  25974. case tsCrosshair:
  25975. {
  25976. return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(clip.left(), center.y()), QCPVector2D(clip.right(), center.y())),
  25977. QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(center.x(), clip.top()), QCPVector2D(center.x(), clip.bottom()))));
  25978. }
  25979. case tsCircle:
  25980. {
  25981. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  25982. {
  25983. // distance to border:
  25984. double centerDist = QCPVector2D(center-pos).length();
  25985. double circleLine = w;
  25986. double result = qAbs(centerDist-circleLine);
  25987. // filled ellipse, allow click inside to count as hit:
  25988. if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
  25989. {
  25990. if (centerDist <= circleLine)
  25991. result = mParentPlot->selectionTolerance()*0.99;
  25992. }
  25993. return result;
  25994. }
  25995. break;
  25996. }
  25997. case tsSquare:
  25998. {
  25999. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  26000. {
  26001. QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w));
  26002. bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
  26003. return rectDistance(rect, pos, filledRect);
  26004. }
  26005. break;
  26006. }
  26007. }
  26008. return -1;
  26009. }
  26010. /* inherits documentation from base class */
  26011. void QCPItemTracer::draw(QCPPainter *painter)
  26012. {
  26013. updatePosition();
  26014. if (mStyle == tsNone)
  26015. return;
  26016. painter->setPen(mainPen());
  26017. painter->setBrush(mainBrush());
  26018. QPointF center(position->pixelPosition());
  26019. double w = mSize/2.0;
  26020. QRect clip = clipRect();
  26021. switch (mStyle)
  26022. {
  26023. case tsNone: return;
  26024. case tsPlus:
  26025. {
  26026. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  26027. {
  26028. painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0)));
  26029. painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w)));
  26030. }
  26031. break;
  26032. }
  26033. case tsCrosshair:
  26034. {
  26035. if (center.y() > clip.top() && center.y() < clip.bottom())
  26036. painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y()));
  26037. if (center.x() > clip.left() && center.x() < clip.right())
  26038. painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom()));
  26039. break;
  26040. }
  26041. case tsCircle:
  26042. {
  26043. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  26044. painter->drawEllipse(center, w, w);
  26045. break;
  26046. }
  26047. case tsSquare:
  26048. {
  26049. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  26050. painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w)));
  26051. break;
  26052. }
  26053. }
  26054. }
  26055. /*!
  26056. If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a
  26057. position to reside on the graph data, depending on the configured key (\ref setGraphKey).
  26058. It is called automatically on every redraw and normally doesn't need to be called manually. One
  26059. exception is when you want to read the tracer coordinates via \a position and are not sure that
  26060. the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw.
  26061. In that situation, call this function before accessing \a position, to make sure you don't get
  26062. out-of-date coordinates.
  26063. If there is no graph set on this tracer, this function does nothing.
  26064. */
  26065. void QCPItemTracer::updatePosition()
  26066. {
  26067. if (mGraph)
  26068. {
  26069. if (mParentPlot->hasPlottable(mGraph))
  26070. {
  26071. if (mGraph->data()->size() > 1)
  26072. {
  26073. QCPGraphDataContainer::const_iterator first = mGraph->data()->constBegin();
  26074. QCPGraphDataContainer::const_iterator last = mGraph->data()->constEnd()-1;
  26075. if (mGraphKey <= first->key)
  26076. position->setCoords(first->key, first->value);
  26077. else if (mGraphKey >= last->key)
  26078. position->setCoords(last->key, last->value);
  26079. else
  26080. {
  26081. QCPGraphDataContainer::const_iterator it = mGraph->data()->findBegin(mGraphKey);
  26082. if (it != mGraph->data()->constEnd()) // mGraphKey is not exactly on last iterator, but somewhere between iterators
  26083. {
  26084. QCPGraphDataContainer::const_iterator prevIt = it;
  26085. ++it; // won't advance to constEnd because we handled that case (mGraphKey >= last->key) before
  26086. if (mInterpolating)
  26087. {
  26088. // interpolate between iterators around mGraphKey:
  26089. double slope = 0;
  26090. if (!qFuzzyCompare(double(it->key), double(prevIt->key)))
  26091. slope = (it->value-prevIt->value)/(it->key-prevIt->key);
  26092. position->setCoords(mGraphKey, (mGraphKey-prevIt->key)*slope+prevIt->value);
  26093. } else
  26094. {
  26095. // find iterator with key closest to mGraphKey:
  26096. if (mGraphKey < (prevIt->key+it->key)*0.5)
  26097. position->setCoords(prevIt->key, prevIt->value);
  26098. else
  26099. position->setCoords(it->key, it->value);
  26100. }
  26101. } else // mGraphKey is exactly on last iterator (should actually be caught when comparing first/last keys, but this is a failsafe for fp uncertainty)
  26102. position->setCoords(it->key, it->value);
  26103. }
  26104. } else if (mGraph->data()->size() == 1)
  26105. {
  26106. QCPGraphDataContainer::const_iterator it = mGraph->data()->constBegin();
  26107. position->setCoords(it->key, it->value);
  26108. } else
  26109. qDebug() << Q_FUNC_INFO << "graph has no data";
  26110. } else
  26111. qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)";
  26112. }
  26113. }
  26114. /*! \internal
  26115. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  26116. and mSelectedPen when it is.
  26117. */
  26118. QPen QCPItemTracer::mainPen() const
  26119. {
  26120. return mSelected ? mSelectedPen : mPen;
  26121. }
  26122. /*! \internal
  26123. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  26124. is not selected and mSelectedBrush when it is.
  26125. */
  26126. QBrush QCPItemTracer::mainBrush() const
  26127. {
  26128. return mSelected ? mSelectedBrush : mBrush;
  26129. }
  26130. /* end of 'src/items/item-tracer.cpp' */
  26131. /* including file 'src/items/item-bracket.cpp' */
  26132. /* modified 2022-11-06T12:45:56, size 10705 */
  26133. ////////////////////////////////////////////////////////////////////////////////////////////////////
  26134. //////////////////// QCPItemBracket
  26135. ////////////////////////////////////////////////////////////////////////////////////////////////////
  26136. /*! \class QCPItemBracket
  26137. \brief A bracket for referencing/highlighting certain parts in the plot.
  26138. \image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs are positions."
  26139. It has two positions, \a left and \a right, which define the span of the bracket. If \a left is
  26140. actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the
  26141. example image.
  26142. The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket
  26143. stretches away from the embraced span, can be controlled with \ref setLength.
  26144. \image html QCPItemBracket-length.png
  26145. <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
  26146. bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
  26147. It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine
  26148. or QCPItemCurve) or a text label (QCPItemText), to the bracket.
  26149. */
  26150. /*!
  26151. Creates a bracket item and sets default values.
  26152. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  26153. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  26154. */
  26155. QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) :
  26156. QCPAbstractItem(parentPlot),
  26157. left(createPosition(QLatin1String("left"))),
  26158. right(createPosition(QLatin1String("right"))),
  26159. center(createAnchor(QLatin1String("center"), aiCenter)),
  26160. mLength(8),
  26161. mStyle(bsCalligraphic)
  26162. {
  26163. left->setCoords(0, 0);
  26164. right->setCoords(1, 1);
  26165. setPen(QPen(Qt::black));
  26166. setSelectedPen(QPen(Qt::blue, 2));
  26167. }
  26168. QCPItemBracket::~QCPItemBracket()
  26169. {
  26170. }
  26171. /*!
  26172. Sets the pen that will be used to draw the bracket.
  26173. Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the
  26174. stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use
  26175. \ref setLength, which has a similar effect.
  26176. \see setSelectedPen
  26177. */
  26178. void QCPItemBracket::setPen(const QPen &pen)
  26179. {
  26180. mPen = pen;
  26181. }
  26182. /*!
  26183. Sets the pen that will be used to draw the bracket when selected
  26184. \see setPen, setSelected
  26185. */
  26186. void QCPItemBracket::setSelectedPen(const QPen &pen)
  26187. {
  26188. mSelectedPen = pen;
  26189. }
  26190. /*!
  26191. Sets the \a length in pixels how far the bracket extends in the direction towards the embraced
  26192. span of the bracket (i.e. perpendicular to the <i>left</i>-<i>right</i>-direction)
  26193. \image html QCPItemBracket-length.png
  26194. <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
  26195. bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
  26196. */
  26197. void QCPItemBracket::setLength(double length)
  26198. {
  26199. mLength = length;
  26200. }
  26201. /*!
  26202. Sets the style of the bracket, i.e. the shape/visual appearance.
  26203. \see setPen
  26204. */
  26205. void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style)
  26206. {
  26207. mStyle = style;
  26208. }
  26209. /* inherits documentation from base class */
  26210. double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  26211. {
  26212. Q_UNUSED(details)
  26213. if (onlySelectable && !mSelectable)
  26214. return -1;
  26215. QCPVector2D p(pos);
  26216. QCPVector2D leftVec(left->pixelPosition());
  26217. QCPVector2D rightVec(right->pixelPosition());
  26218. if (leftVec.toPoint() == rightVec.toPoint())
  26219. return -1;
  26220. QCPVector2D widthVec = (rightVec-leftVec)*0.5;
  26221. QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
  26222. QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
  26223. switch (mStyle)
  26224. {
  26225. case QCPItemBracket::bsSquare:
  26226. case QCPItemBracket::bsRound:
  26227. {
  26228. double a = p.distanceSquaredToLine(centerVec-widthVec, centerVec+widthVec);
  26229. double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec, centerVec-widthVec);
  26230. double c = p.distanceSquaredToLine(centerVec+widthVec+lengthVec, centerVec+widthVec);
  26231. return qSqrt(qMin(qMin(a, b), c));
  26232. }
  26233. case QCPItemBracket::bsCurly:
  26234. case QCPItemBracket::bsCalligraphic:
  26235. {
  26236. double a = p.distanceSquaredToLine(centerVec-widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3);
  26237. double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec*0.7, centerVec-widthVec*0.75+lengthVec*0.15);
  26238. double c = p.distanceSquaredToLine(centerVec+widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3);
  26239. double d = p.distanceSquaredToLine(centerVec+widthVec+lengthVec*0.7, centerVec+widthVec*0.75+lengthVec*0.15);
  26240. return qSqrt(qMin(qMin(a, b), qMin(c, d)));
  26241. }
  26242. }
  26243. return -1;
  26244. }
  26245. /* inherits documentation from base class */
  26246. void QCPItemBracket::draw(QCPPainter *painter)
  26247. {
  26248. QCPVector2D leftVec(left->pixelPosition());
  26249. QCPVector2D rightVec(right->pixelPosition());
  26250. if (leftVec.toPoint() == rightVec.toPoint())
  26251. return;
  26252. QCPVector2D widthVec = (rightVec-leftVec)*0.5;
  26253. QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
  26254. QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
  26255. QPolygon boundingPoly;
  26256. boundingPoly << leftVec.toPoint() << rightVec.toPoint()
  26257. << (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint();
  26258. const int clipEnlarge = qCeil(mainPen().widthF());
  26259. QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge);
  26260. if (clip.intersects(boundingPoly.boundingRect()))
  26261. {
  26262. painter->setPen(mainPen());
  26263. switch (mStyle)
  26264. {
  26265. case bsSquare:
  26266. {
  26267. painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF());
  26268. painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
  26269. painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  26270. break;
  26271. }
  26272. case bsRound:
  26273. {
  26274. painter->setBrush(Qt::NoBrush);
  26275. QPainterPath path;
  26276. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  26277. path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF());
  26278. path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  26279. painter->drawPath(path);
  26280. break;
  26281. }
  26282. case bsCurly:
  26283. {
  26284. painter->setBrush(Qt::NoBrush);
  26285. QPainterPath path;
  26286. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  26287. path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+lengthVec).toPointF(), centerVec.toPointF());
  26288. path.cubicTo((centerVec-0.4*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  26289. painter->drawPath(path);
  26290. break;
  26291. }
  26292. case bsCalligraphic:
  26293. {
  26294. painter->setPen(Qt::NoPen);
  26295. painter->setBrush(QBrush(mainPen().color()));
  26296. QPainterPath path;
  26297. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  26298. path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+0.8*lengthVec).toPointF(), centerVec.toPointF());
  26299. path.cubicTo((centerVec-0.4*widthVec+0.8*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  26300. path.cubicTo((centerVec-widthVec-lengthVec*0.5).toPointF(), (centerVec-0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+lengthVec*0.2).toPointF());
  26301. path.cubicTo((centerVec+0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
  26302. painter->drawPath(path);
  26303. break;
  26304. }
  26305. }
  26306. }
  26307. }
  26308. /* inherits documentation from base class */
  26309. QPointF QCPItemBracket::anchorPixelPosition(int anchorId) const
  26310. {
  26311. QCPVector2D leftVec(left->pixelPosition());
  26312. QCPVector2D rightVec(right->pixelPosition());
  26313. if (leftVec.toPoint() == rightVec.toPoint())
  26314. return leftVec.toPointF();
  26315. QCPVector2D widthVec = (rightVec-leftVec)*0.5;
  26316. QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
  26317. QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
  26318. switch (anchorId)
  26319. {
  26320. case aiCenter:
  26321. return centerVec.toPointF();
  26322. }
  26323. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  26324. return {};
  26325. }
  26326. /*! \internal
  26327. Returns the pen that should be used for drawing lines. Returns mPen when the
  26328. item is not selected and mSelectedPen when it is.
  26329. */
  26330. QPen QCPItemBracket::mainPen() const
  26331. {
  26332. return mSelected ? mSelectedPen : mPen;
  26333. }
  26334. /* end of 'src/items/item-bracket.cpp' */
  26335. /* including file 'src/polar/radialaxis.cpp' */
  26336. /* modified 2022-11-06T12:45:57, size 49415 */
  26337. ////////////////////////////////////////////////////////////////////////////////////////////////////
  26338. //////////////////// QCPPolarAxisRadial
  26339. ////////////////////////////////////////////////////////////////////////////////////////////////////
  26340. /*! \class QCPPolarAxisRadial
  26341. \brief The radial axis inside a radial plot
  26342. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  26343. functionality to be incomplete, as well as changing public interfaces in the future.
  26344. Each axis holds an instance of QCPAxisTicker which is used to generate the tick coordinates and
  26345. tick labels. You can access the currently installed \ref ticker or set a new one (possibly one of
  26346. the specialized subclasses, or your own subclass) via \ref setTicker. For details, see the
  26347. documentation of QCPAxisTicker.
  26348. */
  26349. /* start of documentation of inline functions */
  26350. /*! \fn QSharedPointer<QCPAxisTicker> QCPPolarAxisRadial::ticker() const
  26351. Returns a modifiable shared pointer to the currently installed axis ticker. The axis ticker is
  26352. responsible for generating the tick positions and tick labels of this axis. You can access the
  26353. \ref QCPAxisTicker with this method and modify basic properties such as the approximate tick count
  26354. (\ref QCPAxisTicker::setTickCount).
  26355. You can gain more control over the axis ticks by setting a different \ref QCPAxisTicker subclass, see
  26356. the documentation there. A new axis ticker can be set with \ref setTicker.
  26357. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  26358. ticker simply by passing the same shared pointer to multiple axes.
  26359. \see setTicker
  26360. */
  26361. /* end of documentation of inline functions */
  26362. /* start of documentation of signals */
  26363. /*! \fn void QCPPolarAxisRadial::rangeChanged(const QCPRange &newRange)
  26364. This signal is emitted when the range of this axis has changed. You can connect it to the \ref
  26365. setRange slot of another axis to communicate the new range to the other axis, in order for it to
  26366. be synchronized.
  26367. You may also manipulate/correct the range with \ref setRange in a slot connected to this signal.
  26368. This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper
  26369. range shouldn't go beyond certain values (see \ref QCPRange::bounded). For example, the following
  26370. slot would limit the x axis to ranges between 0 and 10:
  26371. \code
  26372. customPlot->xAxis->setRange(newRange.bounded(0, 10))
  26373. \endcode
  26374. */
  26375. /*! \fn void QCPPolarAxisRadial::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange)
  26376. \overload
  26377. Additionally to the new range, this signal also provides the previous range held by the axis as
  26378. \a oldRange.
  26379. */
  26380. /*! \fn void QCPPolarAxisRadial::scaleTypeChanged(QCPPolarAxisRadial::ScaleType scaleType);
  26381. This signal is emitted when the scale type changes, by calls to \ref setScaleType
  26382. */
  26383. /*! \fn void QCPPolarAxisRadial::selectionChanged(QCPPolarAxisRadial::SelectableParts selection)
  26384. This signal is emitted when the selection state of this axis has changed, either by user interaction
  26385. or by a direct call to \ref setSelectedParts.
  26386. */
  26387. /*! \fn void QCPPolarAxisRadial::selectableChanged(const QCPPolarAxisRadial::SelectableParts &parts);
  26388. This signal is emitted when the selectability changes, by calls to \ref setSelectableParts
  26389. */
  26390. /* end of documentation of signals */
  26391. /*!
  26392. Constructs an Axis instance of Type \a type for the axis rect \a parent.
  26393. Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create
  26394. them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however,
  26395. create them manually and then inject them also via \ref QCPAxisRect::addAxis.
  26396. */
  26397. QCPPolarAxisRadial::QCPPolarAxisRadial(QCPPolarAxisAngular *parent) :
  26398. QCPLayerable(parent->parentPlot(), QString(), parent),
  26399. mRangeDrag(true),
  26400. mRangeZoom(true),
  26401. mRangeZoomFactor(0.85),
  26402. // axis base:
  26403. mAngularAxis(parent),
  26404. mAngle(45),
  26405. mAngleReference(arAngularAxis),
  26406. mSelectableParts(spAxis | spTickLabels | spAxisLabel),
  26407. mSelectedParts(spNone),
  26408. mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  26409. mSelectedBasePen(QPen(Qt::blue, 2)),
  26410. // axis label:
  26411. mLabelPadding(0),
  26412. mLabel(),
  26413. mLabelFont(mParentPlot->font()),
  26414. mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
  26415. mLabelColor(Qt::black),
  26416. mSelectedLabelColor(Qt::blue),
  26417. // tick labels:
  26418. // mTickLabelPadding(0), in label painter
  26419. mTickLabels(true),
  26420. // mTickLabelRotation(0), in label painter
  26421. mTickLabelFont(mParentPlot->font()),
  26422. mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
  26423. mTickLabelColor(Qt::black),
  26424. mSelectedTickLabelColor(Qt::blue),
  26425. mNumberPrecision(6),
  26426. mNumberFormatChar('g'),
  26427. mNumberBeautifulPowers(true),
  26428. mNumberMultiplyCross(false),
  26429. // ticks and subticks:
  26430. mTicks(true),
  26431. mSubTicks(true),
  26432. mTickLengthIn(5),
  26433. mTickLengthOut(0),
  26434. mSubTickLengthIn(2),
  26435. mSubTickLengthOut(0),
  26436. mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  26437. mSelectedTickPen(QPen(Qt::blue, 2)),
  26438. mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  26439. mSelectedSubTickPen(QPen(Qt::blue, 2)),
  26440. // scale and range:
  26441. mRange(0, 5),
  26442. mRangeReversed(false),
  26443. mScaleType(stLinear),
  26444. // internal members:
  26445. mRadius(1), // non-zero initial value, will be overwritten in ::update() according to inner rect
  26446. mTicker(new QCPAxisTicker),
  26447. mLabelPainter(mParentPlot)
  26448. {
  26449. setParent(parent);
  26450. setAntialiased(true);
  26451. setTickLabelPadding(5);
  26452. setTickLabelRotation(0);
  26453. setTickLabelMode(lmUpright);
  26454. mLabelPainter.setAnchorReferenceType(QCPLabelPainterPrivate::artTangent);
  26455. mLabelPainter.setAbbreviateDecimalPowers(false);
  26456. }
  26457. QCPPolarAxisRadial::~QCPPolarAxisRadial()
  26458. {
  26459. }
  26460. QCPPolarAxisRadial::LabelMode QCPPolarAxisRadial::tickLabelMode() const
  26461. {
  26462. switch (mLabelPainter.anchorMode())
  26463. {
  26464. case QCPLabelPainterPrivate::amSkewedUpright: return lmUpright;
  26465. case QCPLabelPainterPrivate::amSkewedRotated: return lmRotated;
  26466. default: qDebug() << Q_FUNC_INFO << "invalid mode for polar axis"; break;
  26467. }
  26468. return lmUpright;
  26469. }
  26470. /* No documentation as it is a property getter */
  26471. QString QCPPolarAxisRadial::numberFormat() const
  26472. {
  26473. QString result;
  26474. result.append(mNumberFormatChar);
  26475. if (mNumberBeautifulPowers)
  26476. {
  26477. result.append(QLatin1Char('b'));
  26478. if (mNumberMultiplyCross)
  26479. result.append(QLatin1Char('c'));
  26480. }
  26481. return result;
  26482. }
  26483. /* No documentation as it is a property getter */
  26484. int QCPPolarAxisRadial::tickLengthIn() const
  26485. {
  26486. return mTickLengthIn;
  26487. }
  26488. /* No documentation as it is a property getter */
  26489. int QCPPolarAxisRadial::tickLengthOut() const
  26490. {
  26491. return mTickLengthOut;
  26492. }
  26493. /* No documentation as it is a property getter */
  26494. int QCPPolarAxisRadial::subTickLengthIn() const
  26495. {
  26496. return mSubTickLengthIn;
  26497. }
  26498. /* No documentation as it is a property getter */
  26499. int QCPPolarAxisRadial::subTickLengthOut() const
  26500. {
  26501. return mSubTickLengthOut;
  26502. }
  26503. /* No documentation as it is a property getter */
  26504. int QCPPolarAxisRadial::labelPadding() const
  26505. {
  26506. return mLabelPadding;
  26507. }
  26508. void QCPPolarAxisRadial::setRangeDrag(bool enabled)
  26509. {
  26510. mRangeDrag = enabled;
  26511. }
  26512. void QCPPolarAxisRadial::setRangeZoom(bool enabled)
  26513. {
  26514. mRangeZoom = enabled;
  26515. }
  26516. void QCPPolarAxisRadial::setRangeZoomFactor(double factor)
  26517. {
  26518. mRangeZoomFactor = factor;
  26519. }
  26520. /*!
  26521. Sets whether the axis uses a linear scale or a logarithmic scale.
  26522. Note that this method controls the coordinate transformation. For logarithmic scales, you will
  26523. likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting
  26524. the axis ticker to an instance of \ref QCPAxisTickerLog :
  26525. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-creation
  26526. See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick
  26527. creation.
  26528. \ref setNumberPrecision
  26529. */
  26530. void QCPPolarAxisRadial::setScaleType(QCPPolarAxisRadial::ScaleType type)
  26531. {
  26532. if (mScaleType != type)
  26533. {
  26534. mScaleType = type;
  26535. if (mScaleType == stLogarithmic)
  26536. setRange(mRange.sanitizedForLogScale());
  26537. //mCachedMarginValid = false;
  26538. emit scaleTypeChanged(mScaleType);
  26539. }
  26540. }
  26541. /*!
  26542. Sets the range of the axis.
  26543. This slot may be connected with the \ref rangeChanged signal of another axis so this axis
  26544. is always synchronized with the other axis range, when it changes.
  26545. To invert the direction of an axis, use \ref setRangeReversed.
  26546. */
  26547. void QCPPolarAxisRadial::setRange(const QCPRange &range)
  26548. {
  26549. if (range.lower == mRange.lower && range.upper == mRange.upper)
  26550. return;
  26551. if (!QCPRange::validRange(range)) return;
  26552. QCPRange oldRange = mRange;
  26553. if (mScaleType == stLogarithmic)
  26554. {
  26555. mRange = range.sanitizedForLogScale();
  26556. } else
  26557. {
  26558. mRange = range.sanitizedForLinScale();
  26559. }
  26560. emit rangeChanged(mRange);
  26561. emit rangeChanged(mRange, oldRange);
  26562. }
  26563. /*!
  26564. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  26565. (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
  26566. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  26567. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  26568. directly.
  26569. \see SelectablePart, setSelectedParts
  26570. */
  26571. void QCPPolarAxisRadial::setSelectableParts(const SelectableParts &selectable)
  26572. {
  26573. if (mSelectableParts != selectable)
  26574. {
  26575. mSelectableParts = selectable;
  26576. emit selectableChanged(mSelectableParts);
  26577. }
  26578. }
  26579. /*!
  26580. Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
  26581. is selected, it uses a different pen/font.
  26582. The entire selection mechanism for axes is handled automatically when \ref
  26583. QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
  26584. wish to change the selection state manually.
  26585. This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
  26586. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  26587. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
  26588. setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
  26589. */
  26590. void QCPPolarAxisRadial::setSelectedParts(const SelectableParts &selected)
  26591. {
  26592. if (mSelectedParts != selected)
  26593. {
  26594. mSelectedParts = selected;
  26595. emit selectionChanged(mSelectedParts);
  26596. }
  26597. }
  26598. /*!
  26599. \overload
  26600. Sets the lower and upper bound of the axis range.
  26601. To invert the direction of an axis, use \ref setRangeReversed.
  26602. There is also a slot to set a range, see \ref setRange(const QCPRange &range).
  26603. */
  26604. void QCPPolarAxisRadial::setRange(double lower, double upper)
  26605. {
  26606. if (lower == mRange.lower && upper == mRange.upper)
  26607. return;
  26608. if (!QCPRange::validRange(lower, upper)) return;
  26609. QCPRange oldRange = mRange;
  26610. mRange.lower = lower;
  26611. mRange.upper = upper;
  26612. if (mScaleType == stLogarithmic)
  26613. {
  26614. mRange = mRange.sanitizedForLogScale();
  26615. } else
  26616. {
  26617. mRange = mRange.sanitizedForLinScale();
  26618. }
  26619. emit rangeChanged(mRange);
  26620. emit rangeChanged(mRange, oldRange);
  26621. }
  26622. /*!
  26623. \overload
  26624. Sets the range of the axis.
  26625. The \a position coordinate indicates together with the \a alignment parameter, where the new
  26626. range will be positioned. \a size defines the size of the new axis range. \a alignment may be
  26627. Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
  26628. or center of the range to be aligned with \a position. Any other values of \a alignment will
  26629. default to Qt::AlignCenter.
  26630. */
  26631. void QCPPolarAxisRadial::setRange(double position, double size, Qt::AlignmentFlag alignment)
  26632. {
  26633. if (alignment == Qt::AlignLeft)
  26634. setRange(position, position+size);
  26635. else if (alignment == Qt::AlignRight)
  26636. setRange(position-size, position);
  26637. else // alignment == Qt::AlignCenter
  26638. setRange(position-size/2.0, position+size/2.0);
  26639. }
  26640. /*!
  26641. Sets the lower bound of the axis range. The upper bound is not changed.
  26642. \see setRange
  26643. */
  26644. void QCPPolarAxisRadial::setRangeLower(double lower)
  26645. {
  26646. if (mRange.lower == lower)
  26647. return;
  26648. QCPRange oldRange = mRange;
  26649. mRange.lower = lower;
  26650. if (mScaleType == stLogarithmic)
  26651. {
  26652. mRange = mRange.sanitizedForLogScale();
  26653. } else
  26654. {
  26655. mRange = mRange.sanitizedForLinScale();
  26656. }
  26657. emit rangeChanged(mRange);
  26658. emit rangeChanged(mRange, oldRange);
  26659. }
  26660. /*!
  26661. Sets the upper bound of the axis range. The lower bound is not changed.
  26662. \see setRange
  26663. */
  26664. void QCPPolarAxisRadial::setRangeUpper(double upper)
  26665. {
  26666. if (mRange.upper == upper)
  26667. return;
  26668. QCPRange oldRange = mRange;
  26669. mRange.upper = upper;
  26670. if (mScaleType == stLogarithmic)
  26671. {
  26672. mRange = mRange.sanitizedForLogScale();
  26673. } else
  26674. {
  26675. mRange = mRange.sanitizedForLinScale();
  26676. }
  26677. emit rangeChanged(mRange);
  26678. emit rangeChanged(mRange, oldRange);
  26679. }
  26680. /*!
  26681. Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
  26682. axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
  26683. direction of increasing values is inverted.
  26684. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
  26685. of the \ref setRange interface will still reference the mathematically smaller number than the \a
  26686. upper part.
  26687. */
  26688. void QCPPolarAxisRadial::setRangeReversed(bool reversed)
  26689. {
  26690. mRangeReversed = reversed;
  26691. }
  26692. void QCPPolarAxisRadial::setAngle(double degrees)
  26693. {
  26694. mAngle = degrees;
  26695. }
  26696. void QCPPolarAxisRadial::setAngleReference(AngleReference reference)
  26697. {
  26698. mAngleReference = reference;
  26699. }
  26700. /*!
  26701. The axis ticker is responsible for generating the tick positions and tick labels. See the
  26702. documentation of QCPAxisTicker for details on how to work with axis tickers.
  26703. You can change the tick positioning/labeling behaviour of this axis by setting a different
  26704. QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
  26705. ticker, access it via \ref ticker.
  26706. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  26707. ticker simply by passing the same shared pointer to multiple axes.
  26708. \see ticker
  26709. */
  26710. void QCPPolarAxisRadial::setTicker(QSharedPointer<QCPAxisTicker> ticker)
  26711. {
  26712. if (ticker)
  26713. mTicker = ticker;
  26714. else
  26715. qDebug() << Q_FUNC_INFO << "can not set 0 as axis ticker";
  26716. // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
  26717. }
  26718. /*!
  26719. Sets whether tick marks are displayed.
  26720. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
  26721. that, see \ref setTickLabels.
  26722. \see setSubTicks
  26723. */
  26724. void QCPPolarAxisRadial::setTicks(bool show)
  26725. {
  26726. if (mTicks != show)
  26727. {
  26728. mTicks = show;
  26729. //mCachedMarginValid = false;
  26730. }
  26731. }
  26732. /*!
  26733. Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
  26734. */
  26735. void QCPPolarAxisRadial::setTickLabels(bool show)
  26736. {
  26737. if (mTickLabels != show)
  26738. {
  26739. mTickLabels = show;
  26740. //mCachedMarginValid = false;
  26741. if (!mTickLabels)
  26742. mTickVectorLabels.clear();
  26743. }
  26744. }
  26745. /*!
  26746. Sets the distance between the axis base line (including any outward ticks) and the tick labels.
  26747. \see setLabelPadding, setPadding
  26748. */
  26749. void QCPPolarAxisRadial::setTickLabelPadding(int padding)
  26750. {
  26751. mLabelPainter.setPadding(padding);
  26752. }
  26753. /*!
  26754. Sets the font of the tick labels.
  26755. \see setTickLabels, setTickLabelColor
  26756. */
  26757. void QCPPolarAxisRadial::setTickLabelFont(const QFont &font)
  26758. {
  26759. if (font != mTickLabelFont)
  26760. {
  26761. mTickLabelFont = font;
  26762. //mCachedMarginValid = false;
  26763. }
  26764. }
  26765. /*!
  26766. Sets the color of the tick labels.
  26767. \see setTickLabels, setTickLabelFont
  26768. */
  26769. void QCPPolarAxisRadial::setTickLabelColor(const QColor &color)
  26770. {
  26771. mTickLabelColor = color;
  26772. }
  26773. /*!
  26774. Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
  26775. the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
  26776. from -90 to 90 degrees.
  26777. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
  26778. other angles, the label is drawn with an offset such that it seems to point toward or away from
  26779. the tick mark.
  26780. */
  26781. void QCPPolarAxisRadial::setTickLabelRotation(double degrees)
  26782. {
  26783. mLabelPainter.setRotation(degrees);
  26784. }
  26785. void QCPPolarAxisRadial::setTickLabelMode(LabelMode mode)
  26786. {
  26787. switch (mode)
  26788. {
  26789. case lmUpright: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedUpright); break;
  26790. case lmRotated: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedRotated); break;
  26791. }
  26792. }
  26793. /*!
  26794. Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
  26795. of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
  26796. that, see the "Argument Formats" section in the detailed description of the QString class.
  26797. \a formatCode is a string of one, two or three characters. The first character is identical to
  26798. the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
  26799. format, 'g'/'G' scientific or fixed, whichever is shorter.
  26800. The second and third characters are optional and specific to QCustomPlot:\n
  26801. If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
  26802. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for
  26803. "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
  26804. [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
  26805. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
  26806. be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
  26807. cross and 183 (0xB7) for the dot.
  26808. Examples for \a formatCode:
  26809. \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
  26810. normal scientific format is used
  26811. \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
  26812. beautifully typeset decimal powers and a dot as multiplication sign
  26813. \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
  26814. multiplication sign
  26815. \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
  26816. powers. Format code will be reduced to 'f'.
  26817. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
  26818. code will not be changed.
  26819. */
  26820. void QCPPolarAxisRadial::setNumberFormat(const QString &formatCode)
  26821. {
  26822. if (formatCode.isEmpty())
  26823. {
  26824. qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
  26825. return;
  26826. }
  26827. //mCachedMarginValid = false;
  26828. // interpret first char as number format char:
  26829. QString allowedFormatChars(QLatin1String("eEfgG"));
  26830. if (allowedFormatChars.contains(formatCode.at(0)))
  26831. {
  26832. mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
  26833. } else
  26834. {
  26835. qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
  26836. return;
  26837. }
  26838. if (formatCode.length() < 2)
  26839. {
  26840. mNumberBeautifulPowers = false;
  26841. mNumberMultiplyCross = false;
  26842. } else
  26843. {
  26844. // interpret second char as indicator for beautiful decimal powers:
  26845. if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
  26846. mNumberBeautifulPowers = true;
  26847. else
  26848. qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
  26849. if (formatCode.length() < 3)
  26850. {
  26851. mNumberMultiplyCross = false;
  26852. } else
  26853. {
  26854. // interpret third char as indicator for dot or cross multiplication symbol:
  26855. if (formatCode.at(2) == QLatin1Char('c'))
  26856. mNumberMultiplyCross = true;
  26857. else if (formatCode.at(2) == QLatin1Char('d'))
  26858. mNumberMultiplyCross = false;
  26859. else
  26860. qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
  26861. }
  26862. }
  26863. mLabelPainter.setSubstituteExponent(mNumberBeautifulPowers);
  26864. mLabelPainter.setMultiplicationSymbol(mNumberMultiplyCross ? QCPLabelPainterPrivate::SymbolCross : QCPLabelPainterPrivate::SymbolDot);
  26865. }
  26866. /*!
  26867. Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
  26868. for details. The effect of precisions are most notably for number Formats starting with 'e', see
  26869. \ref setNumberFormat
  26870. */
  26871. void QCPPolarAxisRadial::setNumberPrecision(int precision)
  26872. {
  26873. if (mNumberPrecision != precision)
  26874. {
  26875. mNumberPrecision = precision;
  26876. //mCachedMarginValid = false;
  26877. }
  26878. }
  26879. /*!
  26880. Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
  26881. plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
  26882. zero, the tick labels and axis label will increase their distance to the axis accordingly, so
  26883. they won't collide with the ticks.
  26884. \see setSubTickLength, setTickLengthIn, setTickLengthOut
  26885. */
  26886. void QCPPolarAxisRadial::setTickLength(int inside, int outside)
  26887. {
  26888. setTickLengthIn(inside);
  26889. setTickLengthOut(outside);
  26890. }
  26891. /*!
  26892. Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
  26893. inside the plot.
  26894. \see setTickLengthOut, setTickLength, setSubTickLength
  26895. */
  26896. void QCPPolarAxisRadial::setTickLengthIn(int inside)
  26897. {
  26898. if (mTickLengthIn != inside)
  26899. {
  26900. mTickLengthIn = inside;
  26901. }
  26902. }
  26903. /*!
  26904. Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
  26905. outside the plot. If \a outside is greater than zero, the tick labels and axis label will
  26906. increase their distance to the axis accordingly, so they won't collide with the ticks.
  26907. \see setTickLengthIn, setTickLength, setSubTickLength
  26908. */
  26909. void QCPPolarAxisRadial::setTickLengthOut(int outside)
  26910. {
  26911. if (mTickLengthOut != outside)
  26912. {
  26913. mTickLengthOut = outside;
  26914. //mCachedMarginValid = false; // only outside tick length can change margin
  26915. }
  26916. }
  26917. /*!
  26918. Sets whether sub tick marks are displayed.
  26919. Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
  26920. \see setTicks
  26921. */
  26922. void QCPPolarAxisRadial::setSubTicks(bool show)
  26923. {
  26924. if (mSubTicks != show)
  26925. {
  26926. mSubTicks = show;
  26927. //mCachedMarginValid = false;
  26928. }
  26929. }
  26930. /*!
  26931. Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
  26932. the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
  26933. than zero, the tick labels and axis label will increase their distance to the axis accordingly,
  26934. so they won't collide with the ticks.
  26935. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
  26936. */
  26937. void QCPPolarAxisRadial::setSubTickLength(int inside, int outside)
  26938. {
  26939. setSubTickLengthIn(inside);
  26940. setSubTickLengthOut(outside);
  26941. }
  26942. /*!
  26943. Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
  26944. the plot.
  26945. \see setSubTickLengthOut, setSubTickLength, setTickLength
  26946. */
  26947. void QCPPolarAxisRadial::setSubTickLengthIn(int inside)
  26948. {
  26949. if (mSubTickLengthIn != inside)
  26950. {
  26951. mSubTickLengthIn = inside;
  26952. }
  26953. }
  26954. /*!
  26955. Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
  26956. outside the plot. If \a outside is greater than zero, the tick labels will increase their
  26957. distance to the axis accordingly, so they won't collide with the ticks.
  26958. \see setSubTickLengthIn, setSubTickLength, setTickLength
  26959. */
  26960. void QCPPolarAxisRadial::setSubTickLengthOut(int outside)
  26961. {
  26962. if (mSubTickLengthOut != outside)
  26963. {
  26964. mSubTickLengthOut = outside;
  26965. //mCachedMarginValid = false; // only outside tick length can change margin
  26966. }
  26967. }
  26968. /*!
  26969. Sets the pen, the axis base line is drawn with.
  26970. \see setTickPen, setSubTickPen
  26971. */
  26972. void QCPPolarAxisRadial::setBasePen(const QPen &pen)
  26973. {
  26974. mBasePen = pen;
  26975. }
  26976. /*!
  26977. Sets the pen, tick marks will be drawn with.
  26978. \see setTickLength, setBasePen
  26979. */
  26980. void QCPPolarAxisRadial::setTickPen(const QPen &pen)
  26981. {
  26982. mTickPen = pen;
  26983. }
  26984. /*!
  26985. Sets the pen, subtick marks will be drawn with.
  26986. \see setSubTickCount, setSubTickLength, setBasePen
  26987. */
  26988. void QCPPolarAxisRadial::setSubTickPen(const QPen &pen)
  26989. {
  26990. mSubTickPen = pen;
  26991. }
  26992. /*!
  26993. Sets the font of the axis label.
  26994. \see setLabelColor
  26995. */
  26996. void QCPPolarAxisRadial::setLabelFont(const QFont &font)
  26997. {
  26998. if (mLabelFont != font)
  26999. {
  27000. mLabelFont = font;
  27001. //mCachedMarginValid = false;
  27002. }
  27003. }
  27004. /*!
  27005. Sets the color of the axis label.
  27006. \see setLabelFont
  27007. */
  27008. void QCPPolarAxisRadial::setLabelColor(const QColor &color)
  27009. {
  27010. mLabelColor = color;
  27011. }
  27012. /*!
  27013. Sets the text of the axis label that will be shown below/above or next to the axis, depending on
  27014. its orientation. To disable axis labels, pass an empty string as \a str.
  27015. */
  27016. void QCPPolarAxisRadial::setLabel(const QString &str)
  27017. {
  27018. if (mLabel != str)
  27019. {
  27020. mLabel = str;
  27021. //mCachedMarginValid = false;
  27022. }
  27023. }
  27024. /*!
  27025. Sets the distance between the tick labels and the axis label.
  27026. \see setTickLabelPadding, setPadding
  27027. */
  27028. void QCPPolarAxisRadial::setLabelPadding(int padding)
  27029. {
  27030. if (mLabelPadding != padding)
  27031. {
  27032. mLabelPadding = padding;
  27033. //mCachedMarginValid = false;
  27034. }
  27035. }
  27036. /*!
  27037. Sets the font that is used for tick labels when they are selected.
  27038. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27039. */
  27040. void QCPPolarAxisRadial::setSelectedTickLabelFont(const QFont &font)
  27041. {
  27042. if (font != mSelectedTickLabelFont)
  27043. {
  27044. mSelectedTickLabelFont = font;
  27045. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  27046. }
  27047. }
  27048. /*!
  27049. Sets the font that is used for the axis label when it is selected.
  27050. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27051. */
  27052. void QCPPolarAxisRadial::setSelectedLabelFont(const QFont &font)
  27053. {
  27054. mSelectedLabelFont = font;
  27055. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  27056. }
  27057. /*!
  27058. Sets the color that is used for tick labels when they are selected.
  27059. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27060. */
  27061. void QCPPolarAxisRadial::setSelectedTickLabelColor(const QColor &color)
  27062. {
  27063. if (color != mSelectedTickLabelColor)
  27064. {
  27065. mSelectedTickLabelColor = color;
  27066. }
  27067. }
  27068. /*!
  27069. Sets the color that is used for the axis label when it is selected.
  27070. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27071. */
  27072. void QCPPolarAxisRadial::setSelectedLabelColor(const QColor &color)
  27073. {
  27074. mSelectedLabelColor = color;
  27075. }
  27076. /*!
  27077. Sets the pen that is used to draw the axis base line when selected.
  27078. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27079. */
  27080. void QCPPolarAxisRadial::setSelectedBasePen(const QPen &pen)
  27081. {
  27082. mSelectedBasePen = pen;
  27083. }
  27084. /*!
  27085. Sets the pen that is used to draw the (major) ticks when selected.
  27086. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27087. */
  27088. void QCPPolarAxisRadial::setSelectedTickPen(const QPen &pen)
  27089. {
  27090. mSelectedTickPen = pen;
  27091. }
  27092. /*!
  27093. Sets the pen that is used to draw the subticks when selected.
  27094. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27095. */
  27096. void QCPPolarAxisRadial::setSelectedSubTickPen(const QPen &pen)
  27097. {
  27098. mSelectedSubTickPen = pen;
  27099. }
  27100. /*!
  27101. If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
  27102. bounds of the range. The range is simply moved by \a diff.
  27103. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
  27104. corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
  27105. */
  27106. void QCPPolarAxisRadial::moveRange(double diff)
  27107. {
  27108. QCPRange oldRange = mRange;
  27109. if (mScaleType == stLinear)
  27110. {
  27111. mRange.lower += diff;
  27112. mRange.upper += diff;
  27113. } else // mScaleType == stLogarithmic
  27114. {
  27115. mRange.lower *= diff;
  27116. mRange.upper *= diff;
  27117. }
  27118. emit rangeChanged(mRange);
  27119. emit rangeChanged(mRange, oldRange);
  27120. }
  27121. /*!
  27122. Scales the range of this axis by \a factor around the center of the current axis range. For
  27123. example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
  27124. range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
  27125. the center will have moved symmetrically closer).
  27126. If you wish to scale around a different coordinate than the current axis range center, use the
  27127. overload \ref scaleRange(double factor, double center).
  27128. */
  27129. void QCPPolarAxisRadial::scaleRange(double factor)
  27130. {
  27131. scaleRange(factor, range().center());
  27132. }
  27133. /*! \overload
  27134. Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
  27135. factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
  27136. coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
  27137. around 1.0 will have moved symmetrically closer to 1.0).
  27138. \see scaleRange(double factor)
  27139. */
  27140. void QCPPolarAxisRadial::scaleRange(double factor, double center)
  27141. {
  27142. QCPRange oldRange = mRange;
  27143. if (mScaleType == stLinear)
  27144. {
  27145. QCPRange newRange;
  27146. newRange.lower = (mRange.lower-center)*factor + center;
  27147. newRange.upper = (mRange.upper-center)*factor + center;
  27148. if (QCPRange::validRange(newRange))
  27149. mRange = newRange.sanitizedForLinScale();
  27150. } else // mScaleType == stLogarithmic
  27151. {
  27152. if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range
  27153. {
  27154. QCPRange newRange;
  27155. newRange.lower = qPow(mRange.lower/center, factor)*center;
  27156. newRange.upper = qPow(mRange.upper/center, factor)*center;
  27157. if (QCPRange::validRange(newRange))
  27158. mRange = newRange.sanitizedForLogScale();
  27159. } else
  27160. qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center;
  27161. }
  27162. emit rangeChanged(mRange);
  27163. emit rangeChanged(mRange, oldRange);
  27164. }
  27165. /*!
  27166. Changes the axis range such that all plottables associated with this axis are fully visible in
  27167. that dimension.
  27168. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
  27169. */
  27170. void QCPPolarAxisRadial::rescale(bool onlyVisiblePlottables)
  27171. {
  27172. Q_UNUSED(onlyVisiblePlottables)
  27173. /* TODO
  27174. QList<QCPAbstractPlottable*> p = plottables();
  27175. QCPRange newRange;
  27176. bool haveRange = false;
  27177. for (int i=0; i<p.size(); ++i)
  27178. {
  27179. if (!p.at(i)->realVisibility() && onlyVisiblePlottables)
  27180. continue;
  27181. QCPRange plottableRange;
  27182. bool currentFoundRange;
  27183. QCP::SignDomain signDomain = QCP::sdBoth;
  27184. if (mScaleType == stLogarithmic)
  27185. signDomain = (mRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  27186. if (p.at(i)->keyAxis() == this)
  27187. plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain);
  27188. else
  27189. plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain);
  27190. if (currentFoundRange)
  27191. {
  27192. if (!haveRange)
  27193. newRange = plottableRange;
  27194. else
  27195. newRange.expand(plottableRange);
  27196. haveRange = true;
  27197. }
  27198. }
  27199. if (haveRange)
  27200. {
  27201. 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
  27202. {
  27203. 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
  27204. if (mScaleType == stLinear)
  27205. {
  27206. newRange.lower = center-mRange.size()/2.0;
  27207. newRange.upper = center+mRange.size()/2.0;
  27208. } else // mScaleType == stLogarithmic
  27209. {
  27210. newRange.lower = center/qSqrt(mRange.upper/mRange.lower);
  27211. newRange.upper = center*qSqrt(mRange.upper/mRange.lower);
  27212. }
  27213. }
  27214. setRange(newRange);
  27215. }
  27216. */
  27217. }
  27218. /*!
  27219. Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
  27220. */
  27221. void QCPPolarAxisRadial::pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const
  27222. {
  27223. QCPVector2D posVector(pixelPos-mCenter);
  27224. radiusCoord = radiusToCoord(posVector.length());
  27225. angleCoord = mAngularAxis->angleRadToCoord(posVector.angle());
  27226. }
  27227. /*!
  27228. Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
  27229. */
  27230. QPointF QCPPolarAxisRadial::coordToPixel(double angleCoord, double radiusCoord) const
  27231. {
  27232. const double radiusPixel = coordToRadius(radiusCoord);
  27233. const double angleRad = mAngularAxis->coordToAngleRad(angleCoord);
  27234. return QPointF(mCenter.x()+qCos(angleRad)*radiusPixel, mCenter.y()+qSin(angleRad)*radiusPixel);
  27235. }
  27236. double QCPPolarAxisRadial::coordToRadius(double coord) const
  27237. {
  27238. if (mScaleType == stLinear)
  27239. {
  27240. if (!mRangeReversed)
  27241. return (coord-mRange.lower)/mRange.size()*mRadius;
  27242. else
  27243. return (mRange.upper-coord)/mRange.size()*mRadius;
  27244. } else // mScaleType == stLogarithmic
  27245. {
  27246. if (coord >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just return outside visible range
  27247. return !mRangeReversed ? mRadius+200 : mRadius-200;
  27248. else if (coord <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just return outside visible range
  27249. return !mRangeReversed ? mRadius-200 :mRadius+200;
  27250. else
  27251. {
  27252. if (!mRangeReversed)
  27253. return qLn(coord/mRange.lower)/qLn(mRange.upper/mRange.lower)*mRadius;
  27254. else
  27255. return qLn(mRange.upper/coord)/qLn(mRange.upper/mRange.lower)*mRadius;
  27256. }
  27257. }
  27258. }
  27259. double QCPPolarAxisRadial::radiusToCoord(double radius) const
  27260. {
  27261. if (mScaleType == stLinear)
  27262. {
  27263. if (!mRangeReversed)
  27264. return (radius)/mRadius*mRange.size()+mRange.lower;
  27265. else
  27266. return -(radius)/mRadius*mRange.size()+mRange.upper;
  27267. } else // mScaleType == stLogarithmic
  27268. {
  27269. if (!mRangeReversed)
  27270. return qPow(mRange.upper/mRange.lower, (radius)/mRadius)*mRange.lower;
  27271. else
  27272. return qPow(mRange.upper/mRange.lower, (-radius)/mRadius)*mRange.upper;
  27273. }
  27274. }
  27275. /*!
  27276. Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
  27277. is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
  27278. function does not change the current selection state of the axis.
  27279. If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
  27280. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
  27281. */
  27282. QCPPolarAxisRadial::SelectablePart QCPPolarAxisRadial::getPartAt(const QPointF &pos) const
  27283. {
  27284. Q_UNUSED(pos) // TODO remove later
  27285. if (!mVisible)
  27286. return spNone;
  27287. /*
  27288. TODO:
  27289. if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
  27290. return spAxis;
  27291. else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
  27292. return spTickLabels;
  27293. else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
  27294. return spAxisLabel;
  27295. else */
  27296. return spNone;
  27297. }
  27298. /* inherits documentation from base class */
  27299. double QCPPolarAxisRadial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  27300. {
  27301. if (!mParentPlot) return -1;
  27302. SelectablePart part = getPartAt(pos);
  27303. if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
  27304. return -1;
  27305. if (details)
  27306. details->setValue(part);
  27307. return mParentPlot->selectionTolerance()*0.99;
  27308. }
  27309. /* inherits documentation from base class */
  27310. void QCPPolarAxisRadial::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  27311. {
  27312. Q_UNUSED(event)
  27313. SelectablePart part = details.value<SelectablePart>();
  27314. if (mSelectableParts.testFlag(part))
  27315. {
  27316. SelectableParts selBefore = mSelectedParts;
  27317. setSelectedParts(additive ? mSelectedParts^part : part);
  27318. if (selectionStateChanged)
  27319. *selectionStateChanged = mSelectedParts != selBefore;
  27320. }
  27321. }
  27322. /* inherits documentation from base class */
  27323. void QCPPolarAxisRadial::deselectEvent(bool *selectionStateChanged)
  27324. {
  27325. SelectableParts selBefore = mSelectedParts;
  27326. setSelectedParts(mSelectedParts & ~mSelectableParts);
  27327. if (selectionStateChanged)
  27328. *selectionStateChanged = mSelectedParts != selBefore;
  27329. }
  27330. /*! \internal
  27331. This mouse event reimplementation provides the functionality to let the user drag individual axes
  27332. exclusively, by startig the drag on top of the axis.
  27333. For the axis to accept this event and perform the single axis drag, the parent \ref QCPAxisRect
  27334. must be configured accordingly, i.e. it must allow range dragging in the orientation of this axis
  27335. (\ref QCPAxisRect::setRangeDrag) and this axis must be a draggable axis (\ref
  27336. QCPAxisRect::setRangeDragAxes)
  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. */
  27341. void QCPPolarAxisRadial::mousePressEvent(QMouseEvent *event, const QVariant &details)
  27342. {
  27343. Q_UNUSED(details)
  27344. if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  27345. {
  27346. event->ignore();
  27347. return;
  27348. }
  27349. if (event->buttons() & Qt::LeftButton)
  27350. {
  27351. mDragging = true;
  27352. // initialize antialiasing backup in case we start dragging:
  27353. if (mParentPlot->noAntialiasingOnDrag())
  27354. {
  27355. mAADragBackup = mParentPlot->antialiasedElements();
  27356. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  27357. }
  27358. // Mouse range dragging interaction:
  27359. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  27360. mDragStartRange = mRange;
  27361. }
  27362. }
  27363. /*! \internal
  27364. This mouse event reimplementation provides the functionality to let the user drag individual axes
  27365. exclusively, by startig the drag on top of the axis.
  27366. \seebaseclassmethod
  27367. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  27368. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  27369. \see QCPAxis::mousePressEvent
  27370. */
  27371. void QCPPolarAxisRadial::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  27372. {
  27373. Q_UNUSED(event) // TODO remove later
  27374. Q_UNUSED(startPos) // TODO remove later
  27375. if (mDragging)
  27376. {
  27377. /* TODO
  27378. const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y();
  27379. const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y();
  27380. if (mScaleType == QCPPolarAxisRadial::stLinear)
  27381. {
  27382. const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel);
  27383. setRange(mDragStartRange.lower+diff, mDragStartRange.upper+diff);
  27384. } else if (mScaleType == QCPPolarAxisRadial::stLogarithmic)
  27385. {
  27386. const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel);
  27387. setRange(mDragStartRange.lower*diff, mDragStartRange.upper*diff);
  27388. }
  27389. */
  27390. if (mParentPlot->noAntialiasingOnDrag())
  27391. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  27392. mParentPlot->replot(QCustomPlot::rpQueuedReplot);
  27393. }
  27394. }
  27395. /*! \internal
  27396. This mouse event reimplementation provides the functionality to let the user drag individual axes
  27397. exclusively, by startig the drag on top of the axis.
  27398. \seebaseclassmethod
  27399. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  27400. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  27401. \see QCPAxis::mousePressEvent
  27402. */
  27403. void QCPPolarAxisRadial::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  27404. {
  27405. Q_UNUSED(event)
  27406. Q_UNUSED(startPos)
  27407. mDragging = false;
  27408. if (mParentPlot->noAntialiasingOnDrag())
  27409. {
  27410. mParentPlot->setAntialiasedElements(mAADragBackup);
  27411. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  27412. }
  27413. }
  27414. /*! \internal
  27415. This mouse event reimplementation provides the functionality to let the user zoom individual axes
  27416. exclusively, by performing the wheel event on top of the axis.
  27417. For the axis to accept this event and perform the single axis zoom, the parent \ref QCPAxisRect
  27418. must be configured accordingly, i.e. it must allow range zooming in the orientation of this axis
  27419. (\ref QCPAxisRect::setRangeZoom) and this axis must be a zoomable axis (\ref
  27420. QCPAxisRect::setRangeZoomAxes)
  27421. \seebaseclassmethod
  27422. \note The zooming of possibly multiple axes at once by performing the wheel event anywhere in the
  27423. axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::wheelEvent.
  27424. */
  27425. void QCPPolarAxisRadial::wheelEvent(QWheelEvent *event)
  27426. {
  27427. // Mouse range zooming interaction:
  27428. if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom))
  27429. {
  27430. event->ignore();
  27431. return;
  27432. }
  27433. // TODO:
  27434. //const double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually
  27435. //const double factor = qPow(mRangeZoomFactor, wheelSteps);
  27436. //scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y()));
  27437. mParentPlot->replot();
  27438. }
  27439. void QCPPolarAxisRadial::updateGeometry(const QPointF &center, double radius)
  27440. {
  27441. mCenter = center;
  27442. mRadius = radius;
  27443. if (mRadius < 1) mRadius = 1;
  27444. }
  27445. /*! \internal
  27446. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  27447. before drawing axis lines.
  27448. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  27449. This function takes into account the local setting of the antialiasing flag as well as the
  27450. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  27451. QCustomPlot::setNotAntialiasedElements.
  27452. \seebaseclassmethod
  27453. \see setAntialiased
  27454. */
  27455. void QCPPolarAxisRadial::applyDefaultAntialiasingHint(QCPPainter *painter) const
  27456. {
  27457. applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
  27458. }
  27459. /*! \internal
  27460. Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance.
  27461. \seebaseclassmethod
  27462. */
  27463. void QCPPolarAxisRadial::draw(QCPPainter *painter)
  27464. {
  27465. const double axisAngleRad = (mAngle+(mAngleReference==arAngularAxis ? mAngularAxis->angle() : 0))/180.0*M_PI;
  27466. const QPointF axisVector(qCos(axisAngleRad), qSin(axisAngleRad)); // semantically should be QCPVector2D, but we save time in loops when we keep it as QPointF
  27467. const QPointF tickNormal = QCPVector2D(axisVector).perpendicular().toPointF(); // semantically should be QCPVector2D, but we save time in loops when we keep it as QPointF
  27468. // draw baseline:
  27469. painter->setPen(getBasePen());
  27470. painter->drawLine(QLineF(mCenter, mCenter+axisVector*(mRadius-0.5)));
  27471. // draw subticks:
  27472. if (!mSubTickVector.isEmpty())
  27473. {
  27474. painter->setPen(getSubTickPen());
  27475. for (int i=0; i<mSubTickVector.size(); ++i)
  27476. {
  27477. const QPointF tickPosition = mCenter+axisVector*coordToRadius(mSubTickVector.at(i));
  27478. painter->drawLine(QLineF(tickPosition-tickNormal*mSubTickLengthIn, tickPosition+tickNormal*mSubTickLengthOut));
  27479. }
  27480. }
  27481. // draw ticks and labels:
  27482. if (!mTickVector.isEmpty())
  27483. {
  27484. mLabelPainter.setAnchorReference(mCenter-axisVector); // subtract (normalized) axisVector, just to prevent degenerate tangents for tick label at exact lower axis range
  27485. mLabelPainter.setFont(getTickLabelFont());
  27486. mLabelPainter.setColor(getTickLabelColor());
  27487. const QPen ticksPen = getTickPen();
  27488. painter->setPen(ticksPen);
  27489. for (int i=0; i<mTickVector.size(); ++i)
  27490. {
  27491. const double r = coordToRadius(mTickVector.at(i));
  27492. const QPointF tickPosition = mCenter+axisVector*r;
  27493. painter->drawLine(QLineF(tickPosition-tickNormal*mTickLengthIn, tickPosition+tickNormal*mTickLengthOut));
  27494. // possibly draw tick labels:
  27495. if (!mTickVectorLabels.isEmpty())
  27496. {
  27497. if ((!mRangeReversed && (i < mTickVectorLabels.count()-1 || mRadius-r > 10)) ||
  27498. (mRangeReversed && (i > 0 || mRadius-r > 10))) // skip last label if it's closer than 10 pixels to angular axis
  27499. mLabelPainter.drawTickLabel(painter, tickPosition+tickNormal*mSubTickLengthOut, mTickVectorLabels.at(i));
  27500. }
  27501. }
  27502. }
  27503. }
  27504. /*! \internal
  27505. Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
  27506. QCPAxisTicker::generate on the currently installed ticker.
  27507. If a change in the label text/count is detected, the cached axis margin is invalidated to make
  27508. sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
  27509. */
  27510. void QCPPolarAxisRadial::setupTickVectors()
  27511. {
  27512. if (!mParentPlot) return;
  27513. if ((!mTicks && !mTickLabels) || mRange.size() <= 0) return;
  27514. mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : 0, mTickLabels ? &mTickVectorLabels : 0);
  27515. }
  27516. /*! \internal
  27517. Returns the pen that is used to draw the axis base line. Depending on the selection state, this
  27518. is either mSelectedBasePen or mBasePen.
  27519. */
  27520. QPen QCPPolarAxisRadial::getBasePen() const
  27521. {
  27522. return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
  27523. }
  27524. /*! \internal
  27525. Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
  27526. is either mSelectedTickPen or mTickPen.
  27527. */
  27528. QPen QCPPolarAxisRadial::getTickPen() const
  27529. {
  27530. return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
  27531. }
  27532. /*! \internal
  27533. Returns the pen that is used to draw the subticks. Depending on the selection state, this
  27534. is either mSelectedSubTickPen or mSubTickPen.
  27535. */
  27536. QPen QCPPolarAxisRadial::getSubTickPen() const
  27537. {
  27538. return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
  27539. }
  27540. /*! \internal
  27541. Returns the font that is used to draw the tick labels. Depending on the selection state, this
  27542. is either mSelectedTickLabelFont or mTickLabelFont.
  27543. */
  27544. QFont QCPPolarAxisRadial::getTickLabelFont() const
  27545. {
  27546. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
  27547. }
  27548. /*! \internal
  27549. Returns the font that is used to draw the axis label. Depending on the selection state, this
  27550. is either mSelectedLabelFont or mLabelFont.
  27551. */
  27552. QFont QCPPolarAxisRadial::getLabelFont() const
  27553. {
  27554. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
  27555. }
  27556. /*! \internal
  27557. Returns the color that is used to draw the tick labels. Depending on the selection state, this
  27558. is either mSelectedTickLabelColor or mTickLabelColor.
  27559. */
  27560. QColor QCPPolarAxisRadial::getTickLabelColor() const
  27561. {
  27562. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
  27563. }
  27564. /*! \internal
  27565. Returns the color that is used to draw the axis label. Depending on the selection state, this
  27566. is either mSelectedLabelColor or mLabelColor.
  27567. */
  27568. QColor QCPPolarAxisRadial::getLabelColor() const
  27569. {
  27570. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
  27571. }
  27572. /* inherits documentation from base class */
  27573. QCP::Interaction QCPPolarAxisRadial::selectionCategory() const
  27574. {
  27575. return QCP::iSelectAxes;
  27576. }
  27577. /* end of 'src/polar/radialaxis.cpp' */
  27578. /* including file 'src/polar/layoutelement-angularaxis.cpp' */
  27579. /* modified 2022-11-06T12:45:57, size 57266 */
  27580. ////////////////////////////////////////////////////////////////////////////////////////////////////
  27581. //////////////////// QCPPolarAxisAngular
  27582. ////////////////////////////////////////////////////////////////////////////////////////////////////
  27583. /*! \class QCPPolarAxisAngular
  27584. \brief The main container for polar plots, representing the angular axis as a circle
  27585. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  27586. functionality to be incomplete, as well as changing public interfaces in the future.
  27587. */
  27588. /* start documentation of inline functions */
  27589. /*! \fn QCPLayoutInset *QCPPolarAxisAngular::insetLayout() const
  27590. Returns the inset layout of this axis rect. It can be used to place other layout elements (or
  27591. even layouts with multiple other elements) inside/on top of an axis rect.
  27592. \see QCPLayoutInset
  27593. */
  27594. /*! \fn int QCPPolarAxisAngular::left() const
  27595. Returns the pixel position of the left border of this axis rect. Margins are not taken into
  27596. account here, so the returned value is with respect to the inner \ref rect.
  27597. */
  27598. /*! \fn int QCPPolarAxisAngular::right() const
  27599. Returns the pixel position of the right border of this axis rect. Margins are not taken into
  27600. account here, so the returned value is with respect to the inner \ref rect.
  27601. */
  27602. /*! \fn int QCPPolarAxisAngular::top() const
  27603. Returns the pixel position of the top border of this axis rect. Margins are not taken into
  27604. account here, so the returned value is with respect to the inner \ref rect.
  27605. */
  27606. /*! \fn int QCPPolarAxisAngular::bottom() const
  27607. Returns the pixel position of the bottom border of this axis rect. Margins are not taken into
  27608. account here, so the returned value is with respect to the inner \ref rect.
  27609. */
  27610. /*! \fn int QCPPolarAxisAngular::width() const
  27611. Returns the pixel width of this axis rect. Margins are not taken into account here, so the
  27612. returned value is with respect to the inner \ref rect.
  27613. */
  27614. /*! \fn int QCPPolarAxisAngular::height() const
  27615. Returns the pixel height of this axis rect. Margins are not taken into account here, so the
  27616. returned value is with respect to the inner \ref rect.
  27617. */
  27618. /*! \fn QSize QCPPolarAxisAngular::size() const
  27619. Returns the pixel size of this axis rect. Margins are not taken into account here, so the
  27620. returned value is with respect to the inner \ref rect.
  27621. */
  27622. /*! \fn QPoint QCPPolarAxisAngular::topLeft() const
  27623. Returns the top left corner of this axis rect in pixels. Margins are not taken into account here,
  27624. so the returned value is with respect to the inner \ref rect.
  27625. */
  27626. /*! \fn QPoint QCPPolarAxisAngular::topRight() const
  27627. Returns the top right corner of this axis rect in pixels. Margins are not taken into account
  27628. here, so the returned value is with respect to the inner \ref rect.
  27629. */
  27630. /*! \fn QPoint QCPPolarAxisAngular::bottomLeft() const
  27631. Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account
  27632. here, so the returned value is with respect to the inner \ref rect.
  27633. */
  27634. /*! \fn QPoint QCPPolarAxisAngular::bottomRight() const
  27635. Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account
  27636. here, so the returned value is with respect to the inner \ref rect.
  27637. */
  27638. /*! \fn QPoint QCPPolarAxisAngular::center() const
  27639. Returns the center of this axis rect in pixels. Margins are not taken into account here, so the
  27640. returned value is with respect to the inner \ref rect.
  27641. */
  27642. /* end documentation of inline functions */
  27643. /*!
  27644. Creates a QCPPolarAxis instance and sets default values. An axis is added for each of the four
  27645. sides, the top and right axes are set invisible initially.
  27646. */
  27647. QCPPolarAxisAngular::QCPPolarAxisAngular(QCustomPlot *parentPlot) :
  27648. QCPLayoutElement(parentPlot),
  27649. mBackgroundBrush(Qt::NoBrush),
  27650. mBackgroundScaled(true),
  27651. mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
  27652. mInsetLayout(new QCPLayoutInset),
  27653. mRangeDrag(false),
  27654. mRangeZoom(false),
  27655. mRangeZoomFactor(0.85),
  27656. // axis base:
  27657. mAngle(-90),
  27658. mAngleRad(mAngle/180.0*M_PI),
  27659. mSelectableParts(spAxis | spTickLabels | spAxisLabel),
  27660. mSelectedParts(spNone),
  27661. mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  27662. mSelectedBasePen(QPen(Qt::blue, 2)),
  27663. // axis label:
  27664. mLabelPadding(0),
  27665. mLabel(),
  27666. mLabelFont(mParentPlot->font()),
  27667. mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
  27668. mLabelColor(Qt::black),
  27669. mSelectedLabelColor(Qt::blue),
  27670. // tick labels:
  27671. //mTickLabelPadding(0), in label painter
  27672. mTickLabels(true),
  27673. //mTickLabelRotation(0), in label painter
  27674. mTickLabelFont(mParentPlot->font()),
  27675. mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
  27676. mTickLabelColor(Qt::black),
  27677. mSelectedTickLabelColor(Qt::blue),
  27678. mNumberPrecision(6),
  27679. mNumberFormatChar('g'),
  27680. mNumberBeautifulPowers(true),
  27681. mNumberMultiplyCross(false),
  27682. // ticks and subticks:
  27683. mTicks(true),
  27684. mSubTicks(true),
  27685. mTickLengthIn(5),
  27686. mTickLengthOut(0),
  27687. mSubTickLengthIn(2),
  27688. mSubTickLengthOut(0),
  27689. mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  27690. mSelectedTickPen(QPen(Qt::blue, 2)),
  27691. mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  27692. mSelectedSubTickPen(QPen(Qt::blue, 2)),
  27693. // scale and range:
  27694. mRange(0, 360),
  27695. mRangeReversed(false),
  27696. // internal members:
  27697. mRadius(1), // non-zero initial value, will be overwritten in ::update() according to inner rect
  27698. mGrid(new QCPPolarGrid(this)),
  27699. mTicker(new QCPAxisTickerFixed),
  27700. mDragging(false),
  27701. mLabelPainter(parentPlot)
  27702. {
  27703. // TODO:
  27704. //mInsetLayout->initializeParentPlot(mParentPlot);
  27705. //mInsetLayout->setParentLayerable(this);
  27706. //mInsetLayout->setParent(this);
  27707. if (QCPAxisTickerFixed *fixedTicker = mTicker.dynamicCast<QCPAxisTickerFixed>().data())
  27708. {
  27709. fixedTicker->setTickStep(30);
  27710. }
  27711. setAntialiased(true);
  27712. 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
  27713. setTickLabelPadding(5);
  27714. setTickLabelRotation(0);
  27715. setTickLabelMode(lmUpright);
  27716. mLabelPainter.setAnchorReferenceType(QCPLabelPainterPrivate::artNormal);
  27717. mLabelPainter.setAbbreviateDecimalPowers(false);
  27718. mLabelPainter.setCacheSize(24); // so we can cache up to 15-degree intervals, polar angular axis uses a bit larger cache than normal axes
  27719. setMinimumSize(50, 50);
  27720. setMinimumMargins(QMargins(30, 30, 30, 30));
  27721. addRadialAxis();
  27722. mGrid->setRadialAxis(radialAxis());
  27723. }
  27724. QCPPolarAxisAngular::~QCPPolarAxisAngular()
  27725. {
  27726. delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order
  27727. mGrid = 0;
  27728. delete mInsetLayout;
  27729. mInsetLayout = 0;
  27730. QList<QCPPolarAxisRadial*> radialAxesList = radialAxes();
  27731. for (int i=0; i<radialAxesList.size(); ++i)
  27732. removeRadialAxis(radialAxesList.at(i));
  27733. }
  27734. QCPPolarAxisAngular::LabelMode QCPPolarAxisAngular::tickLabelMode() const
  27735. {
  27736. switch (mLabelPainter.anchorMode())
  27737. {
  27738. case QCPLabelPainterPrivate::amSkewedUpright: return lmUpright;
  27739. case QCPLabelPainterPrivate::amSkewedRotated: return lmRotated;
  27740. default: qDebug() << Q_FUNC_INFO << "invalid mode for polar axis"; break;
  27741. }
  27742. return lmUpright;
  27743. }
  27744. /* No documentation as it is a property getter */
  27745. QString QCPPolarAxisAngular::numberFormat() const
  27746. {
  27747. QString result;
  27748. result.append(mNumberFormatChar);
  27749. if (mNumberBeautifulPowers)
  27750. {
  27751. result.append(QLatin1Char('b'));
  27752. if (mLabelPainter.multiplicationSymbol() == QCPLabelPainterPrivate::SymbolCross)
  27753. result.append(QLatin1Char('c'));
  27754. }
  27755. return result;
  27756. }
  27757. /*!
  27758. Returns the number of axes on the axis rect side specified with \a type.
  27759. \see axis
  27760. */
  27761. int QCPPolarAxisAngular::radialAxisCount() const
  27762. {
  27763. return mRadialAxes.size();
  27764. }
  27765. /*!
  27766. Returns the axis with the given \a index on the axis rect side specified with \a type.
  27767. \see axisCount, axes
  27768. */
  27769. QCPPolarAxisRadial *QCPPolarAxisAngular::radialAxis(int index) const
  27770. {
  27771. if (index >= 0 && index < mRadialAxes.size())
  27772. {
  27773. return mRadialAxes.at(index);
  27774. } else
  27775. {
  27776. qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index;
  27777. return 0;
  27778. }
  27779. }
  27780. /*!
  27781. Returns all axes on the axis rect sides specified with \a types.
  27782. \a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of
  27783. multiple sides.
  27784. \see axis
  27785. */
  27786. QList<QCPPolarAxisRadial*> QCPPolarAxisAngular::radialAxes() const
  27787. {
  27788. return mRadialAxes;
  27789. }
  27790. /*!
  27791. Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a
  27792. new QCPAxis instance is created internally. QCustomPlot owns the returned axis, so if you want to
  27793. remove an axis, use \ref removeAxis instead of deleting it manually.
  27794. You may inject QCPAxis instances (or subclasses of QCPAxis) by setting \a axis to an axis that was
  27795. previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership
  27796. of the axis, so you may not delete it afterwards. Further, the \a axis must have been created
  27797. with this axis rect as parent and with the same axis type as specified in \a type. If this is not
  27798. the case, a debug output is generated, the axis is not added, and the method returns 0.
  27799. This method can not be used to move \a axis between axis rects. The same \a axis instance must
  27800. not be added multiple times to the same or different axis rects.
  27801. If an axis rect side already contains one or more axes, the lower and upper endings of the new
  27802. axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref
  27803. QCPLineEnding::esHalfBar.
  27804. \see addAxes, setupFullAxesBox
  27805. */
  27806. QCPPolarAxisRadial *QCPPolarAxisAngular::addRadialAxis(QCPPolarAxisRadial *axis)
  27807. {
  27808. QCPPolarAxisRadial *newAxis = axis;
  27809. if (!newAxis)
  27810. {
  27811. newAxis = new QCPPolarAxisRadial(this);
  27812. } else // user provided existing axis instance, do some sanity checks
  27813. {
  27814. if (newAxis->angularAxis() != this)
  27815. {
  27816. qDebug() << Q_FUNC_INFO << "passed radial axis doesn't have this angular axis as parent angular axis";
  27817. return 0;
  27818. }
  27819. if (radialAxes().contains(newAxis))
  27820. {
  27821. qDebug() << Q_FUNC_INFO << "passed axis is already owned by this angular axis";
  27822. return 0;
  27823. }
  27824. }
  27825. mRadialAxes.append(newAxis);
  27826. return newAxis;
  27827. }
  27828. /*!
  27829. Removes the specified \a axis from the axis rect and deletes it.
  27830. Returns true on success, i.e. if \a axis was a valid axis in this axis rect.
  27831. \see addAxis
  27832. */
  27833. bool QCPPolarAxisAngular::removeRadialAxis(QCPPolarAxisRadial *radialAxis)
  27834. {
  27835. if (mRadialAxes.contains(radialAxis))
  27836. {
  27837. mRadialAxes.removeOne(radialAxis);
  27838. delete radialAxis;
  27839. return true;
  27840. } else
  27841. {
  27842. qDebug() << Q_FUNC_INFO << "Radial axis isn't associated with this angular axis:" << reinterpret_cast<quintptr>(radialAxis);
  27843. return false;
  27844. }
  27845. }
  27846. QRegion QCPPolarAxisAngular::exactClipRegion() const
  27847. {
  27848. return QRegion(mCenter.x()-mRadius, mCenter.y()-mRadius, qRound(2*mRadius), qRound(2*mRadius), QRegion::Ellipse);
  27849. }
  27850. /*!
  27851. If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
  27852. bounds of the range. The range is simply moved by \a diff.
  27853. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
  27854. corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
  27855. */
  27856. void QCPPolarAxisAngular::moveRange(double diff)
  27857. {
  27858. QCPRange oldRange = mRange;
  27859. mRange.lower += diff;
  27860. mRange.upper += diff;
  27861. emit rangeChanged(mRange);
  27862. emit rangeChanged(mRange, oldRange);
  27863. }
  27864. /*!
  27865. Scales the range of this axis by \a factor around the center of the current axis range. For
  27866. example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
  27867. range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
  27868. the center will have moved symmetrically closer).
  27869. If you wish to scale around a different coordinate than the current axis range center, use the
  27870. overload \ref scaleRange(double factor, double center).
  27871. */
  27872. void QCPPolarAxisAngular::scaleRange(double factor)
  27873. {
  27874. scaleRange(factor, range().center());
  27875. }
  27876. /*! \overload
  27877. Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
  27878. factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
  27879. coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
  27880. around 1.0 will have moved symmetrically closer to 1.0).
  27881. \see scaleRange(double factor)
  27882. */
  27883. void QCPPolarAxisAngular::scaleRange(double factor, double center)
  27884. {
  27885. QCPRange oldRange = mRange;
  27886. QCPRange newRange;
  27887. newRange.lower = (mRange.lower-center)*factor + center;
  27888. newRange.upper = (mRange.upper-center)*factor + center;
  27889. if (QCPRange::validRange(newRange))
  27890. mRange = newRange.sanitizedForLinScale();
  27891. emit rangeChanged(mRange);
  27892. emit rangeChanged(mRange, oldRange);
  27893. }
  27894. /*!
  27895. Changes the axis range such that all plottables associated with this axis are fully visible in
  27896. that dimension.
  27897. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
  27898. */
  27899. void QCPPolarAxisAngular::rescale(bool onlyVisiblePlottables)
  27900. {
  27901. QCPRange newRange;
  27902. bool haveRange = false;
  27903. for (int i=0; i<mGraphs.size(); ++i)
  27904. {
  27905. if (!mGraphs.at(i)->realVisibility() && onlyVisiblePlottables)
  27906. continue;
  27907. QCPRange range;
  27908. bool currentFoundRange;
  27909. if (mGraphs.at(i)->keyAxis() == this)
  27910. range = mGraphs.at(i)->getKeyRange(currentFoundRange, QCP::sdBoth);
  27911. else
  27912. range = mGraphs.at(i)->getValueRange(currentFoundRange, QCP::sdBoth);
  27913. if (currentFoundRange)
  27914. {
  27915. if (!haveRange)
  27916. newRange = range;
  27917. else
  27918. newRange.expand(range);
  27919. haveRange = true;
  27920. }
  27921. }
  27922. if (haveRange)
  27923. {
  27924. 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
  27925. {
  27926. 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
  27927. newRange.lower = center-mRange.size()/2.0;
  27928. newRange.upper = center+mRange.size()/2.0;
  27929. }
  27930. setRange(newRange);
  27931. }
  27932. }
  27933. /*!
  27934. Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
  27935. */
  27936. void QCPPolarAxisAngular::pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const
  27937. {
  27938. if (!mRadialAxes.isEmpty())
  27939. mRadialAxes.first()->pixelToCoord(pixelPos, angleCoord, radiusCoord);
  27940. else
  27941. qDebug() << Q_FUNC_INFO << "no radial axis configured";
  27942. }
  27943. /*!
  27944. Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
  27945. */
  27946. QPointF QCPPolarAxisAngular::coordToPixel(double angleCoord, double radiusCoord) const
  27947. {
  27948. if (!mRadialAxes.isEmpty())
  27949. {
  27950. return mRadialAxes.first()->coordToPixel(angleCoord, radiusCoord);
  27951. } else
  27952. {
  27953. qDebug() << Q_FUNC_INFO << "no radial axis configured";
  27954. return QPointF();
  27955. }
  27956. }
  27957. /*!
  27958. Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
  27959. is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
  27960. function does not change the current selection state of the axis.
  27961. If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
  27962. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
  27963. */
  27964. QCPPolarAxisAngular::SelectablePart QCPPolarAxisAngular::getPartAt(const QPointF &pos) const
  27965. {
  27966. Q_UNUSED(pos) // TODO remove later
  27967. if (!mVisible)
  27968. return spNone;
  27969. /*
  27970. TODO:
  27971. if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
  27972. return spAxis;
  27973. else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
  27974. return spTickLabels;
  27975. else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
  27976. return spAxisLabel;
  27977. else */
  27978. return spNone;
  27979. }
  27980. /* inherits documentation from base class */
  27981. double QCPPolarAxisAngular::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  27982. {
  27983. /*
  27984. if (!mParentPlot) return -1;
  27985. SelectablePart part = getPartAt(pos);
  27986. if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
  27987. return -1;
  27988. if (details)
  27989. details->setValue(part);
  27990. return mParentPlot->selectionTolerance()*0.99;
  27991. */
  27992. Q_UNUSED(details)
  27993. if (onlySelectable)
  27994. return -1;
  27995. if (QRectF(mOuterRect).contains(pos))
  27996. {
  27997. if (mParentPlot)
  27998. return mParentPlot->selectionTolerance()*0.99;
  27999. else
  28000. {
  28001. qDebug() << Q_FUNC_INFO << "parent plot not defined";
  28002. return -1;
  28003. }
  28004. } else
  28005. return -1;
  28006. }
  28007. /*!
  28008. This method is called automatically upon replot and doesn't need to be called by users of
  28009. QCPPolarAxisAngular.
  28010. Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
  28011. and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
  28012. QCPInsetLayout::update function.
  28013. \seebaseclassmethod
  28014. */
  28015. void QCPPolarAxisAngular::update(UpdatePhase phase)
  28016. {
  28017. QCPLayoutElement::update(phase);
  28018. switch (phase)
  28019. {
  28020. case upPreparation:
  28021. {
  28022. setupTickVectors();
  28023. for (int i=0; i<mRadialAxes.size(); ++i)
  28024. mRadialAxes.at(i)->setupTickVectors();
  28025. break;
  28026. }
  28027. case upLayout:
  28028. {
  28029. mCenter = mRect.center();
  28030. mRadius = 0.5*qMin(qAbs(mRect.width()), qAbs(mRect.height()));
  28031. if (mRadius < 1) mRadius = 1; // prevent cases where radius might become 0 which causes trouble
  28032. for (int i=0; i<mRadialAxes.size(); ++i)
  28033. mRadialAxes.at(i)->updateGeometry(mCenter, mRadius);
  28034. mInsetLayout->setOuterRect(rect());
  28035. break;
  28036. }
  28037. default: break;
  28038. }
  28039. // pass update call on to inset layout (doesn't happen automatically, because QCPPolarAxis doesn't derive from QCPLayout):
  28040. mInsetLayout->update(phase);
  28041. }
  28042. /* inherits documentation from base class */
  28043. QList<QCPLayoutElement*> QCPPolarAxisAngular::elements(bool recursive) const
  28044. {
  28045. QList<QCPLayoutElement*> result;
  28046. if (mInsetLayout)
  28047. {
  28048. result << mInsetLayout;
  28049. if (recursive)
  28050. result << mInsetLayout->elements(recursive);
  28051. }
  28052. return result;
  28053. }
  28054. bool QCPPolarAxisAngular::removeGraph(QCPPolarGraph *graph)
  28055. {
  28056. if (!mGraphs.contains(graph))
  28057. {
  28058. qDebug() << Q_FUNC_INFO << "graph not in list:" << reinterpret_cast<quintptr>(graph);
  28059. return false;
  28060. }
  28061. // remove plottable from legend:
  28062. graph->removeFromLegend();
  28063. // remove plottable:
  28064. delete graph;
  28065. mGraphs.removeOne(graph);
  28066. return true;
  28067. }
  28068. /* inherits documentation from base class */
  28069. void QCPPolarAxisAngular::applyDefaultAntialiasingHint(QCPPainter *painter) const
  28070. {
  28071. applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
  28072. }
  28073. /* inherits documentation from base class */
  28074. void QCPPolarAxisAngular::draw(QCPPainter *painter)
  28075. {
  28076. drawBackground(painter, mCenter, mRadius);
  28077. // draw baseline circle:
  28078. painter->setPen(getBasePen());
  28079. painter->drawEllipse(mCenter, mRadius, mRadius);
  28080. // draw subticks:
  28081. if (!mSubTickVector.isEmpty())
  28082. {
  28083. painter->setPen(getSubTickPen());
  28084. for (int i=0; i<mSubTickVector.size(); ++i)
  28085. {
  28086. painter->drawLine(mCenter+mSubTickVectorCosSin.at(i)*(mRadius-mSubTickLengthIn),
  28087. mCenter+mSubTickVectorCosSin.at(i)*(mRadius+mSubTickLengthOut));
  28088. }
  28089. }
  28090. // draw ticks and labels:
  28091. if (!mTickVector.isEmpty())
  28092. {
  28093. mLabelPainter.setAnchorReference(mCenter);
  28094. mLabelPainter.setFont(getTickLabelFont());
  28095. mLabelPainter.setColor(getTickLabelColor());
  28096. const QPen ticksPen = getTickPen();
  28097. painter->setPen(ticksPen);
  28098. for (int i=0; i<mTickVector.size(); ++i)
  28099. {
  28100. const QPointF outerTick = mCenter+mTickVectorCosSin.at(i)*(mRadius+mTickLengthOut);
  28101. painter->drawLine(mCenter+mTickVectorCosSin.at(i)*(mRadius-mTickLengthIn), outerTick);
  28102. // draw tick labels:
  28103. if (!mTickVectorLabels.isEmpty())
  28104. {
  28105. 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
  28106. mLabelPainter.drawTickLabel(painter, outerTick, mTickVectorLabels.at(i));
  28107. }
  28108. }
  28109. }
  28110. }
  28111. /* inherits documentation from base class */
  28112. QCP::Interaction QCPPolarAxisAngular::selectionCategory() const
  28113. {
  28114. return QCP::iSelectAxes;
  28115. }
  28116. /*!
  28117. Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the
  28118. axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect
  28119. backgrounds are usually drawn below everything else.
  28120. For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be
  28121. enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio
  28122. is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  28123. consider using the overloaded version of this function.
  28124. Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref
  28125. setBackground(const QBrush &brush).
  28126. \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush)
  28127. */
  28128. void QCPPolarAxisAngular::setBackground(const QPixmap &pm)
  28129. {
  28130. mBackgroundPixmap = pm;
  28131. mScaledBackgroundPixmap = QPixmap();
  28132. }
  28133. /*! \overload
  28134. Sets \a brush as the background brush. The axis rect background will be filled with this brush.
  28135. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds
  28136. are usually drawn below everything else.
  28137. The brush will be drawn before (under) any background pixmap, which may be specified with \ref
  28138. setBackground(const QPixmap &pm).
  28139. To disable drawing of a background brush, set \a brush to Qt::NoBrush.
  28140. \see setBackground(const QPixmap &pm)
  28141. */
  28142. void QCPPolarAxisAngular::setBackground(const QBrush &brush)
  28143. {
  28144. mBackgroundBrush = brush;
  28145. }
  28146. /*! \overload
  28147. Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it
  28148. shall be scaled in one call.
  28149. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  28150. */
  28151. void QCPPolarAxisAngular::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
  28152. {
  28153. mBackgroundPixmap = pm;
  28154. mScaledBackgroundPixmap = QPixmap();
  28155. mBackgroundScaled = scaled;
  28156. mBackgroundScaledMode = mode;
  28157. }
  28158. /*!
  28159. Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled
  28160. is set to true, you may control whether and how the aspect ratio of the original pixmap is
  28161. preserved with \ref setBackgroundScaledMode.
  28162. Note that the scaled version of the original pixmap is buffered, so there is no performance
  28163. penalty on replots. (Except when the axis rect dimensions are changed continuously.)
  28164. \see setBackground, setBackgroundScaledMode
  28165. */
  28166. void QCPPolarAxisAngular::setBackgroundScaled(bool scaled)
  28167. {
  28168. mBackgroundScaled = scaled;
  28169. }
  28170. /*!
  28171. If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to
  28172. define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved.
  28173. \see setBackground, setBackgroundScaled
  28174. */
  28175. void QCPPolarAxisAngular::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  28176. {
  28177. mBackgroundScaledMode = mode;
  28178. }
  28179. void QCPPolarAxisAngular::setRangeDrag(bool enabled)
  28180. {
  28181. mRangeDrag = enabled;
  28182. }
  28183. void QCPPolarAxisAngular::setRangeZoom(bool enabled)
  28184. {
  28185. mRangeZoom = enabled;
  28186. }
  28187. void QCPPolarAxisAngular::setRangeZoomFactor(double factor)
  28188. {
  28189. mRangeZoomFactor = factor;
  28190. }
  28191. /*!
  28192. Sets the range of the axis.
  28193. This slot may be connected with the \ref rangeChanged signal of another axis so this axis
  28194. is always synchronized with the other axis range, when it changes.
  28195. To invert the direction of an axis, use \ref setRangeReversed.
  28196. */
  28197. void QCPPolarAxisAngular::setRange(const QCPRange &range)
  28198. {
  28199. if (range.lower == mRange.lower && range.upper == mRange.upper)
  28200. return;
  28201. if (!QCPRange::validRange(range)) return;
  28202. QCPRange oldRange = mRange;
  28203. mRange = range.sanitizedForLinScale();
  28204. emit rangeChanged(mRange);
  28205. emit rangeChanged(mRange, oldRange);
  28206. }
  28207. /*!
  28208. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  28209. (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
  28210. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  28211. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  28212. directly.
  28213. \see SelectablePart, setSelectedParts
  28214. */
  28215. void QCPPolarAxisAngular::setSelectableParts(const SelectableParts &selectable)
  28216. {
  28217. if (mSelectableParts != selectable)
  28218. {
  28219. mSelectableParts = selectable;
  28220. emit selectableChanged(mSelectableParts);
  28221. }
  28222. }
  28223. /*!
  28224. Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
  28225. is selected, it uses a different pen/font.
  28226. The entire selection mechanism for axes is handled automatically when \ref
  28227. QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
  28228. wish to change the selection state manually.
  28229. This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
  28230. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  28231. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
  28232. setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
  28233. */
  28234. void QCPPolarAxisAngular::setSelectedParts(const SelectableParts &selected)
  28235. {
  28236. if (mSelectedParts != selected)
  28237. {
  28238. mSelectedParts = selected;
  28239. emit selectionChanged(mSelectedParts);
  28240. }
  28241. }
  28242. /*!
  28243. \overload
  28244. Sets the lower and upper bound of the axis range.
  28245. To invert the direction of an axis, use \ref setRangeReversed.
  28246. There is also a slot to set a range, see \ref setRange(const QCPRange &range).
  28247. */
  28248. void QCPPolarAxisAngular::setRange(double lower, double upper)
  28249. {
  28250. if (lower == mRange.lower && upper == mRange.upper)
  28251. return;
  28252. if (!QCPRange::validRange(lower, upper)) return;
  28253. QCPRange oldRange = mRange;
  28254. mRange.lower = lower;
  28255. mRange.upper = upper;
  28256. mRange = mRange.sanitizedForLinScale();
  28257. emit rangeChanged(mRange);
  28258. emit rangeChanged(mRange, oldRange);
  28259. }
  28260. /*!
  28261. \overload
  28262. Sets the range of the axis.
  28263. The \a position coordinate indicates together with the \a alignment parameter, where the new
  28264. range will be positioned. \a size defines the size of the new axis range. \a alignment may be
  28265. Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
  28266. or center of the range to be aligned with \a position. Any other values of \a alignment will
  28267. default to Qt::AlignCenter.
  28268. */
  28269. void QCPPolarAxisAngular::setRange(double position, double size, Qt::AlignmentFlag alignment)
  28270. {
  28271. if (alignment == Qt::AlignLeft)
  28272. setRange(position, position+size);
  28273. else if (alignment == Qt::AlignRight)
  28274. setRange(position-size, position);
  28275. else // alignment == Qt::AlignCenter
  28276. setRange(position-size/2.0, position+size/2.0);
  28277. }
  28278. /*!
  28279. Sets the lower bound of the axis range. The upper bound is not changed.
  28280. \see setRange
  28281. */
  28282. void QCPPolarAxisAngular::setRangeLower(double lower)
  28283. {
  28284. if (mRange.lower == lower)
  28285. return;
  28286. QCPRange oldRange = mRange;
  28287. mRange.lower = lower;
  28288. mRange = mRange.sanitizedForLinScale();
  28289. emit rangeChanged(mRange);
  28290. emit rangeChanged(mRange, oldRange);
  28291. }
  28292. /*!
  28293. Sets the upper bound of the axis range. The lower bound is not changed.
  28294. \see setRange
  28295. */
  28296. void QCPPolarAxisAngular::setRangeUpper(double upper)
  28297. {
  28298. if (mRange.upper == upper)
  28299. return;
  28300. QCPRange oldRange = mRange;
  28301. mRange.upper = upper;
  28302. mRange = mRange.sanitizedForLinScale();
  28303. emit rangeChanged(mRange);
  28304. emit rangeChanged(mRange, oldRange);
  28305. }
  28306. /*!
  28307. Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
  28308. axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
  28309. direction of increasing values is inverted.
  28310. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
  28311. of the \ref setRange interface will still reference the mathematically smaller number than the \a
  28312. upper part.
  28313. */
  28314. void QCPPolarAxisAngular::setRangeReversed(bool reversed)
  28315. {
  28316. mRangeReversed = reversed;
  28317. }
  28318. void QCPPolarAxisAngular::setAngle(double degrees)
  28319. {
  28320. mAngle = degrees;
  28321. mAngleRad = mAngle/180.0*M_PI;
  28322. }
  28323. /*!
  28324. The axis ticker is responsible for generating the tick positions and tick labels. See the
  28325. documentation of QCPAxisTicker for details on how to work with axis tickers.
  28326. You can change the tick positioning/labeling behaviour of this axis by setting a different
  28327. QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
  28328. ticker, access it via \ref ticker.
  28329. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  28330. ticker simply by passing the same shared pointer to multiple axes.
  28331. \see ticker
  28332. */
  28333. void QCPPolarAxisAngular::setTicker(QSharedPointer<QCPAxisTicker> ticker)
  28334. {
  28335. if (ticker)
  28336. mTicker = ticker;
  28337. else
  28338. qDebug() << Q_FUNC_INFO << "can not set 0 as axis ticker";
  28339. // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
  28340. }
  28341. /*!
  28342. Sets whether tick marks are displayed.
  28343. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
  28344. that, see \ref setTickLabels.
  28345. \see setSubTicks
  28346. */
  28347. void QCPPolarAxisAngular::setTicks(bool show)
  28348. {
  28349. if (mTicks != show)
  28350. {
  28351. mTicks = show;
  28352. //mCachedMarginValid = false;
  28353. }
  28354. }
  28355. /*!
  28356. Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
  28357. */
  28358. void QCPPolarAxisAngular::setTickLabels(bool show)
  28359. {
  28360. if (mTickLabels != show)
  28361. {
  28362. mTickLabels = show;
  28363. //mCachedMarginValid = false;
  28364. if (!mTickLabels)
  28365. mTickVectorLabels.clear();
  28366. }
  28367. }
  28368. /*!
  28369. Sets the distance between the axis base line (including any outward ticks) and the tick labels.
  28370. \see setLabelPadding, setPadding
  28371. */
  28372. void QCPPolarAxisAngular::setTickLabelPadding(int padding)
  28373. {
  28374. mLabelPainter.setPadding(padding);
  28375. }
  28376. /*!
  28377. Sets the font of the tick labels.
  28378. \see setTickLabels, setTickLabelColor
  28379. */
  28380. void QCPPolarAxisAngular::setTickLabelFont(const QFont &font)
  28381. {
  28382. mTickLabelFont = font;
  28383. }
  28384. /*!
  28385. Sets the color of the tick labels.
  28386. \see setTickLabels, setTickLabelFont
  28387. */
  28388. void QCPPolarAxisAngular::setTickLabelColor(const QColor &color)
  28389. {
  28390. mTickLabelColor = color;
  28391. }
  28392. /*!
  28393. Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
  28394. the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
  28395. from -90 to 90 degrees.
  28396. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
  28397. other angles, the label is drawn with an offset such that it seems to point toward or away from
  28398. the tick mark.
  28399. */
  28400. void QCPPolarAxisAngular::setTickLabelRotation(double degrees)
  28401. {
  28402. mLabelPainter.setRotation(degrees);
  28403. }
  28404. void QCPPolarAxisAngular::setTickLabelMode(LabelMode mode)
  28405. {
  28406. switch (mode)
  28407. {
  28408. case lmUpright: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedUpright); break;
  28409. case lmRotated: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedRotated); break;
  28410. }
  28411. }
  28412. /*!
  28413. Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
  28414. of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
  28415. that, see the "Argument Formats" section in the detailed description of the QString class.
  28416. \a formatCode is a string of one, two or three characters. The first character is identical to
  28417. the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
  28418. format, 'g'/'G' scientific or fixed, whichever is shorter.
  28419. The second and third characters are optional and specific to QCustomPlot:\n If the first char was
  28420. 'e' or 'g', numbers are/might be displayed in the scientific format, e.g. "5.5e9", which might be
  28421. visually unappealing in a plot. So when the second char of \a formatCode is set to 'b' (for
  28422. "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
  28423. [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
  28424. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
  28425. be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
  28426. cross and 183 (0xB7) for the dot.
  28427. Examples for \a formatCode:
  28428. \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
  28429. normal scientific format is used
  28430. \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
  28431. beautifully typeset decimal powers and a dot as multiplication sign
  28432. \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
  28433. multiplication sign
  28434. \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
  28435. powers. Format code will be reduced to 'f'.
  28436. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
  28437. code will not be changed.
  28438. */
  28439. void QCPPolarAxisAngular::setNumberFormat(const QString &formatCode)
  28440. {
  28441. if (formatCode.isEmpty())
  28442. {
  28443. qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
  28444. return;
  28445. }
  28446. //mCachedMarginValid = false;
  28447. // interpret first char as number format char:
  28448. QString allowedFormatChars(QLatin1String("eEfgG"));
  28449. if (allowedFormatChars.contains(formatCode.at(0)))
  28450. {
  28451. mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
  28452. } else
  28453. {
  28454. qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
  28455. return;
  28456. }
  28457. if (formatCode.length() < 2)
  28458. {
  28459. mNumberBeautifulPowers = false;
  28460. mNumberMultiplyCross = false;
  28461. } else
  28462. {
  28463. // interpret second char as indicator for beautiful decimal powers:
  28464. if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
  28465. mNumberBeautifulPowers = true;
  28466. else
  28467. qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
  28468. if (formatCode.length() < 3)
  28469. {
  28470. mNumberMultiplyCross = false;
  28471. } else
  28472. {
  28473. // interpret third char as indicator for dot or cross multiplication symbol:
  28474. if (formatCode.at(2) == QLatin1Char('c'))
  28475. mNumberMultiplyCross = true;
  28476. else if (formatCode.at(2) == QLatin1Char('d'))
  28477. mNumberMultiplyCross = false;
  28478. else
  28479. qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
  28480. }
  28481. }
  28482. mLabelPainter.setSubstituteExponent(mNumberBeautifulPowers);
  28483. mLabelPainter.setMultiplicationSymbol(mNumberMultiplyCross ? QCPLabelPainterPrivate::SymbolCross : QCPLabelPainterPrivate::SymbolDot);
  28484. }
  28485. /*!
  28486. Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
  28487. for details. The effect of precisions are most notably for number Formats starting with 'e', see
  28488. \ref setNumberFormat
  28489. */
  28490. void QCPPolarAxisAngular::setNumberPrecision(int precision)
  28491. {
  28492. if (mNumberPrecision != precision)
  28493. {
  28494. mNumberPrecision = precision;
  28495. //mCachedMarginValid = false;
  28496. }
  28497. }
  28498. /*!
  28499. Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
  28500. plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
  28501. zero, the tick labels and axis label will increase their distance to the axis accordingly, so
  28502. they won't collide with the ticks.
  28503. \see setSubTickLength, setTickLengthIn, setTickLengthOut
  28504. */
  28505. void QCPPolarAxisAngular::setTickLength(int inside, int outside)
  28506. {
  28507. setTickLengthIn(inside);
  28508. setTickLengthOut(outside);
  28509. }
  28510. /*!
  28511. Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
  28512. inside the plot.
  28513. \see setTickLengthOut, setTickLength, setSubTickLength
  28514. */
  28515. void QCPPolarAxisAngular::setTickLengthIn(int inside)
  28516. {
  28517. if (mTickLengthIn != inside)
  28518. {
  28519. mTickLengthIn = inside;
  28520. }
  28521. }
  28522. /*!
  28523. Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
  28524. outside the plot. If \a outside is greater than zero, the tick labels and axis label will
  28525. increase their distance to the axis accordingly, so they won't collide with the ticks.
  28526. \see setTickLengthIn, setTickLength, setSubTickLength
  28527. */
  28528. void QCPPolarAxisAngular::setTickLengthOut(int outside)
  28529. {
  28530. if (mTickLengthOut != outside)
  28531. {
  28532. mTickLengthOut = outside;
  28533. //mCachedMarginValid = false; // only outside tick length can change margin
  28534. }
  28535. }
  28536. /*!
  28537. Sets whether sub tick marks are displayed.
  28538. Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
  28539. \see setTicks
  28540. */
  28541. void QCPPolarAxisAngular::setSubTicks(bool show)
  28542. {
  28543. if (mSubTicks != show)
  28544. {
  28545. mSubTicks = show;
  28546. //mCachedMarginValid = false;
  28547. }
  28548. }
  28549. /*!
  28550. Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
  28551. the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
  28552. than zero, the tick labels and axis label will increase their distance to the axis accordingly,
  28553. so they won't collide with the ticks.
  28554. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
  28555. */
  28556. void QCPPolarAxisAngular::setSubTickLength(int inside, int outside)
  28557. {
  28558. setSubTickLengthIn(inside);
  28559. setSubTickLengthOut(outside);
  28560. }
  28561. /*!
  28562. Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
  28563. the plot.
  28564. \see setSubTickLengthOut, setSubTickLength, setTickLength
  28565. */
  28566. void QCPPolarAxisAngular::setSubTickLengthIn(int inside)
  28567. {
  28568. if (mSubTickLengthIn != inside)
  28569. {
  28570. mSubTickLengthIn = inside;
  28571. }
  28572. }
  28573. /*!
  28574. Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
  28575. outside the plot. If \a outside is greater than zero, the tick labels will increase their
  28576. distance to the axis accordingly, so they won't collide with the ticks.
  28577. \see setSubTickLengthIn, setSubTickLength, setTickLength
  28578. */
  28579. void QCPPolarAxisAngular::setSubTickLengthOut(int outside)
  28580. {
  28581. if (mSubTickLengthOut != outside)
  28582. {
  28583. mSubTickLengthOut = outside;
  28584. //mCachedMarginValid = false; // only outside tick length can change margin
  28585. }
  28586. }
  28587. /*!
  28588. Sets the pen, the axis base line is drawn with.
  28589. \see setTickPen, setSubTickPen
  28590. */
  28591. void QCPPolarAxisAngular::setBasePen(const QPen &pen)
  28592. {
  28593. mBasePen = pen;
  28594. }
  28595. /*!
  28596. Sets the pen, tick marks will be drawn with.
  28597. \see setTickLength, setBasePen
  28598. */
  28599. void QCPPolarAxisAngular::setTickPen(const QPen &pen)
  28600. {
  28601. mTickPen = pen;
  28602. }
  28603. /*!
  28604. Sets the pen, subtick marks will be drawn with.
  28605. \see setSubTickCount, setSubTickLength, setBasePen
  28606. */
  28607. void QCPPolarAxisAngular::setSubTickPen(const QPen &pen)
  28608. {
  28609. mSubTickPen = pen;
  28610. }
  28611. /*!
  28612. Sets the font of the axis label.
  28613. \see setLabelColor
  28614. */
  28615. void QCPPolarAxisAngular::setLabelFont(const QFont &font)
  28616. {
  28617. if (mLabelFont != font)
  28618. {
  28619. mLabelFont = font;
  28620. //mCachedMarginValid = false;
  28621. }
  28622. }
  28623. /*!
  28624. Sets the color of the axis label.
  28625. \see setLabelFont
  28626. */
  28627. void QCPPolarAxisAngular::setLabelColor(const QColor &color)
  28628. {
  28629. mLabelColor = color;
  28630. }
  28631. /*!
  28632. Sets the text of the axis label that will be shown below/above or next to the axis, depending on
  28633. its orientation. To disable axis labels, pass an empty string as \a str.
  28634. */
  28635. void QCPPolarAxisAngular::setLabel(const QString &str)
  28636. {
  28637. if (mLabel != str)
  28638. {
  28639. mLabel = str;
  28640. //mCachedMarginValid = false;
  28641. }
  28642. }
  28643. /*!
  28644. Sets the distance between the tick labels and the axis label.
  28645. \see setTickLabelPadding, setPadding
  28646. */
  28647. void QCPPolarAxisAngular::setLabelPadding(int padding)
  28648. {
  28649. if (mLabelPadding != padding)
  28650. {
  28651. mLabelPadding = padding;
  28652. //mCachedMarginValid = false;
  28653. }
  28654. }
  28655. /*!
  28656. Sets the font that is used for tick labels when they are selected.
  28657. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28658. */
  28659. void QCPPolarAxisAngular::setSelectedTickLabelFont(const QFont &font)
  28660. {
  28661. if (font != mSelectedTickLabelFont)
  28662. {
  28663. mSelectedTickLabelFont = font;
  28664. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  28665. }
  28666. }
  28667. /*!
  28668. Sets the font that is used for the axis label when it is selected.
  28669. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28670. */
  28671. void QCPPolarAxisAngular::setSelectedLabelFont(const QFont &font)
  28672. {
  28673. mSelectedLabelFont = font;
  28674. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  28675. }
  28676. /*!
  28677. Sets the color that is used for tick labels when they are selected.
  28678. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28679. */
  28680. void QCPPolarAxisAngular::setSelectedTickLabelColor(const QColor &color)
  28681. {
  28682. if (color != mSelectedTickLabelColor)
  28683. {
  28684. mSelectedTickLabelColor = color;
  28685. }
  28686. }
  28687. /*!
  28688. Sets the color that is used for the axis label when it is selected.
  28689. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28690. */
  28691. void QCPPolarAxisAngular::setSelectedLabelColor(const QColor &color)
  28692. {
  28693. mSelectedLabelColor = color;
  28694. }
  28695. /*!
  28696. Sets the pen that is used to draw the axis base line when selected.
  28697. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28698. */
  28699. void QCPPolarAxisAngular::setSelectedBasePen(const QPen &pen)
  28700. {
  28701. mSelectedBasePen = pen;
  28702. }
  28703. /*!
  28704. Sets the pen that is used to draw the (major) ticks when selected.
  28705. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28706. */
  28707. void QCPPolarAxisAngular::setSelectedTickPen(const QPen &pen)
  28708. {
  28709. mSelectedTickPen = pen;
  28710. }
  28711. /*!
  28712. Sets the pen that is used to draw the subticks when selected.
  28713. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28714. */
  28715. void QCPPolarAxisAngular::setSelectedSubTickPen(const QPen &pen)
  28716. {
  28717. mSelectedSubTickPen = pen;
  28718. }
  28719. /*! \internal
  28720. Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a
  28721. pixmap.
  28722. If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an
  28723. according filling inside the axis rect with the provided \a painter.
  28724. Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version
  28725. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  28726. the axis rect with the provided \a painter. The scaled version is buffered in
  28727. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  28728. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  28729. dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
  28730. set.
  28731. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  28732. */
  28733. void QCPPolarAxisAngular::drawBackground(QCPPainter *painter, const QPointF &center, double radius)
  28734. {
  28735. // draw background fill (don't use circular clip, looks bad):
  28736. if (mBackgroundBrush != Qt::NoBrush)
  28737. {
  28738. QPainterPath ellipsePath;
  28739. ellipsePath.addEllipse(center, radius, radius);
  28740. painter->fillPath(ellipsePath, mBackgroundBrush);
  28741. }
  28742. // draw background pixmap (on top of fill, if brush specified):
  28743. if (!mBackgroundPixmap.isNull())
  28744. {
  28745. QRegion clipCircle(center.x()-radius, center.y()-radius, qRound(2*radius), qRound(2*radius), QRegion::Ellipse);
  28746. QRegion originalClip = painter->clipRegion();
  28747. painter->setClipRegion(clipCircle);
  28748. if (mBackgroundScaled)
  28749. {
  28750. // check whether mScaledBackground needs to be updated:
  28751. QSize scaledSize(mBackgroundPixmap.size());
  28752. scaledSize.scale(mRect.size(), mBackgroundScaledMode);
  28753. if (mScaledBackgroundPixmap.size() != scaledSize)
  28754. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
  28755. painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect());
  28756. } else
  28757. {
  28758. painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()));
  28759. }
  28760. painter->setClipRegion(originalClip);
  28761. }
  28762. }
  28763. /*! \internal
  28764. Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
  28765. QCPAxisTicker::generate on the currently installed ticker.
  28766. If a change in the label text/count is detected, the cached axis margin is invalidated to make
  28767. sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
  28768. */
  28769. void QCPPolarAxisAngular::setupTickVectors()
  28770. {
  28771. if (!mParentPlot) return;
  28772. if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
  28773. mSubTickVector.clear(); // since we might not pass it to mTicker->generate(), and we don't want old data in there
  28774. mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : 0, mTickLabels ? &mTickVectorLabels : 0);
  28775. // fill cos/sin buffers which will be used by draw() and QCPPolarGrid::draw(), so we don't have to calculate it twice:
  28776. mTickVectorCosSin.resize(mTickVector.size());
  28777. for (int i=0; i<mTickVector.size(); ++i)
  28778. {
  28779. const double theta = coordToAngleRad(mTickVector.at(i));
  28780. mTickVectorCosSin[i] = QPointF(qCos(theta), qSin(theta));
  28781. }
  28782. mSubTickVectorCosSin.resize(mSubTickVector.size());
  28783. for (int i=0; i<mSubTickVector.size(); ++i)
  28784. {
  28785. const double theta = coordToAngleRad(mSubTickVector.at(i));
  28786. mSubTickVectorCosSin[i] = QPointF(qCos(theta), qSin(theta));
  28787. }
  28788. }
  28789. /*! \internal
  28790. Returns the pen that is used to draw the axis base line. Depending on the selection state, this
  28791. is either mSelectedBasePen or mBasePen.
  28792. */
  28793. QPen QCPPolarAxisAngular::getBasePen() const
  28794. {
  28795. return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
  28796. }
  28797. /*! \internal
  28798. Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
  28799. is either mSelectedTickPen or mTickPen.
  28800. */
  28801. QPen QCPPolarAxisAngular::getTickPen() const
  28802. {
  28803. return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
  28804. }
  28805. /*! \internal
  28806. Returns the pen that is used to draw the subticks. Depending on the selection state, this
  28807. is either mSelectedSubTickPen or mSubTickPen.
  28808. */
  28809. QPen QCPPolarAxisAngular::getSubTickPen() const
  28810. {
  28811. return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
  28812. }
  28813. /*! \internal
  28814. Returns the font that is used to draw the tick labels. Depending on the selection state, this
  28815. is either mSelectedTickLabelFont or mTickLabelFont.
  28816. */
  28817. QFont QCPPolarAxisAngular::getTickLabelFont() const
  28818. {
  28819. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
  28820. }
  28821. /*! \internal
  28822. Returns the font that is used to draw the axis label. Depending on the selection state, this
  28823. is either mSelectedLabelFont or mLabelFont.
  28824. */
  28825. QFont QCPPolarAxisAngular::getLabelFont() const
  28826. {
  28827. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
  28828. }
  28829. /*! \internal
  28830. Returns the color that is used to draw the tick labels. Depending on the selection state, this
  28831. is either mSelectedTickLabelColor or mTickLabelColor.
  28832. */
  28833. QColor QCPPolarAxisAngular::getTickLabelColor() const
  28834. {
  28835. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
  28836. }
  28837. /*! \internal
  28838. Returns the color that is used to draw the axis label. Depending on the selection state, this
  28839. is either mSelectedLabelColor or mLabelColor.
  28840. */
  28841. QColor QCPPolarAxisAngular::getLabelColor() const
  28842. {
  28843. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
  28844. }
  28845. /*! \internal
  28846. Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
  28847. pressed, the range dragging interaction is initialized (the actual range manipulation happens in
  28848. the \ref mouseMoveEvent).
  28849. The mDragging flag is set to true and some anchor points are set that are needed to determine the
  28850. distance the mouse was dragged in the mouse move/release events later.
  28851. \see mouseMoveEvent, mouseReleaseEvent
  28852. */
  28853. void QCPPolarAxisAngular::mousePressEvent(QMouseEvent *event, const QVariant &details)
  28854. {
  28855. Q_UNUSED(details)
  28856. if (event->buttons() & Qt::LeftButton)
  28857. {
  28858. mDragging = true;
  28859. // initialize antialiasing backup in case we start dragging:
  28860. if (mParentPlot->noAntialiasingOnDrag())
  28861. {
  28862. mAADragBackup = mParentPlot->antialiasedElements();
  28863. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  28864. }
  28865. // Mouse range dragging interaction:
  28866. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  28867. {
  28868. mDragAngularStart = range();
  28869. mDragRadialStart.clear();
  28870. for (int i=0; i<mRadialAxes.size(); ++i)
  28871. mDragRadialStart.append(mRadialAxes.at(i)->range());
  28872. }
  28873. }
  28874. }
  28875. /*! \internal
  28876. Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a
  28877. preceding \ref mousePressEvent, the range is moved accordingly.
  28878. \see mousePressEvent, mouseReleaseEvent
  28879. */
  28880. void QCPPolarAxisAngular::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  28881. {
  28882. Q_UNUSED(startPos)
  28883. bool doReplot = false;
  28884. // Mouse range dragging interaction:
  28885. if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  28886. {
  28887. if (mRangeDrag)
  28888. {
  28889. doReplot = true;
  28890. double angleCoordStart, radiusCoordStart;
  28891. double angleCoord, radiusCoord;
  28892. pixelToCoord(startPos, angleCoordStart, radiusCoordStart);
  28893. pixelToCoord(event->pos(), angleCoord, radiusCoord);
  28894. double diff = angleCoordStart - angleCoord;
  28895. setRange(mDragAngularStart.lower+diff, mDragAngularStart.upper+diff);
  28896. }
  28897. for (int i=0; i<mRadialAxes.size(); ++i)
  28898. {
  28899. QCPPolarAxisRadial *ax = mRadialAxes.at(i);
  28900. if (!ax->rangeDrag())
  28901. continue;
  28902. doReplot = true;
  28903. double angleCoordStart, radiusCoordStart;
  28904. double angleCoord, radiusCoord;
  28905. ax->pixelToCoord(startPos, angleCoordStart, radiusCoordStart);
  28906. ax->pixelToCoord(event->pos(), angleCoord, radiusCoord);
  28907. if (ax->scaleType() == QCPPolarAxisRadial::stLinear)
  28908. {
  28909. double diff = radiusCoordStart - radiusCoord;
  28910. ax->setRange(mDragRadialStart.at(i).lower+diff, mDragRadialStart.at(i).upper+diff);
  28911. } else if (ax->scaleType() == QCPPolarAxisRadial::stLogarithmic)
  28912. {
  28913. if (radiusCoord != 0)
  28914. {
  28915. double diff = radiusCoordStart/radiusCoord;
  28916. ax->setRange(mDragRadialStart.at(i).lower*diff, mDragRadialStart.at(i).upper*diff);
  28917. }
  28918. }
  28919. }
  28920. if (doReplot) // if either vertical or horizontal drag was enabled, do a replot
  28921. {
  28922. if (mParentPlot->noAntialiasingOnDrag())
  28923. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  28924. mParentPlot->replot(QCustomPlot::rpQueuedReplot);
  28925. }
  28926. }
  28927. }
  28928. /* inherits documentation from base class */
  28929. void QCPPolarAxisAngular::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  28930. {
  28931. Q_UNUSED(event)
  28932. Q_UNUSED(startPos)
  28933. mDragging = false;
  28934. if (mParentPlot->noAntialiasingOnDrag())
  28935. {
  28936. mParentPlot->setAntialiasedElements(mAADragBackup);
  28937. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  28938. }
  28939. }
  28940. /*! \internal
  28941. Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
  28942. ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
  28943. the scaling operation is the current cursor position inside the axis rect. The scaling factor is
  28944. dependent on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
  28945. zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
  28946. Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse
  28947. wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be
  28948. multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as
  28949. exponent of the range zoom factor. This takes care of the wheel direction automatically, by
  28950. inverting the factor, when the wheel step is negative (f^-1 = 1/f).
  28951. */
  28952. void QCPPolarAxisAngular::wheelEvent(QWheelEvent *event)
  28953. {
  28954. bool doReplot = false;
  28955. // Mouse range zooming interaction:
  28956. if (mParentPlot->interactions().testFlag(QCP::iRangeZoom))
  28957. {
  28958. #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  28959. const double delta = event->delta();
  28960. #else
  28961. const double delta = event->angleDelta().y();
  28962. #endif
  28963. #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  28964. const QPointF pos = event->pos();
  28965. #else
  28966. const QPointF pos = event->position();
  28967. #endif
  28968. const double wheelSteps = delta/120.0; // a single step delta is +/-120 usually
  28969. if (mRangeZoom)
  28970. {
  28971. double angleCoord, radiusCoord;
  28972. pixelToCoord(pos, angleCoord, radiusCoord);
  28973. scaleRange(qPow(mRangeZoomFactor, wheelSteps), angleCoord);
  28974. }
  28975. for (int i=0; i<mRadialAxes.size(); ++i)
  28976. {
  28977. QCPPolarAxisRadial *ax = mRadialAxes.at(i);
  28978. if (!ax->rangeZoom())
  28979. continue;
  28980. doReplot = true;
  28981. double angleCoord, radiusCoord;
  28982. ax->pixelToCoord(pos, angleCoord, radiusCoord);
  28983. ax->scaleRange(qPow(ax->rangeZoomFactor(), wheelSteps), radiusCoord);
  28984. }
  28985. }
  28986. if (doReplot)
  28987. mParentPlot->replot();
  28988. }
  28989. bool QCPPolarAxisAngular::registerPolarGraph(QCPPolarGraph *graph)
  28990. {
  28991. if (mGraphs.contains(graph))
  28992. {
  28993. qDebug() << Q_FUNC_INFO << "plottable already added:" << reinterpret_cast<quintptr>(graph);
  28994. return false;
  28995. }
  28996. if (graph->keyAxis() != this)
  28997. {
  28998. qDebug() << Q_FUNC_INFO << "plottable not created with this as axis:" << reinterpret_cast<quintptr>(graph);
  28999. return false;
  29000. }
  29001. mGraphs.append(graph);
  29002. // possibly add plottable to legend:
  29003. if (mParentPlot->autoAddPlottableToLegend())
  29004. graph->addToLegend();
  29005. if (!graph->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
  29006. graph->setLayer(mParentPlot->currentLayer());
  29007. return true;
  29008. }
  29009. /* end of 'src/polar/layoutelement-angularaxis.cpp' */
  29010. /* including file 'src/polar/polargrid.cpp' */
  29011. /* modified 2022-11-06T12:45:57, size 7493 */
  29012. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29013. //////////////////// QCPPolarGrid
  29014. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29015. /*! \class QCPPolarGrid
  29016. \brief The grid in both angular and radial dimensions for polar plots
  29017. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  29018. functionality to be incomplete, as well as changing public interfaces in the future.
  29019. */
  29020. /*!
  29021. Creates a QCPPolarGrid instance and sets default values.
  29022. You shouldn't instantiate grids on their own, since every axis brings its own grid.
  29023. */
  29024. QCPPolarGrid::QCPPolarGrid(QCPPolarAxisAngular *parentAxis) :
  29025. QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis),
  29026. mType(gtNone),
  29027. mSubGridType(gtNone),
  29028. mAntialiasedSubGrid(true),
  29029. mAntialiasedZeroLine(true),
  29030. mParentAxis(parentAxis)
  29031. {
  29032. // warning: this is called in QCPPolarAxisAngular constructor, so parentAxis members should not be accessed/called
  29033. setParent(parentAxis);
  29034. setType(gtAll);
  29035. setSubGridType(gtNone);
  29036. setAngularPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
  29037. setAngularSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
  29038. setRadialPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
  29039. setRadialSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
  29040. setRadialZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine));
  29041. setAntialiased(true);
  29042. }
  29043. void QCPPolarGrid::setRadialAxis(QCPPolarAxisRadial *axis)
  29044. {
  29045. mRadialAxis = axis;
  29046. }
  29047. void QCPPolarGrid::setType(GridTypes type)
  29048. {
  29049. mType = type;
  29050. }
  29051. void QCPPolarGrid::setSubGridType(GridTypes type)
  29052. {
  29053. mSubGridType = type;
  29054. }
  29055. /*!
  29056. Sets whether sub grid lines are drawn antialiased.
  29057. */
  29058. void QCPPolarGrid::setAntialiasedSubGrid(bool enabled)
  29059. {
  29060. mAntialiasedSubGrid = enabled;
  29061. }
  29062. /*!
  29063. Sets whether zero lines are drawn antialiased.
  29064. */
  29065. void QCPPolarGrid::setAntialiasedZeroLine(bool enabled)
  29066. {
  29067. mAntialiasedZeroLine = enabled;
  29068. }
  29069. /*!
  29070. Sets the pen with which (major) grid lines are drawn.
  29071. */
  29072. void QCPPolarGrid::setAngularPen(const QPen &pen)
  29073. {
  29074. mAngularPen = pen;
  29075. }
  29076. /*!
  29077. Sets the pen with which sub grid lines are drawn.
  29078. */
  29079. void QCPPolarGrid::setAngularSubGridPen(const QPen &pen)
  29080. {
  29081. mAngularSubGridPen = pen;
  29082. }
  29083. void QCPPolarGrid::setRadialPen(const QPen &pen)
  29084. {
  29085. mRadialPen = pen;
  29086. }
  29087. void QCPPolarGrid::setRadialSubGridPen(const QPen &pen)
  29088. {
  29089. mRadialSubGridPen = pen;
  29090. }
  29091. void QCPPolarGrid::setRadialZeroLinePen(const QPen &pen)
  29092. {
  29093. mRadialZeroLinePen = pen;
  29094. }
  29095. /*! \internal
  29096. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  29097. before drawing the major grid lines.
  29098. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  29099. This function takes into account the local setting of the antialiasing flag as well as the
  29100. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  29101. QCustomPlot::setNotAntialiasedElements.
  29102. \see setAntialiased
  29103. */
  29104. void QCPPolarGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const
  29105. {
  29106. applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid);
  29107. }
  29108. /*! \internal
  29109. Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning
  29110. over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen).
  29111. */
  29112. void QCPPolarGrid::draw(QCPPainter *painter)
  29113. {
  29114. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  29115. const QPointF center = mParentAxis->mCenter;
  29116. const double radius = mParentAxis->mRadius;
  29117. painter->setBrush(Qt::NoBrush);
  29118. // draw main angular grid:
  29119. if (mType.testFlag(gtAngular))
  29120. drawAngularGrid(painter, center, radius, mParentAxis->mTickVectorCosSin, mAngularPen);
  29121. // draw main radial grid:
  29122. if (mType.testFlag(gtRadial) && mRadialAxis)
  29123. drawRadialGrid(painter, center, mRadialAxis->tickVector(), mRadialPen, mRadialZeroLinePen);
  29124. applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeGrid);
  29125. // draw sub angular grid:
  29126. if (mSubGridType.testFlag(gtAngular))
  29127. drawAngularGrid(painter, center, radius, mParentAxis->mSubTickVectorCosSin, mAngularSubGridPen);
  29128. // draw sub radial grid:
  29129. if (mSubGridType.testFlag(gtRadial) && mRadialAxis)
  29130. drawRadialGrid(painter, center, mRadialAxis->subTickVector(), mRadialSubGridPen);
  29131. }
  29132. void QCPPolarGrid::drawRadialGrid(QCPPainter *painter, const QPointF &center, const QVector<double> &coords, const QPen &pen, const QPen &zeroPen)
  29133. {
  29134. if (!mRadialAxis) return;
  29135. if (coords.isEmpty()) return;
  29136. const bool drawZeroLine = zeroPen != Qt::NoPen;
  29137. const double zeroLineEpsilon = qAbs(coords.last()-coords.first())*1e-6;
  29138. painter->setPen(pen);
  29139. for (int i=0; i<coords.size(); ++i)
  29140. {
  29141. const double r = mRadialAxis->coordToRadius(coords.at(i));
  29142. if (drawZeroLine && qAbs(coords.at(i)) < zeroLineEpsilon)
  29143. {
  29144. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  29145. painter->setPen(zeroPen);
  29146. painter->drawEllipse(center, r, r);
  29147. painter->setPen(pen);
  29148. applyDefaultAntialiasingHint(painter);
  29149. } else
  29150. {
  29151. painter->drawEllipse(center, r, r);
  29152. }
  29153. }
  29154. }
  29155. void QCPPolarGrid::drawAngularGrid(QCPPainter *painter, const QPointF &center, double radius, const QVector<QPointF> &ticksCosSin, const QPen &pen)
  29156. {
  29157. if (ticksCosSin.isEmpty()) return;
  29158. painter->setPen(pen);
  29159. for (int i=0; i<ticksCosSin.size(); ++i)
  29160. painter->drawLine(center, center+ticksCosSin.at(i)*radius);
  29161. }
  29162. /* end of 'src/polar/polargrid.cpp' */
  29163. /* including file 'src/polar/polargraph.cpp' */
  29164. /* modified 2022-11-06T12:45:57, size 44035 */
  29165. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29166. //////////////////// QCPPolarLegendItem
  29167. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29168. /*! \class QCPPolarLegendItem
  29169. \brief A legend item for polar plots
  29170. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  29171. functionality to be incomplete, as well as changing public interfaces in the future.
  29172. */
  29173. QCPPolarLegendItem::QCPPolarLegendItem(QCPLegend *parent, QCPPolarGraph *graph) :
  29174. QCPAbstractLegendItem(parent),
  29175. mPolarGraph(graph)
  29176. {
  29177. setAntialiased(false);
  29178. }
  29179. void QCPPolarLegendItem::draw(QCPPainter *painter)
  29180. {
  29181. if (!mPolarGraph) return;
  29182. painter->setFont(getFont());
  29183. painter->setPen(QPen(getTextColor()));
  29184. QSizeF iconSize = mParentLegend->iconSize();
  29185. QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPolarGraph->name());
  29186. QRectF iconRect(mRect.topLeft(), iconSize);
  29187. int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops
  29188. painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPolarGraph->name());
  29189. // draw icon:
  29190. painter->save();
  29191. painter->setClipRect(iconRect, Qt::IntersectClip);
  29192. mPolarGraph->drawLegendIcon(painter, iconRect);
  29193. painter->restore();
  29194. // draw icon border:
  29195. if (getIconBorderPen().style() != Qt::NoPen)
  29196. {
  29197. painter->setPen(getIconBorderPen());
  29198. painter->setBrush(Qt::NoBrush);
  29199. int halfPen = qCeil(painter->pen().widthF()*0.5)+1;
  29200. painter->setClipRect(mOuterRect.adjusted(-halfPen, -halfPen, halfPen, halfPen)); // extend default clip rect so thicker pens (especially during selection) are not clipped
  29201. painter->drawRect(iconRect);
  29202. }
  29203. }
  29204. QSize QCPPolarLegendItem::minimumOuterSizeHint() const
  29205. {
  29206. if (!mPolarGraph) return QSize();
  29207. QSize result(0, 0);
  29208. QRect textRect;
  29209. QFontMetrics fontMetrics(getFont());
  29210. QSize iconSize = mParentLegend->iconSize();
  29211. textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPolarGraph->name());
  29212. result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width());
  29213. result.setHeight(qMax(textRect.height(), iconSize.height()));
  29214. result.rwidth() += mMargins.left()+mMargins.right();
  29215. result.rheight() += mMargins.top()+mMargins.bottom();
  29216. return result;
  29217. }
  29218. QPen QCPPolarLegendItem::getIconBorderPen() const
  29219. {
  29220. return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen();
  29221. }
  29222. QColor QCPPolarLegendItem::getTextColor() const
  29223. {
  29224. return mSelected ? mSelectedTextColor : mTextColor;
  29225. }
  29226. QFont QCPPolarLegendItem::getFont() const
  29227. {
  29228. return mSelected ? mSelectedFont : mFont;
  29229. }
  29230. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29231. //////////////////// QCPPolarGraph
  29232. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29233. /*! \class QCPPolarGraph
  29234. \brief A radial graph used to display data in polar plots
  29235. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  29236. functionality to be incomplete, as well as changing public interfaces in the future.
  29237. */
  29238. /* start of documentation of inline functions */
  29239. // TODO
  29240. /* end of documentation of inline functions */
  29241. /*!
  29242. Constructs a graph which uses \a keyAxis as its angular and \a valueAxis as its radial axis. \a
  29243. keyAxis and \a valueAxis must reside in the same QCustomPlot, and the radial axis must be
  29244. associated with the angular axis. If either of these restrictions is violated, a corresponding
  29245. message is printed to the debug output (qDebug), the construction is not aborted, though.
  29246. The created QCPPolarGraph is automatically registered with the QCustomPlot instance inferred from
  29247. \a keyAxis. This QCustomPlot instance takes ownership of the QCPPolarGraph, so do not delete it
  29248. manually but use QCPPolarAxisAngular::removeGraph() instead.
  29249. To directly create a QCPPolarGraph inside a plot, you shoud use the QCPPolarAxisAngular::addGraph
  29250. method.
  29251. */
  29252. QCPPolarGraph::QCPPolarGraph(QCPPolarAxisAngular *keyAxis, QCPPolarAxisRadial *valueAxis) :
  29253. QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis),
  29254. mDataContainer(new QCPGraphDataContainer),
  29255. mName(),
  29256. mAntialiasedFill(true),
  29257. mAntialiasedScatters(true),
  29258. mPen(Qt::black),
  29259. mBrush(Qt::NoBrush),
  29260. mPeriodic(true),
  29261. mKeyAxis(keyAxis),
  29262. mValueAxis(valueAxis),
  29263. mSelectable(QCP::stWhole)
  29264. //mSelectionDecorator(0) // TODO
  29265. {
  29266. if (keyAxis->parentPlot() != valueAxis->parentPlot())
  29267. qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
  29268. mKeyAxis->registerPolarGraph(this);
  29269. //setSelectionDecorator(new QCPSelectionDecorator); // TODO
  29270. setPen(QPen(Qt::blue, 0));
  29271. setBrush(Qt::NoBrush);
  29272. setLineStyle(lsLine);
  29273. }
  29274. QCPPolarGraph::~QCPPolarGraph()
  29275. {
  29276. /* TODO
  29277. if (mSelectionDecorator)
  29278. {
  29279. delete mSelectionDecorator;
  29280. mSelectionDecorator = 0;
  29281. }
  29282. */
  29283. }
  29284. /*!
  29285. The name is the textual representation of this plottable as it is displayed in the legend
  29286. (\ref QCPLegend). It may contain any UTF-8 characters, including newlines.
  29287. */
  29288. void QCPPolarGraph::setName(const QString &name)
  29289. {
  29290. mName = name;
  29291. }
  29292. /*!
  29293. Sets whether fills of this plottable are drawn antialiased or not.
  29294. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  29295. QCustomPlot::setNotAntialiasedElements.
  29296. */
  29297. void QCPPolarGraph::setAntialiasedFill(bool enabled)
  29298. {
  29299. mAntialiasedFill = enabled;
  29300. }
  29301. /*!
  29302. Sets whether the scatter symbols of this plottable are drawn antialiased or not.
  29303. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  29304. QCustomPlot::setNotAntialiasedElements.
  29305. */
  29306. void QCPPolarGraph::setAntialiasedScatters(bool enabled)
  29307. {
  29308. mAntialiasedScatters = enabled;
  29309. }
  29310. /*!
  29311. The pen is used to draw basic lines that make up the plottable representation in the
  29312. plot.
  29313. For example, the \ref QCPGraph subclass draws its graph lines with this pen.
  29314. \see setBrush
  29315. */
  29316. void QCPPolarGraph::setPen(const QPen &pen)
  29317. {
  29318. mPen = pen;
  29319. }
  29320. /*!
  29321. The brush is used to draw basic fills of the plottable representation in the
  29322. plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
  29323. For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when
  29324. it's not set to Qt::NoBrush.
  29325. \see setPen
  29326. */
  29327. void QCPPolarGraph::setBrush(const QBrush &brush)
  29328. {
  29329. mBrush = brush;
  29330. }
  29331. void QCPPolarGraph::setPeriodic(bool enabled)
  29332. {
  29333. mPeriodic = enabled;
  29334. }
  29335. /*!
  29336. The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
  29337. to the plottable's value axis. This function performs no checks to make sure this is the case.
  29338. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
  29339. y-axis (QCustomPlot::yAxis) as value axis.
  29340. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  29341. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  29342. \see setValueAxis
  29343. */
  29344. void QCPPolarGraph::setKeyAxis(QCPPolarAxisAngular *axis)
  29345. {
  29346. mKeyAxis = axis;
  29347. }
  29348. /*!
  29349. The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is
  29350. orthogonal to the plottable's key axis. This function performs no checks to make sure this is the
  29351. case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and
  29352. the y-axis (QCustomPlot::yAxis) as value axis.
  29353. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  29354. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  29355. \see setKeyAxis
  29356. */
  29357. void QCPPolarGraph::setValueAxis(QCPPolarAxisRadial *axis)
  29358. {
  29359. mValueAxis = axis;
  29360. }
  29361. /*!
  29362. Sets whether and to which granularity this plottable can be selected.
  29363. A selection can happen by clicking on the QCustomPlot surface (When \ref
  29364. QCustomPlot::setInteractions contains \ref QCP::iSelectPlottables), by dragging a selection rect
  29365. (When \ref QCustomPlot::setSelectionRectMode is \ref QCP::srmSelect), or programmatically by
  29366. calling \ref setSelection.
  29367. \see setSelection, QCP::SelectionType
  29368. */
  29369. void QCPPolarGraph::setSelectable(QCP::SelectionType selectable)
  29370. {
  29371. if (mSelectable != selectable)
  29372. {
  29373. mSelectable = selectable;
  29374. QCPDataSelection oldSelection = mSelection;
  29375. mSelection.enforceType(mSelectable);
  29376. emit selectableChanged(mSelectable);
  29377. if (mSelection != oldSelection)
  29378. {
  29379. emit selectionChanged(selected());
  29380. emit selectionChanged(mSelection);
  29381. }
  29382. }
  29383. }
  29384. /*!
  29385. Sets which data ranges of this plottable are selected. Selected data ranges are drawn differently
  29386. (e.g. color) in the plot. This can be controlled via the selection decorator (see \ref
  29387. selectionDecorator).
  29388. The entire selection mechanism for plottables is handled automatically when \ref
  29389. QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
  29390. you wish to change the selection state programmatically.
  29391. Using \ref setSelectable you can further specify for each plottable whether and to which
  29392. granularity it is selectable. If \a selection is not compatible with the current \ref
  29393. QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted
  29394. accordingly (see \ref QCPDataSelection::enforceType).
  29395. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  29396. \see setSelectable, selectTest
  29397. */
  29398. void QCPPolarGraph::setSelection(QCPDataSelection selection)
  29399. {
  29400. selection.enforceType(mSelectable);
  29401. if (mSelection != selection)
  29402. {
  29403. mSelection = selection;
  29404. emit selectionChanged(selected());
  29405. emit selectionChanged(mSelection);
  29406. }
  29407. }
  29408. /*! \overload
  29409. Replaces the current data container with the provided \a data container.
  29410. Since a QSharedPointer is used, multiple QCPPolarGraphs may share the same data container safely.
  29411. Modifying the data in the container will then affect all graphs that share the container. Sharing
  29412. can be achieved by simply exchanging the data containers wrapped in shared pointers:
  29413. \snippet documentation/doc-code-snippets/mainwindow.cpp QCPPolarGraph-datasharing-1
  29414. If you do not wish to share containers, but create a copy from an existing container, rather use
  29415. the \ref QCPDataContainer<DataType>::set method on the graph's data container directly:
  29416. \snippet documentation/doc-code-snippets/mainwindow.cpp QCPPolarGraph-datasharing-2
  29417. \see addData
  29418. */
  29419. void QCPPolarGraph::setData(QSharedPointer<QCPGraphDataContainer> data)
  29420. {
  29421. mDataContainer = data;
  29422. }
  29423. /*! \overload
  29424. Replaces the current data with the provided points in \a keys and \a values. The provided
  29425. vectors should have equal length. Else, the number of added points will be the size of the
  29426. smallest vector.
  29427. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  29428. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  29429. \see addData
  29430. */
  29431. void QCPPolarGraph::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  29432. {
  29433. mDataContainer->clear();
  29434. addData(keys, values, alreadySorted);
  29435. }
  29436. /*!
  29437. Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
  29438. \ref lsNone and \ref setScatterStyle to the desired scatter style.
  29439. \see setScatterStyle
  29440. */
  29441. void QCPPolarGraph::setLineStyle(LineStyle ls)
  29442. {
  29443. mLineStyle = ls;
  29444. }
  29445. /*!
  29446. Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points
  29447. are drawn (e.g. for line-only-plots with appropriate line style).
  29448. \see QCPScatterStyle, setLineStyle
  29449. */
  29450. void QCPPolarGraph::setScatterStyle(const QCPScatterStyle &style)
  29451. {
  29452. mScatterStyle = style;
  29453. }
  29454. void QCPPolarGraph::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  29455. {
  29456. if (keys.size() != values.size())
  29457. qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
  29458. const int n = qMin(keys.size(), values.size());
  29459. QVector<QCPGraphData> tempData(n);
  29460. QVector<QCPGraphData>::iterator it = tempData.begin();
  29461. const QVector<QCPGraphData>::iterator itEnd = tempData.end();
  29462. int i = 0;
  29463. while (it != itEnd)
  29464. {
  29465. it->key = keys[i];
  29466. it->value = values[i];
  29467. ++it;
  29468. ++i;
  29469. }
  29470. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  29471. }
  29472. void QCPPolarGraph::addData(double key, double value)
  29473. {
  29474. mDataContainer->add(QCPGraphData(key, value));
  29475. }
  29476. /*!
  29477. Use this method to set an own QCPSelectionDecorator (subclass) instance. This allows you to
  29478. customize the visual representation of selected data ranges further than by using the default
  29479. QCPSelectionDecorator.
  29480. The plottable takes ownership of the \a decorator.
  29481. The currently set decorator can be accessed via \ref selectionDecorator.
  29482. */
  29483. /*
  29484. void QCPPolarGraph::setSelectionDecorator(QCPSelectionDecorator *decorator)
  29485. {
  29486. if (decorator)
  29487. {
  29488. if (decorator->registerWithPlottable(this))
  29489. {
  29490. if (mSelectionDecorator) // delete old decorator if necessary
  29491. delete mSelectionDecorator;
  29492. mSelectionDecorator = decorator;
  29493. }
  29494. } else if (mSelectionDecorator) // just clear decorator
  29495. {
  29496. delete mSelectionDecorator;
  29497. mSelectionDecorator = 0;
  29498. }
  29499. }
  29500. */
  29501. void QCPPolarGraph::coordsToPixels(double key, double value, double &x, double &y) const
  29502. {
  29503. if (mValueAxis)
  29504. {
  29505. const QPointF point = mValueAxis->coordToPixel(key, value);
  29506. x = point.x();
  29507. y = point.y();
  29508. } else
  29509. {
  29510. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  29511. }
  29512. }
  29513. const QPointF QCPPolarGraph::coordsToPixels(double key, double value) const
  29514. {
  29515. if (mValueAxis)
  29516. {
  29517. return mValueAxis->coordToPixel(key, value);
  29518. } else
  29519. {
  29520. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  29521. return QPointF();
  29522. }
  29523. }
  29524. void QCPPolarGraph::pixelsToCoords(double x, double y, double &key, double &value) const
  29525. {
  29526. if (mValueAxis)
  29527. {
  29528. mValueAxis->pixelToCoord(QPointF(x, y), key, value);
  29529. } else
  29530. {
  29531. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  29532. }
  29533. }
  29534. void QCPPolarGraph::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
  29535. {
  29536. if (mValueAxis)
  29537. {
  29538. mValueAxis->pixelToCoord(pixelPos, key, value);
  29539. } else
  29540. {
  29541. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  29542. }
  29543. }
  29544. void QCPPolarGraph::rescaleAxes(bool onlyEnlarge) const
  29545. {
  29546. rescaleKeyAxis(onlyEnlarge);
  29547. rescaleValueAxis(onlyEnlarge);
  29548. }
  29549. void QCPPolarGraph::rescaleKeyAxis(bool onlyEnlarge) const
  29550. {
  29551. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  29552. if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
  29553. bool foundRange;
  29554. QCPRange newRange = getKeyRange(foundRange, QCP::sdBoth);
  29555. if (foundRange)
  29556. {
  29557. if (onlyEnlarge)
  29558. newRange.expand(keyAxis->range());
  29559. 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
  29560. {
  29561. 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
  29562. newRange.lower = center-keyAxis->range().size()/2.0;
  29563. newRange.upper = center+keyAxis->range().size()/2.0;
  29564. }
  29565. keyAxis->setRange(newRange);
  29566. }
  29567. }
  29568. void QCPPolarGraph::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const
  29569. {
  29570. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  29571. QCPPolarAxisRadial *valueAxis = mValueAxis.data();
  29572. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  29573. QCP::SignDomain signDomain = QCP::sdBoth;
  29574. if (valueAxis->scaleType() == QCPPolarAxisRadial::stLogarithmic)
  29575. signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  29576. bool foundRange;
  29577. QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange());
  29578. if (foundRange)
  29579. {
  29580. if (onlyEnlarge)
  29581. newRange.expand(valueAxis->range());
  29582. 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
  29583. {
  29584. 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
  29585. if (valueAxis->scaleType() == QCPPolarAxisRadial::stLinear)
  29586. {
  29587. newRange.lower = center-valueAxis->range().size()/2.0;
  29588. newRange.upper = center+valueAxis->range().size()/2.0;
  29589. } else // scaleType() == stLogarithmic
  29590. {
  29591. newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  29592. newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  29593. }
  29594. }
  29595. valueAxis->setRange(newRange);
  29596. }
  29597. }
  29598. bool QCPPolarGraph::addToLegend(QCPLegend *legend)
  29599. {
  29600. if (!legend)
  29601. {
  29602. qDebug() << Q_FUNC_INFO << "passed legend is null";
  29603. return false;
  29604. }
  29605. if (legend->parentPlot() != mParentPlot)
  29606. {
  29607. qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable";
  29608. return false;
  29609. }
  29610. //if (!legend->hasItemWithPlottable(this)) // TODO
  29611. //{
  29612. legend->addItem(new QCPPolarLegendItem(legend, this));
  29613. return true;
  29614. //} else
  29615. // return false;
  29616. }
  29617. bool QCPPolarGraph::addToLegend()
  29618. {
  29619. if (!mParentPlot || !mParentPlot->legend)
  29620. return false;
  29621. else
  29622. return addToLegend(mParentPlot->legend);
  29623. }
  29624. bool QCPPolarGraph::removeFromLegend(QCPLegend *legend) const
  29625. {
  29626. if (!legend)
  29627. {
  29628. qDebug() << Q_FUNC_INFO << "passed legend is null";
  29629. return false;
  29630. }
  29631. QCPPolarLegendItem *removableItem = 0;
  29632. for (int i=0; i<legend->itemCount(); ++i) // TODO: reduce this to code in QCPAbstractPlottable::removeFromLegend once unified
  29633. {
  29634. if (QCPPolarLegendItem *pli = qobject_cast<QCPPolarLegendItem*>(legend->item(i)))
  29635. {
  29636. if (pli->polarGraph() == this)
  29637. {
  29638. removableItem = pli;
  29639. break;
  29640. }
  29641. }
  29642. }
  29643. if (removableItem)
  29644. return legend->removeItem(removableItem);
  29645. else
  29646. return false;
  29647. }
  29648. bool QCPPolarGraph::removeFromLegend() const
  29649. {
  29650. if (!mParentPlot || !mParentPlot->legend)
  29651. return false;
  29652. else
  29653. return removeFromLegend(mParentPlot->legend);
  29654. }
  29655. double QCPPolarGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  29656. {
  29657. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  29658. return -1;
  29659. if (!mKeyAxis || !mValueAxis)
  29660. return -1;
  29661. if (mKeyAxis->rect().contains(pos.toPoint()))
  29662. {
  29663. QCPGraphDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  29664. double result = pointDistance(pos, closestDataPoint);
  29665. if (details)
  29666. {
  29667. int pointIndex = closestDataPoint-mDataContainer->constBegin();
  29668. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  29669. }
  29670. return result;
  29671. } else
  29672. return -1;
  29673. }
  29674. /* inherits documentation from base class */
  29675. QCPRange QCPPolarGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  29676. {
  29677. return mDataContainer->keyRange(foundRange, inSignDomain);
  29678. }
  29679. /* inherits documentation from base class */
  29680. QCPRange QCPPolarGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  29681. {
  29682. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  29683. }
  29684. /* inherits documentation from base class */
  29685. QRect QCPPolarGraph::clipRect() const
  29686. {
  29687. if (mKeyAxis)
  29688. return mKeyAxis.data()->rect();
  29689. else
  29690. return QRect();
  29691. }
  29692. void QCPPolarGraph::draw(QCPPainter *painter)
  29693. {
  29694. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  29695. if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
  29696. if (mLineStyle == lsNone && mScatterStyle.isNone()) return;
  29697. painter->setClipRegion(mKeyAxis->exactClipRegion());
  29698. QVector<QPointF> lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments
  29699. // loop over and draw segments of unselected/selected data:
  29700. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  29701. getDataSegments(selectedSegments, unselectedSegments);
  29702. allSegments << unselectedSegments << selectedSegments;
  29703. for (int i=0; i<allSegments.size(); ++i)
  29704. {
  29705. bool isSelectedSegment = i >= unselectedSegments.size();
  29706. // get line pixel points appropriate to line style:
  29707. 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)
  29708. getLines(&lines, lineDataRange);
  29709. // check data validity if flag set:
  29710. #ifdef QCUSTOMPLOT_CHECK_DATA
  29711. QCPGraphDataContainer::const_iterator it;
  29712. for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  29713. {
  29714. if (QCP::isInvalidData(it->key, it->value))
  29715. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
  29716. }
  29717. #endif
  29718. // draw fill of graph:
  29719. //if (isSelectedSegment && mSelectionDecorator)
  29720. // mSelectionDecorator->applyBrush(painter);
  29721. //else
  29722. painter->setBrush(mBrush);
  29723. painter->setPen(Qt::NoPen);
  29724. drawFill(painter, &lines);
  29725. // draw line:
  29726. if (mLineStyle != lsNone)
  29727. {
  29728. //if (isSelectedSegment && mSelectionDecorator)
  29729. // mSelectionDecorator->applyPen(painter);
  29730. //else
  29731. painter->setPen(mPen);
  29732. painter->setBrush(Qt::NoBrush);
  29733. drawLinePlot(painter, lines);
  29734. }
  29735. // draw scatters:
  29736. QCPScatterStyle finalScatterStyle = mScatterStyle;
  29737. //if (isSelectedSegment && mSelectionDecorator)
  29738. // finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
  29739. if (!finalScatterStyle.isNone())
  29740. {
  29741. getScatters(&scatters, allSegments.at(i));
  29742. drawScatterPlot(painter, scatters, finalScatterStyle);
  29743. }
  29744. }
  29745. // draw other selection decoration that isn't just line/scatter pens and brushes:
  29746. //if (mSelectionDecorator)
  29747. // mSelectionDecorator->drawDecoration(painter, selection());
  29748. }
  29749. QCP::Interaction QCPPolarGraph::selectionCategory() const
  29750. {
  29751. return QCP::iSelectPlottables;
  29752. }
  29753. void QCPPolarGraph::applyDefaultAntialiasingHint(QCPPainter *painter) const
  29754. {
  29755. applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables);
  29756. }
  29757. /* inherits documentation from base class */
  29758. void QCPPolarGraph::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  29759. {
  29760. Q_UNUSED(event)
  29761. if (mSelectable != QCP::stNone)
  29762. {
  29763. QCPDataSelection newSelection = details.value<QCPDataSelection>();
  29764. QCPDataSelection selectionBefore = mSelection;
  29765. if (additive)
  29766. {
  29767. if (mSelectable == QCP::stWhole) // in whole selection mode, we toggle to no selection even if currently unselected point was hit
  29768. {
  29769. if (selected())
  29770. setSelection(QCPDataSelection());
  29771. else
  29772. setSelection(newSelection);
  29773. } else // in all other selection modes we toggle selections of homogeneously selected/unselected segments
  29774. {
  29775. if (mSelection.contains(newSelection)) // if entire newSelection is already selected, toggle selection
  29776. setSelection(mSelection-newSelection);
  29777. else
  29778. setSelection(mSelection+newSelection);
  29779. }
  29780. } else
  29781. setSelection(newSelection);
  29782. if (selectionStateChanged)
  29783. *selectionStateChanged = mSelection != selectionBefore;
  29784. }
  29785. }
  29786. /* inherits documentation from base class */
  29787. void QCPPolarGraph::deselectEvent(bool *selectionStateChanged)
  29788. {
  29789. if (mSelectable != QCP::stNone)
  29790. {
  29791. QCPDataSelection selectionBefore = mSelection;
  29792. setSelection(QCPDataSelection());
  29793. if (selectionStateChanged)
  29794. *selectionStateChanged = mSelection != selectionBefore;
  29795. }
  29796. }
  29797. /*! \internal
  29798. Draws lines between the points in \a lines, given in pixel coordinates.
  29799. \see drawScatterPlot, drawImpulsePlot, QCPAbstractPlottable1D::drawPolyline
  29800. */
  29801. void QCPPolarGraph::drawLinePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
  29802. {
  29803. if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
  29804. {
  29805. applyDefaultAntialiasingHint(painter);
  29806. drawPolyline(painter, lines);
  29807. }
  29808. }
  29809. /*! \internal
  29810. Draws the fill of the graph using the specified \a painter, with the currently set brush.
  29811. Depending on whether a normal fill or a channel fill (\ref setChannelFillGraph) is needed, \ref
  29812. getFillPolygon or \ref getChannelFillPolygon are used to find the according fill polygons.
  29813. In order to handle NaN Data points correctly (the fill needs to be split into disjoint areas),
  29814. this method first determines a list of non-NaN segments with \ref getNonNanSegments, on which to
  29815. operate. In the channel fill case, \ref getOverlappingSegments is used to consolidate the non-NaN
  29816. segments of the two involved graphs, before passing the overlapping pairs to \ref
  29817. getChannelFillPolygon.
  29818. Pass the points of this graph's line as \a lines, in pixel coordinates.
  29819. \see drawLinePlot, drawImpulsePlot, drawScatterPlot
  29820. */
  29821. void QCPPolarGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lines) const
  29822. {
  29823. applyFillAntialiasingHint(painter);
  29824. if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0)
  29825. painter->drawPolygon(QPolygonF(*lines));
  29826. }
  29827. /*! \internal
  29828. Draws scatter symbols at every point passed in \a scatters, given in pixel coordinates. The
  29829. scatters will be drawn with \a painter and have the appearance as specified in \a style.
  29830. \see drawLinePlot, drawImpulsePlot
  29831. */
  29832. void QCPPolarGraph::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &scatters, const QCPScatterStyle &style) const
  29833. {
  29834. applyScattersAntialiasingHint(painter);
  29835. style.applyTo(painter, mPen);
  29836. for (int i=0; i<scatters.size(); ++i)
  29837. style.drawShape(painter, scatters.at(i).x(), scatters.at(i).y());
  29838. }
  29839. void QCPPolarGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  29840. {
  29841. // draw fill:
  29842. if (mBrush.style() != Qt::NoBrush)
  29843. {
  29844. applyFillAntialiasingHint(painter);
  29845. painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
  29846. }
  29847. // draw line vertically centered:
  29848. if (mLineStyle != lsNone)
  29849. {
  29850. applyDefaultAntialiasingHint(painter);
  29851. painter->setPen(mPen);
  29852. 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
  29853. }
  29854. // draw scatter symbol:
  29855. if (!mScatterStyle.isNone())
  29856. {
  29857. applyScattersAntialiasingHint(painter);
  29858. // scale scatter pixmap if it's too large to fit in legend icon rect:
  29859. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
  29860. {
  29861. QCPScatterStyle scaledStyle(mScatterStyle);
  29862. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  29863. scaledStyle.applyTo(painter, mPen);
  29864. scaledStyle.drawShape(painter, QRectF(rect).center());
  29865. } else
  29866. {
  29867. mScatterStyle.applyTo(painter, mPen);
  29868. mScatterStyle.drawShape(painter, QRectF(rect).center());
  29869. }
  29870. }
  29871. }
  29872. void QCPPolarGraph::applyFillAntialiasingHint(QCPPainter *painter) const
  29873. {
  29874. applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills);
  29875. }
  29876. void QCPPolarGraph::applyScattersAntialiasingHint(QCPPainter *painter) const
  29877. {
  29878. applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
  29879. }
  29880. double QCPPolarGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const
  29881. {
  29882. closestData = mDataContainer->constEnd();
  29883. if (mDataContainer->isEmpty())
  29884. return -1.0;
  29885. if (mLineStyle == lsNone && mScatterStyle.isNone())
  29886. return -1.0;
  29887. // calculate minimum distances to graph data points and find closestData iterator:
  29888. double minDistSqr = (std::numeric_limits<double>::max)();
  29889. // determine which key range comes into question, taking selection tolerance around pos into account:
  29890. double posKeyMin, posKeyMax, dummy;
  29891. pixelsToCoords(pixelPoint-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy);
  29892. pixelsToCoords(pixelPoint+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy);
  29893. if (posKeyMin > posKeyMax)
  29894. qSwap(posKeyMin, posKeyMax);
  29895. // iterate over found data points and then choose the one with the shortest distance to pos:
  29896. QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true);
  29897. QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true);
  29898. for (QCPGraphDataContainer::const_iterator it=begin; it!=end; ++it)
  29899. {
  29900. const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
  29901. if (currentDistSqr < minDistSqr)
  29902. {
  29903. minDistSqr = currentDistSqr;
  29904. closestData = it;
  29905. }
  29906. }
  29907. // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point):
  29908. if (mLineStyle != lsNone)
  29909. {
  29910. // line displayed, calculate distance to line segments:
  29911. QVector<QPointF> lineData;
  29912. getLines(&lineData, QCPDataRange(0, dataCount()));
  29913. QCPVector2D p(pixelPoint);
  29914. for (int i=0; i<lineData.size()-1; ++i)
  29915. {
  29916. const double currentDistSqr = p.distanceSquaredToLine(lineData.at(i), lineData.at(i+1));
  29917. if (currentDistSqr < minDistSqr)
  29918. minDistSqr = currentDistSqr;
  29919. }
  29920. }
  29921. return qSqrt(minDistSqr);
  29922. }
  29923. int QCPPolarGraph::dataCount() const
  29924. {
  29925. return mDataContainer->size();
  29926. }
  29927. void QCPPolarGraph::getDataSegments(QList<QCPDataRange> &selectedSegments, QList<QCPDataRange> &unselectedSegments) const
  29928. {
  29929. selectedSegments.clear();
  29930. unselectedSegments.clear();
  29931. if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty
  29932. {
  29933. if (selected())
  29934. selectedSegments << QCPDataRange(0, dataCount());
  29935. else
  29936. unselectedSegments << QCPDataRange(0, dataCount());
  29937. } else
  29938. {
  29939. QCPDataSelection sel(selection());
  29940. sel.simplify();
  29941. selectedSegments = sel.dataRanges();
  29942. unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges();
  29943. }
  29944. }
  29945. void QCPPolarGraph::drawPolyline(QCPPainter *painter, const QVector<QPointF> &lineData) const
  29946. {
  29947. // if drawing solid line and not in PDF, use much faster line drawing instead of polyline:
  29948. if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) &&
  29949. painter->pen().style() == Qt::SolidLine &&
  29950. !painter->modes().testFlag(QCPPainter::pmVectorized) &&
  29951. !painter->modes().testFlag(QCPPainter::pmNoCaching))
  29952. {
  29953. int i = 0;
  29954. bool lastIsNan = false;
  29955. const int lineDataSize = lineData.size();
  29956. while (i < lineDataSize && (qIsNaN(lineData.at(i).y()) || qIsNaN(lineData.at(i).x()))) // make sure first point is not NaN
  29957. ++i;
  29958. ++i; // because drawing works in 1 point retrospect
  29959. while (i < lineDataSize)
  29960. {
  29961. if (!qIsNaN(lineData.at(i).y()) && !qIsNaN(lineData.at(i).x())) // NaNs create a gap in the line
  29962. {
  29963. if (!lastIsNan)
  29964. painter->drawLine(lineData.at(i-1), lineData.at(i));
  29965. else
  29966. lastIsNan = false;
  29967. } else
  29968. lastIsNan = true;
  29969. ++i;
  29970. }
  29971. } else
  29972. {
  29973. int segmentStart = 0;
  29974. int i = 0;
  29975. const int lineDataSize = lineData.size();
  29976. while (i < lineDataSize)
  29977. {
  29978. 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
  29979. {
  29980. painter->drawPolyline(lineData.constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point
  29981. segmentStart = i+1;
  29982. }
  29983. ++i;
  29984. }
  29985. // draw last segment:
  29986. painter->drawPolyline(lineData.constData()+segmentStart, lineDataSize-segmentStart);
  29987. }
  29988. }
  29989. void QCPPolarGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
  29990. {
  29991. if (rangeRestriction.isEmpty())
  29992. {
  29993. end = mDataContainer->constEnd();
  29994. begin = end;
  29995. } else
  29996. {
  29997. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  29998. QCPPolarAxisRadial *valueAxis = mValueAxis.data();
  29999. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  30000. // get visible data range:
  30001. if (mPeriodic)
  30002. {
  30003. begin = mDataContainer->constBegin();
  30004. end = mDataContainer->constEnd();
  30005. } else
  30006. {
  30007. begin = mDataContainer->findBegin(keyAxis->range().lower);
  30008. end = mDataContainer->findEnd(keyAxis->range().upper);
  30009. }
  30010. // limit lower/upperEnd to rangeRestriction:
  30011. mDataContainer->limitIteratorsToDataRange(begin, end, rangeRestriction); // this also ensures rangeRestriction outside data bounds doesn't break anything
  30012. }
  30013. }
  30014. /*! \internal
  30015. This method retrieves an optimized set of data points via \ref getOptimizedLineData, an branches
  30016. out to the line style specific functions such as \ref dataToLines, \ref dataToStepLeftLines, etc.
  30017. according to the line style of the graph.
  30018. \a lines will be filled with points in pixel coordinates, that can be drawn with the according
  30019. draw functions like \ref drawLinePlot and \ref drawImpulsePlot. The points returned in \a lines
  30020. aren't necessarily the original data points. For example, step line styles require additional
  30021. points to form the steps when drawn. If the line style of the graph is \ref lsNone, the \a
  30022. lines vector will be empty.
  30023. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  30024. conversion. In this function, the specified range may exceed the total data bounds without harm:
  30025. a correspondingly trimmed data range will be used. This takes the burden off the user of this
  30026. function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
  30027. getDataSegments.
  30028. \see getScatters
  30029. */
  30030. void QCPPolarGraph::getLines(QVector<QPointF> *lines, const QCPDataRange &dataRange) const
  30031. {
  30032. if (!lines) return;
  30033. QCPGraphDataContainer::const_iterator begin, end;
  30034. getVisibleDataBounds(begin, end, dataRange);
  30035. if (begin == end)
  30036. {
  30037. lines->clear();
  30038. return;
  30039. }
  30040. QVector<QCPGraphData> lineData;
  30041. if (mLineStyle != lsNone)
  30042. getOptimizedLineData(&lineData, begin, end);
  30043. switch (mLineStyle)
  30044. {
  30045. case lsNone: lines->clear(); break;
  30046. case lsLine: *lines = dataToLines(lineData); break;
  30047. }
  30048. }
  30049. void QCPPolarGraph::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange) const
  30050. {
  30051. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  30052. QCPPolarAxisRadial *valueAxis = mValueAxis.data();
  30053. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  30054. if (!scatters) return;
  30055. QCPGraphDataContainer::const_iterator begin, end;
  30056. getVisibleDataBounds(begin, end, dataRange);
  30057. if (begin == end)
  30058. {
  30059. scatters->clear();
  30060. return;
  30061. }
  30062. QVector<QCPGraphData> data;
  30063. getOptimizedScatterData(&data, begin, end);
  30064. scatters->resize(data.size());
  30065. for (int i=0; i<data.size(); ++i)
  30066. {
  30067. if (!qIsNaN(data.at(i).value))
  30068. (*scatters)[i] = valueAxis->coordToPixel(data.at(i).key, data.at(i).value);
  30069. }
  30070. }
  30071. void QCPPolarGraph::getOptimizedLineData(QVector<QCPGraphData> *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const
  30072. {
  30073. lineData->clear();
  30074. // TODO: fix for log axes and thick line style
  30075. const QCPRange range = mValueAxis->range();
  30076. bool reversed = mValueAxis->rangeReversed();
  30077. 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
  30078. 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
  30079. 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
  30080. 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)
  30081. double skipBegin = 0;
  30082. bool belowRange = false;
  30083. bool aboveRange = false;
  30084. QCPGraphDataContainer::const_iterator it = begin;
  30085. while (it != end)
  30086. {
  30087. if (it->value < lowerClipValue)
  30088. {
  30089. if (aboveRange) // jumped directly from above to below visible range, draw previous point so entry angle is correct
  30090. {
  30091. aboveRange = false;
  30092. if (!reversed) // TODO: with inner radius, we'll need else case here with projected border point
  30093. lineData->append(*(it-1));
  30094. }
  30095. if (!belowRange)
  30096. {
  30097. skipBegin = it->key;
  30098. lineData->append(QCPGraphData(it->key, lowerClipValue));
  30099. belowRange = true;
  30100. }
  30101. if (it->key-skipBegin > maxKeySkip) // add dummy point if we're exceeding the maximum skippable angle (to prevent unintentional intersections with visible circle)
  30102. {
  30103. skipBegin += maxKeySkip;
  30104. lineData->append(QCPGraphData(skipBegin, lowerClipValue));
  30105. }
  30106. } else if (it->value > upperClipValue)
  30107. {
  30108. 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)
  30109. {
  30110. belowRange = false;
  30111. if (reversed)
  30112. lineData->append(*(it-1));
  30113. }
  30114. if (!aboveRange)
  30115. {
  30116. skipBegin = it->key;
  30117. lineData->append(QCPGraphData(it->key, upperClipValue));
  30118. aboveRange = true;
  30119. }
  30120. if (it->key-skipBegin > maxKeySkip) // add dummy point if we're exceeding the maximum skippable angle (to prevent unintentional intersections with visible circle)
  30121. {
  30122. skipBegin += maxKeySkip;
  30123. lineData->append(QCPGraphData(skipBegin, upperClipValue));
  30124. }
  30125. } else // value within bounds where we don't optimize away points
  30126. {
  30127. if (aboveRange)
  30128. {
  30129. aboveRange = false;
  30130. if (!reversed)
  30131. 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)
  30132. }
  30133. if (belowRange)
  30134. {
  30135. belowRange = false;
  30136. if (reversed)
  30137. lineData->append(*(it-1)); // just entered from below, draw previous point so entry angle is correct (if below means outer, so if reversed axis)
  30138. }
  30139. lineData->append(*it); // inside visible circle, add point normally
  30140. }
  30141. ++it;
  30142. }
  30143. // to make fill not erratic, add last point normally if it was outside visible circle:
  30144. if (aboveRange)
  30145. {
  30146. aboveRange = false;
  30147. if (!reversed)
  30148. 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)
  30149. }
  30150. if (belowRange)
  30151. {
  30152. belowRange = false;
  30153. if (reversed)
  30154. lineData->append(*(it-1)); // just entered from below, draw previous point so entry angle is correct (if below means outer, so if reversed axis)
  30155. }
  30156. }
  30157. void QCPPolarGraph::getOptimizedScatterData(QVector<QCPGraphData> *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const
  30158. {
  30159. scatterData->clear();
  30160. const QCPRange range = mValueAxis->range();
  30161. bool reversed = mValueAxis->rangeReversed();
  30162. const double clipMargin = range.size()*0.05;
  30163. const double upperClipValue = range.upper + (reversed ? 0 : clipMargin); // clip slightly outside of actual range to avoid scatter size to peek into visible circle
  30164. const double lowerClipValue = range.lower - (reversed ? clipMargin : 0); // clip slightly outside of actual range to avoid scatter size to peek into visible circle
  30165. QCPGraphDataContainer::const_iterator it = begin;
  30166. while (it != end)
  30167. {
  30168. if (it->value > lowerClipValue && it->value < upperClipValue)
  30169. scatterData->append(*it);
  30170. ++it;
  30171. }
  30172. }
  30173. /*! \internal
  30174. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  30175. coordinate points which are suitable for drawing the line style \ref lsLine.
  30176. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  30177. getLines if the line style is set accordingly.
  30178. \see dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
  30179. */
  30180. QVector<QPointF> QCPPolarGraph::dataToLines(const QVector<QCPGraphData> &data) const
  30181. {
  30182. QVector<QPointF> result;
  30183. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  30184. QCPPolarAxisRadial *valueAxis = mValueAxis.data();
  30185. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  30186. // transform data points to pixels:
  30187. result.resize(data.size());
  30188. for (int i=0; i<data.size(); ++i)
  30189. result[i] = mValueAxis->coordToPixel(data.at(i).key, data.at(i).value);
  30190. return result;
  30191. }
  30192. /* end of 'src/polar/polargraph.cpp' */