qcustomplot.cpp 1.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517
  1. /***************************************************************************
  2. ** **
  3. ** QCustomPlot, an easy to use, modern plotting widget for Qt **
  4. ** Copyright (C) 2011-2021 Emanuel Eichhammer **
  5. ** **
  6. ** This program is free software: you can redistribute it and/or modify **
  7. ** it under the terms of the GNU General Public License as published by **
  8. ** the Free Software Foundation, either version 3 of the License, or **
  9. ** (at your option) any later version. **
  10. ** **
  11. ** This program is distributed in the hope that it will be useful, **
  12. ** but WITHOUT ANY WARRANTY; without even the implied warranty of **
  13. ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the **
  14. ** GNU General Public License for more details. **
  15. ** **
  16. ** You should have received a copy of the GNU General Public License **
  17. ** along with this program. If not, see http://www.gnu.org/licenses/. **
  18. ** **
  19. ****************************************************************************
  20. ** Author: Emanuel Eichhammer **
  21. ** Website/Contact: http://www.qcustomplot.com/ **
  22. ** Date: 29.03.21 **
  23. ** Version: 2.1.0 **
  24. ****************************************************************************/
  25. #include "qcustomplot.h"
  26. /* including file 'src/vector2d.cpp' */
  27. /* modified 2021-03-29T02:30:44, size 7973 */
  28. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29. //////////////////// QCPVector2D
  30. ////////////////////////////////////////////////////////////////////////////////////////////////////
  31. /*! \class QCPVector2D
  32. \brief Represents two doubles as a mathematical 2D vector
  33. This class acts as a replacement for QVector2D with the advantage of double precision instead of
  34. single, and some convenience methods tailored for the QCustomPlot library.
  35. */
  36. /* start documentation of inline functions */
  37. /*! \fn void QCPVector2D::setX(double x)
  38. Sets the x coordinate of this vector to \a x.
  39. \see setY
  40. */
  41. /*! \fn void QCPVector2D::setY(double y)
  42. Sets the y coordinate of this vector to \a y.
  43. \see setX
  44. */
  45. /*! \fn double QCPVector2D::length() const
  46. Returns the length of this vector.
  47. \see lengthSquared
  48. */
  49. /*! \fn double QCPVector2D::lengthSquared() const
  50. Returns the squared length of this vector. In some situations, e.g. when just trying to find the
  51. shortest vector of a group, this is faster than calculating \ref length, because it avoids
  52. calculation of a square root.
  53. \see length
  54. */
  55. /*! \fn double QCPVector2D::angle() const
  56. Returns the angle of the vector in radians. The angle is measured between the positive x line and
  57. the vector, counter-clockwise in a mathematical coordinate system (y axis upwards positive). In
  58. screen/widget coordinates where the y axis is inverted, the angle appears clockwise.
  59. */
  60. /*! \fn QPoint QCPVector2D::toPoint() const
  61. Returns a QPoint which has the x and y coordinates of this vector, truncating any floating point
  62. information.
  63. \see toPointF
  64. */
  65. /*! \fn QPointF QCPVector2D::toPointF() const
  66. Returns a QPointF which has the x and y coordinates of this vector.
  67. \see toPoint
  68. */
  69. /*! \fn bool QCPVector2D::isNull() const
  70. Returns whether this vector is null. A vector is null if \c qIsNull returns true for both x and y
  71. coordinates, i.e. if both are binary equal to 0.
  72. */
  73. /*! \fn QCPVector2D QCPVector2D::perpendicular() const
  74. Returns a vector perpendicular to this vector, with the same length.
  75. */
  76. /*! \fn double QCPVector2D::dot() const
  77. Returns the dot/scalar product of this vector with the specified vector \a vec.
  78. */
  79. /* end documentation of inline functions */
  80. /*!
  81. Creates a QCPVector2D object and initializes the x and y coordinates to 0.
  82. */
  83. QCPVector2D::QCPVector2D() :
  84. mX(0),
  85. mY(0)
  86. {
  87. }
  88. /*!
  89. Creates a QCPVector2D object and initializes the \a x and \a y coordinates with the specified
  90. values.
  91. */
  92. QCPVector2D::QCPVector2D(double x, double y) :
  93. mX(x),
  94. mY(y)
  95. {
  96. }
  97. /*!
  98. Creates a QCPVector2D object and initializes the x and y coordinates respective coordinates of
  99. the specified \a point.
  100. */
  101. QCPVector2D::QCPVector2D(const QPoint &point) :
  102. mX(point.x()),
  103. mY(point.y())
  104. {
  105. }
  106. /*!
  107. Creates a QCPVector2D object and initializes the x and y coordinates respective coordinates of
  108. the specified \a point.
  109. */
  110. QCPVector2D::QCPVector2D(const QPointF &point) :
  111. mX(point.x()),
  112. mY(point.y())
  113. {
  114. }
  115. /*!
  116. Normalizes this vector. After this operation, the length of the vector is equal to 1.
  117. If the vector has both entries set to zero, this method does nothing.
  118. \see normalized, length, lengthSquared
  119. */
  120. void QCPVector2D::normalize()
  121. {
  122. if (mX == 0.0 && mY == 0.0) return;
  123. const double lenInv = 1.0/length();
  124. mX *= lenInv;
  125. mY *= lenInv;
  126. }
  127. /*!
  128. Returns a normalized version of this vector. The length of the returned vector is equal to 1.
  129. If the vector has both entries set to zero, this method returns the vector unmodified.
  130. \see normalize, length, lengthSquared
  131. */
  132. QCPVector2D QCPVector2D::normalized() const
  133. {
  134. if (mX == 0.0 && mY == 0.0) return *this;
  135. const double lenInv = 1.0/length();
  136. return QCPVector2D(mX*lenInv, mY*lenInv);
  137. }
  138. /*! \overload
  139. Returns the squared shortest distance of this vector (interpreted as a point) to the finite line
  140. segment given by \a start and \a end.
  141. \see distanceToStraightLine
  142. */
  143. double QCPVector2D::distanceSquaredToLine(const QCPVector2D &start, const QCPVector2D &end) const
  144. {
  145. const QCPVector2D v(end-start);
  146. const double vLengthSqr = v.lengthSquared();
  147. if (!qFuzzyIsNull(vLengthSqr))
  148. {
  149. const double mu = v.dot(*this-start)/vLengthSqr;
  150. if (mu < 0)
  151. return (*this-start).lengthSquared();
  152. else if (mu > 1)
  153. return (*this-end).lengthSquared();
  154. else
  155. return ((start + mu*v)-*this).lengthSquared();
  156. } else
  157. return (*this-start).lengthSquared();
  158. }
  159. /*! \overload
  160. Returns the squared shortest distance of this vector (interpreted as a point) to the finite line
  161. segment given by \a line.
  162. \see distanceToStraightLine
  163. */
  164. double QCPVector2D::distanceSquaredToLine(const QLineF &line) const
  165. {
  166. return distanceSquaredToLine(QCPVector2D(line.p1()), QCPVector2D(line.p2()));
  167. }
  168. /*!
  169. Returns the shortest distance of this vector (interpreted as a point) to the infinite straight
  170. line given by a \a base point and a \a direction vector.
  171. \see distanceSquaredToLine
  172. */
  173. double QCPVector2D::distanceToStraightLine(const QCPVector2D &base, const QCPVector2D &direction) const
  174. {
  175. return qAbs((*this-base).dot(direction.perpendicular()))/direction.length();
  176. }
  177. /*!
  178. Scales this vector by the given \a factor, i.e. the x and y components are multiplied by \a
  179. factor.
  180. */
  181. QCPVector2D &QCPVector2D::operator*=(double factor)
  182. {
  183. mX *= factor;
  184. mY *= factor;
  185. return *this;
  186. }
  187. /*!
  188. Scales this vector by the given \a divisor, i.e. the x and y components are divided by \a
  189. divisor.
  190. */
  191. QCPVector2D &QCPVector2D::operator/=(double divisor)
  192. {
  193. mX /= divisor;
  194. mY /= divisor;
  195. return *this;
  196. }
  197. /*!
  198. Adds the given \a vector to this vector component-wise.
  199. */
  200. QCPVector2D &QCPVector2D::operator+=(const QCPVector2D &vector)
  201. {
  202. mX += vector.mX;
  203. mY += vector.mY;
  204. return *this;
  205. }
  206. /*!
  207. subtracts the given \a vector from this vector component-wise.
  208. */
  209. QCPVector2D &QCPVector2D::operator-=(const QCPVector2D &vector)
  210. {
  211. mX -= vector.mX;
  212. mY -= vector.mY;
  213. return *this;
  214. }
  215. /* end of 'src/vector2d.cpp' */
  216. /* including file 'src/painter.cpp' */
  217. /* modified 2021-03-29T02:30:44, size 8656 */
  218. ////////////////////////////////////////////////////////////////////////////////////////////////////
  219. //////////////////// QCPPainter
  220. ////////////////////////////////////////////////////////////////////////////////////////////////////
  221. /*! \class QCPPainter
  222. \brief QPainter subclass used internally
  223. This QPainter subclass is used to provide some extended functionality e.g. for tweaking position
  224. consistency between antialiased and non-antialiased painting. Further it provides workarounds
  225. for QPainter quirks.
  226. \warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and
  227. restore. So while it is possible to pass a QCPPainter instance to a function that expects a
  228. QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because
  229. it will call the base class implementations of the functions actually hidden by QCPPainter).
  230. */
  231. /*!
  232. Creates a new QCPPainter instance and sets default values
  233. */
  234. QCPPainter::QCPPainter() :
  235. mModes(pmDefault),
  236. mIsAntialiasing(false)
  237. {
  238. // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and
  239. // a call to begin() will follow
  240. }
  241. /*!
  242. Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just
  243. like the analogous QPainter constructor, begins painting on \a device immediately.
  244. Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5.
  245. */
  246. QCPPainter::QCPPainter(QPaintDevice *device) :
  247. QPainter(device),
  248. mModes(pmDefault),
  249. mIsAntialiasing(false)
  250. {
  251. #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions.
  252. if (isActive())
  253. setRenderHint(QPainter::NonCosmeticDefaultPen);
  254. #endif
  255. }
  256. /*!
  257. Sets the pen of the painter and applies certain fixes to it, depending on the mode of this
  258. QCPPainter.
  259. \note this function hides the non-virtual base class implementation.
  260. */
  261. void QCPPainter::setPen(const QPen &pen)
  262. {
  263. QPainter::setPen(pen);
  264. if (mModes.testFlag(pmNonCosmetic))
  265. makeNonCosmetic();
  266. }
  267. /*! \overload
  268. Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of
  269. this QCPPainter.
  270. \note this function hides the non-virtual base class implementation.
  271. */
  272. void QCPPainter::setPen(const QColor &color)
  273. {
  274. QPainter::setPen(color);
  275. if (mModes.testFlag(pmNonCosmetic))
  276. makeNonCosmetic();
  277. }
  278. /*! \overload
  279. Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of
  280. this QCPPainter.
  281. \note this function hides the non-virtual base class implementation.
  282. */
  283. void QCPPainter::setPen(Qt::PenStyle penStyle)
  284. {
  285. QPainter::setPen(penStyle);
  286. if (mModes.testFlag(pmNonCosmetic))
  287. makeNonCosmetic();
  288. }
  289. /*! \overload
  290. Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when
  291. antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to
  292. integer coordinates and then passes it to the original drawLine.
  293. \note this function hides the non-virtual base class implementation.
  294. */
  295. void QCPPainter::drawLine(const QLineF &line)
  296. {
  297. if (mIsAntialiasing || mModes.testFlag(pmVectorized))
  298. QPainter::drawLine(line);
  299. else
  300. QPainter::drawLine(line.toLine());
  301. }
  302. /*!
  303. Sets whether painting uses antialiasing or not. Use this method instead of using setRenderHint
  304. with QPainter::Antialiasing directly, as it allows QCPPainter to regain pixel exactness between
  305. antialiased and non-antialiased painting (Since Qt < 5.0 uses slightly different coordinate systems for
  306. AA/Non-AA painting).
  307. */
  308. void QCPPainter::setAntialiasing(bool enabled)
  309. {
  310. setRenderHint(QPainter::Antialiasing, enabled);
  311. if (mIsAntialiasing != enabled)
  312. {
  313. mIsAntialiasing = enabled;
  314. if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs
  315. {
  316. if (mIsAntialiasing)
  317. translate(0.5, 0.5);
  318. else
  319. translate(-0.5, -0.5);
  320. }
  321. }
  322. }
  323. /*!
  324. Sets the mode of the painter. This controls whether the painter shall adjust its
  325. fixes/workarounds optimized for certain output devices.
  326. */
  327. void QCPPainter::setModes(QCPPainter::PainterModes modes)
  328. {
  329. mModes = modes;
  330. }
  331. /*!
  332. Sets the QPainter::NonCosmeticDefaultPen in Qt versions before Qt5 after beginning painting on \a
  333. device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5,
  334. all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that
  335. behaviour.
  336. The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets
  337. the render hint as appropriate.
  338. \note this function hides the non-virtual base class implementation.
  339. */
  340. bool QCPPainter::begin(QPaintDevice *device)
  341. {
  342. bool result = QPainter::begin(device);
  343. #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions.
  344. if (result)
  345. setRenderHint(QPainter::NonCosmeticDefaultPen);
  346. #endif
  347. return result;
  348. }
  349. /*! \overload
  350. Sets the mode of the painter. This controls whether the painter shall adjust its
  351. fixes/workarounds optimized for certain output devices.
  352. */
  353. void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled)
  354. {
  355. if (!enabled && mModes.testFlag(mode))
  356. mModes &= ~mode;
  357. else if (enabled && !mModes.testFlag(mode))
  358. mModes |= mode;
  359. }
  360. /*!
  361. Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to
  362. QPainter, the save/restore functions are reimplemented to also save/restore those members.
  363. \note this function hides the non-virtual base class implementation.
  364. \see restore
  365. */
  366. void QCPPainter::save()
  367. {
  368. mAntialiasingStack.push(mIsAntialiasing);
  369. QPainter::save();
  370. }
  371. /*!
  372. Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to
  373. QPainter, the save/restore functions are reimplemented to also save/restore those members.
  374. \note this function hides the non-virtual base class implementation.
  375. \see save
  376. */
  377. void QCPPainter::restore()
  378. {
  379. if (!mAntialiasingStack.isEmpty())
  380. mIsAntialiasing = mAntialiasingStack.pop();
  381. else
  382. qDebug() << Q_FUNC_INFO << "Unbalanced save/restore";
  383. QPainter::restore();
  384. }
  385. /*!
  386. Changes the pen width to 1 if it currently is 0. This function is called in the \ref setPen
  387. overrides when the \ref pmNonCosmetic mode is set.
  388. */
  389. void QCPPainter::makeNonCosmetic()
  390. {
  391. if (qFuzzyIsNull(pen().widthF()))
  392. {
  393. QPen p = pen();
  394. p.setWidth(1);
  395. QPainter::setPen(p);
  396. }
  397. }
  398. /* end of 'src/painter.cpp' */
  399. /* including file 'src/paintbuffer.cpp' */
  400. /* modified 2021-03-29T02:30:44, size 18915 */
  401. ////////////////////////////////////////////////////////////////////////////////////////////////////
  402. //////////////////// QCPAbstractPaintBuffer
  403. ////////////////////////////////////////////////////////////////////////////////////////////////////
  404. /*! \class QCPAbstractPaintBuffer
  405. \brief The abstract base class for paint buffers, which define the rendering backend
  406. This abstract base class defines the basic interface that a paint buffer needs to provide in
  407. order to be usable by QCustomPlot.
  408. A paint buffer manages both a surface to draw onto, and the matching paint device. The size of
  409. the surface can be changed via \ref setSize. External classes (\ref QCustomPlot and \ref
  410. QCPLayer) request a painter via \ref startPainting and then perform the draw calls. Once the
  411. painting is complete, \ref donePainting is called, so the paint buffer implementation can do
  412. clean up if necessary. Before rendering a frame, each paint buffer is usually filled with a color
  413. using \ref clear (usually the color is \c Qt::transparent), to remove the contents of the
  414. previous frame.
  415. The simplest paint buffer implementation is \ref QCPPaintBufferPixmap which allows regular
  416. software rendering via the raster engine. Hardware accelerated rendering via pixel buffers and
  417. frame buffer objects is provided by \ref QCPPaintBufferGlPbuffer and \ref QCPPaintBufferGlFbo.
  418. They are used automatically if \ref QCustomPlot::setOpenGl is enabled.
  419. */
  420. /* start documentation of pure virtual functions */
  421. /*! \fn virtual QCPPainter *QCPAbstractPaintBuffer::startPainting() = 0
  422. Returns a \ref QCPPainter which is ready to draw to this buffer. The ownership and thus the
  423. responsibility to delete the painter after the painting operations are complete is given to the
  424. caller of this method.
  425. Once you are done using the painter, delete the painter and call \ref donePainting.
  426. While a painter generated with this method is active, you must not call \ref setSize, \ref
  427. setDevicePixelRatio or \ref clear.
  428. This method may return 0, if a painter couldn't be activated on the buffer. This usually
  429. indicates a problem with the respective painting backend.
  430. */
  431. /*! \fn virtual void QCPAbstractPaintBuffer::draw(QCPPainter *painter) const = 0
  432. Draws the contents of this buffer with the provided \a painter. This is the method that is used
  433. to finally join all paint buffers and draw them onto the screen.
  434. */
  435. /*! \fn virtual void QCPAbstractPaintBuffer::clear(const QColor &color) = 0
  436. Fills the entire buffer with the provided \a color. To have an empty transparent buffer, use the
  437. named color \c Qt::transparent.
  438. This method must not be called if there is currently a painter (acquired with \ref startPainting)
  439. active.
  440. */
  441. /*! \fn virtual void QCPAbstractPaintBuffer::reallocateBuffer() = 0
  442. Reallocates the internal buffer with the currently configured size (\ref setSize) and device
  443. pixel ratio, if applicable (\ref setDevicePixelRatio). It is called as soon as any of those
  444. properties are changed on this paint buffer.
  445. \note Subclasses of \ref QCPAbstractPaintBuffer must call their reimplementation of this method
  446. in their constructor, to perform the first allocation (this can not be done by the base class
  447. because calling pure virtual methods in base class constructors is not possible).
  448. */
  449. /* end documentation of pure virtual functions */
  450. /* start documentation of inline functions */
  451. /*! \fn virtual void QCPAbstractPaintBuffer::donePainting()
  452. If you have acquired a \ref QCPPainter to paint onto this paint buffer via \ref startPainting,
  453. call this method as soon as you are done with the painting operations and have deleted the
  454. painter.
  455. paint buffer subclasses may use this method to perform any type of cleanup that is necessary. The
  456. default implementation does nothing.
  457. */
  458. /* end documentation of inline functions */
  459. /*!
  460. Creates a paint buffer and initializes it with the provided \a size and \a devicePixelRatio.
  461. Subclasses must call their \ref reallocateBuffer implementation in their respective constructors.
  462. */
  463. QCPAbstractPaintBuffer::QCPAbstractPaintBuffer(const QSize &size, double devicePixelRatio) :
  464. mSize(size),
  465. mDevicePixelRatio(devicePixelRatio),
  466. mInvalidated(true)
  467. {
  468. }
  469. QCPAbstractPaintBuffer::~QCPAbstractPaintBuffer()
  470. {
  471. }
  472. /*!
  473. Sets the paint buffer size.
  474. The buffer is reallocated (by calling \ref reallocateBuffer), so any painters that were obtained
  475. by \ref startPainting are invalidated and must not be used after calling this method.
  476. If \a size is already the current buffer size, this method does nothing.
  477. */
  478. void QCPAbstractPaintBuffer::setSize(const QSize &size)
  479. {
  480. if (mSize != size)
  481. {
  482. mSize = size;
  483. reallocateBuffer();
  484. }
  485. }
  486. /*!
  487. Sets the invalidated flag to \a invalidated.
  488. This mechanism is used internally in conjunction with isolated replotting of \ref QCPLayer
  489. instances (in \ref QCPLayer::lmBuffered mode). If \ref QCPLayer::replot is called on a buffered
  490. layer, i.e. an isolated repaint of only that layer (and its dedicated paint buffer) is requested,
  491. QCustomPlot will decide depending on the invalidated flags of other paint buffers whether it also
  492. replots them, instead of only the layer on which the replot was called.
  493. The invalidated flag is set to true when \ref QCPLayer association has changed, i.e. if layers
  494. were added or removed from this buffer, or if they were reordered. It is set to false as soon as
  495. all associated \ref QCPLayer instances are drawn onto the buffer.
  496. Under normal circumstances, it is not necessary to manually call this method.
  497. */
  498. void QCPAbstractPaintBuffer::setInvalidated(bool invalidated)
  499. {
  500. mInvalidated = invalidated;
  501. }
  502. /*!
  503. Sets the device pixel ratio to \a ratio. This is useful to render on high-DPI output devices.
  504. The ratio is automatically set to the device pixel ratio used by the parent QCustomPlot instance.
  505. The buffer is reallocated (by calling \ref reallocateBuffer), so any painters that were obtained
  506. by \ref startPainting are invalidated and must not be used after calling this method.
  507. \note This method is only available for Qt versions 5.4 and higher.
  508. */
  509. void QCPAbstractPaintBuffer::setDevicePixelRatio(double ratio)
  510. {
  511. if (!qFuzzyCompare(ratio, mDevicePixelRatio))
  512. {
  513. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  514. mDevicePixelRatio = ratio;
  515. reallocateBuffer();
  516. #else
  517. qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
  518. mDevicePixelRatio = 1.0;
  519. #endif
  520. }
  521. }
  522. ////////////////////////////////////////////////////////////////////////////////////////////////////
  523. //////////////////// QCPPaintBufferPixmap
  524. ////////////////////////////////////////////////////////////////////////////////////////////////////
  525. /*! \class QCPPaintBufferPixmap
  526. \brief A paint buffer based on QPixmap, using software raster rendering
  527. This paint buffer is the default and fall-back paint buffer which uses software rendering and
  528. QPixmap as internal buffer. It is used if \ref QCustomPlot::setOpenGl is false.
  529. */
  530. /*!
  531. Creates a pixmap paint buffer instancen with the specified \a size and \a devicePixelRatio, if
  532. applicable.
  533. */
  534. QCPPaintBufferPixmap::QCPPaintBufferPixmap(const QSize &size, double devicePixelRatio) :
  535. QCPAbstractPaintBuffer(size, devicePixelRatio)
  536. {
  537. QCPPaintBufferPixmap::reallocateBuffer();
  538. }
  539. QCPPaintBufferPixmap::~QCPPaintBufferPixmap()
  540. {
  541. }
  542. /* inherits documentation from base class */
  543. QCPPainter *QCPPaintBufferPixmap::startPainting()
  544. {
  545. QCPPainter *result = new QCPPainter(&mBuffer);
  546. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  547. result->setRenderHint(QPainter::HighQualityAntialiasing);
  548. #endif
  549. return result;
  550. }
  551. /* inherits documentation from base class */
  552. void QCPPaintBufferPixmap::draw(QCPPainter *painter) const
  553. {
  554. if (painter && painter->isActive())
  555. painter->drawPixmap(0, 0, mBuffer);
  556. else
  557. qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
  558. }
  559. /* inherits documentation from base class */
  560. void QCPPaintBufferPixmap::clear(const QColor &color)
  561. {
  562. mBuffer.fill(color);
  563. }
  564. /* inherits documentation from base class */
  565. void QCPPaintBufferPixmap::reallocateBuffer()
  566. {
  567. setInvalidated();
  568. if (!qFuzzyCompare(1.0, mDevicePixelRatio))
  569. {
  570. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  571. mBuffer = QPixmap(mSize*mDevicePixelRatio);
  572. mBuffer.setDevicePixelRatio(mDevicePixelRatio);
  573. #else
  574. qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
  575. mDevicePixelRatio = 1.0;
  576. mBuffer = QPixmap(mSize);
  577. #endif
  578. } else
  579. {
  580. mBuffer = QPixmap(mSize);
  581. }
  582. }
  583. #ifdef QCP_OPENGL_PBUFFER
  584. ////////////////////////////////////////////////////////////////////////////////////////////////////
  585. //////////////////// QCPPaintBufferGlPbuffer
  586. ////////////////////////////////////////////////////////////////////////////////////////////////////
  587. /*! \class QCPPaintBufferGlPbuffer
  588. \brief A paint buffer based on OpenGL pixel buffers, using hardware accelerated rendering
  589. This paint buffer is one of the OpenGL paint buffers which facilitate hardware accelerated plot
  590. rendering. It is based on OpenGL pixel buffers (pbuffer) and is used in Qt versions before 5.0.
  591. (See \ref QCPPaintBufferGlFbo used in newer Qt versions.)
  592. The OpenGL paint buffers are used if \ref QCustomPlot::setOpenGl is set to true, and if they are
  593. supported by the system.
  594. */
  595. /*!
  596. Creates a \ref QCPPaintBufferGlPbuffer instance with the specified \a size and \a
  597. devicePixelRatio, if applicable.
  598. The parameter \a multisamples defines how many samples are used per pixel. Higher values thus
  599. result in higher quality antialiasing. If the specified \a multisamples value exceeds the
  600. capability of the graphics hardware, the highest supported multisampling is used.
  601. */
  602. QCPPaintBufferGlPbuffer::QCPPaintBufferGlPbuffer(const QSize &size, double devicePixelRatio, int multisamples) :
  603. QCPAbstractPaintBuffer(size, devicePixelRatio),
  604. mGlPBuffer(0),
  605. mMultisamples(qMax(0, multisamples))
  606. {
  607. QCPPaintBufferGlPbuffer::reallocateBuffer();
  608. }
  609. QCPPaintBufferGlPbuffer::~QCPPaintBufferGlPbuffer()
  610. {
  611. if (mGlPBuffer)
  612. delete mGlPBuffer;
  613. }
  614. /* inherits documentation from base class */
  615. QCPPainter *QCPPaintBufferGlPbuffer::startPainting()
  616. {
  617. if (!mGlPBuffer->isValid())
  618. {
  619. qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
  620. return 0;
  621. }
  622. QCPPainter *result = new QCPPainter(mGlPBuffer);
  623. result->setRenderHint(QPainter::HighQualityAntialiasing);
  624. return result;
  625. }
  626. /* inherits documentation from base class */
  627. void QCPPaintBufferGlPbuffer::draw(QCPPainter *painter) const
  628. {
  629. if (!painter || !painter->isActive())
  630. {
  631. qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
  632. return;
  633. }
  634. if (!mGlPBuffer->isValid())
  635. {
  636. qDebug() << Q_FUNC_INFO << "OpenGL pbuffer isn't valid, reallocateBuffer was not called?";
  637. return;
  638. }
  639. painter->drawImage(0, 0, mGlPBuffer->toImage());
  640. }
  641. /* inherits documentation from base class */
  642. void QCPPaintBufferGlPbuffer::clear(const QColor &color)
  643. {
  644. if (mGlPBuffer->isValid())
  645. {
  646. mGlPBuffer->makeCurrent();
  647. glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
  648. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  649. mGlPBuffer->doneCurrent();
  650. } else
  651. qDebug() << Q_FUNC_INFO << "OpenGL pbuffer invalid or context not current";
  652. }
  653. /* inherits documentation from base class */
  654. void QCPPaintBufferGlPbuffer::reallocateBuffer()
  655. {
  656. if (mGlPBuffer)
  657. delete mGlPBuffer;
  658. QGLFormat format;
  659. format.setAlpha(true);
  660. format.setSamples(mMultisamples);
  661. mGlPBuffer = new QGLPixelBuffer(mSize, format);
  662. }
  663. #endif // QCP_OPENGL_PBUFFER
  664. #ifdef QCP_OPENGL_FBO
  665. ////////////////////////////////////////////////////////////////////////////////////////////////////
  666. //////////////////// QCPPaintBufferGlFbo
  667. ////////////////////////////////////////////////////////////////////////////////////////////////////
  668. /*! \class QCPPaintBufferGlFbo
  669. \brief A paint buffer based on OpenGL frame buffers objects, using hardware accelerated rendering
  670. This paint buffer is one of the OpenGL paint buffers which facilitate hardware accelerated plot
  671. rendering. It is based on OpenGL frame buffer objects (fbo) and is used in Qt versions 5.0 and
  672. higher. (See \ref QCPPaintBufferGlPbuffer used in older Qt versions.)
  673. The OpenGL paint buffers are used if \ref QCustomPlot::setOpenGl is set to true, and if they are
  674. supported by the system.
  675. */
  676. /*!
  677. Creates a \ref QCPPaintBufferGlFbo instance with the specified \a size and \a devicePixelRatio,
  678. if applicable.
  679. All frame buffer objects shall share one OpenGL context and paint device, which need to be set up
  680. externally and passed via \a glContext and \a glPaintDevice. The set-up is done in \ref
  681. QCustomPlot::setupOpenGl and the context and paint device are managed by the parent QCustomPlot
  682. instance.
  683. */
  684. QCPPaintBufferGlFbo::QCPPaintBufferGlFbo(const QSize &size, double devicePixelRatio, QWeakPointer<QOpenGLContext> glContext, QWeakPointer<QOpenGLPaintDevice> glPaintDevice) :
  685. QCPAbstractPaintBuffer(size, devicePixelRatio),
  686. mGlContext(glContext),
  687. mGlPaintDevice(glPaintDevice),
  688. mGlFrameBuffer(0)
  689. {
  690. QCPPaintBufferGlFbo::reallocateBuffer();
  691. }
  692. QCPPaintBufferGlFbo::~QCPPaintBufferGlFbo()
  693. {
  694. if (mGlFrameBuffer)
  695. delete mGlFrameBuffer;
  696. }
  697. /* inherits documentation from base class */
  698. QCPPainter *QCPPaintBufferGlFbo::startPainting()
  699. {
  700. QSharedPointer<QOpenGLPaintDevice> paintDevice = mGlPaintDevice.toStrongRef();
  701. QSharedPointer<QOpenGLContext> context = mGlContext.toStrongRef();
  702. if (!paintDevice)
  703. {
  704. qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist";
  705. return 0;
  706. }
  707. if (!context)
  708. {
  709. qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist";
  710. return 0;
  711. }
  712. if (!mGlFrameBuffer)
  713. {
  714. qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
  715. return 0;
  716. }
  717. if (QOpenGLContext::currentContext() != context.data())
  718. context->makeCurrent(context->surface());
  719. mGlFrameBuffer->bind();
  720. QCPPainter *result = new QCPPainter(paintDevice.data());
  721. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  722. result->setRenderHint(QPainter::HighQualityAntialiasing);
  723. #endif
  724. return result;
  725. }
  726. /* inherits documentation from base class */
  727. void QCPPaintBufferGlFbo::donePainting()
  728. {
  729. if (mGlFrameBuffer && mGlFrameBuffer->isBound())
  730. mGlFrameBuffer->release();
  731. else
  732. qDebug() << Q_FUNC_INFO << "Either OpenGL frame buffer not valid or was not bound";
  733. }
  734. /* inherits documentation from base class */
  735. void QCPPaintBufferGlFbo::draw(QCPPainter *painter) const
  736. {
  737. if (!painter || !painter->isActive())
  738. {
  739. qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
  740. return;
  741. }
  742. if (!mGlFrameBuffer)
  743. {
  744. qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
  745. return;
  746. }
  747. painter->drawImage(0, 0, mGlFrameBuffer->toImage());
  748. }
  749. /* inherits documentation from base class */
  750. void QCPPaintBufferGlFbo::clear(const QColor &color)
  751. {
  752. QSharedPointer<QOpenGLContext> context = mGlContext.toStrongRef();
  753. if (!context)
  754. {
  755. qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist";
  756. return;
  757. }
  758. if (!mGlFrameBuffer)
  759. {
  760. qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
  761. return;
  762. }
  763. if (QOpenGLContext::currentContext() != context.data())
  764. context->makeCurrent(context->surface());
  765. mGlFrameBuffer->bind();
  766. glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
  767. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  768. mGlFrameBuffer->release();
  769. }
  770. /* inherits documentation from base class */
  771. void QCPPaintBufferGlFbo::reallocateBuffer()
  772. {
  773. // release and delete possibly existing framebuffer:
  774. if (mGlFrameBuffer)
  775. {
  776. if (mGlFrameBuffer->isBound())
  777. mGlFrameBuffer->release();
  778. delete mGlFrameBuffer;
  779. mGlFrameBuffer = 0;
  780. }
  781. QSharedPointer<QOpenGLPaintDevice> paintDevice = mGlPaintDevice.toStrongRef();
  782. QSharedPointer<QOpenGLContext> context = mGlContext.toStrongRef();
  783. if (!paintDevice)
  784. {
  785. qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist";
  786. return;
  787. }
  788. if (!context)
  789. {
  790. qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist";
  791. return;
  792. }
  793. // create new fbo with appropriate size:
  794. context->makeCurrent(context->surface());
  795. QOpenGLFramebufferObjectFormat frameBufferFormat;
  796. frameBufferFormat.setSamples(context->format().samples());
  797. frameBufferFormat.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
  798. mGlFrameBuffer = new QOpenGLFramebufferObject(mSize*mDevicePixelRatio, frameBufferFormat);
  799. if (paintDevice->size() != mSize*mDevicePixelRatio)
  800. paintDevice->setSize(mSize*mDevicePixelRatio);
  801. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  802. paintDevice->setDevicePixelRatio(mDevicePixelRatio);
  803. #endif
  804. }
  805. #endif // QCP_OPENGL_FBO
  806. /* end of 'src/paintbuffer.cpp' */
  807. /* including file 'src/layer.cpp' */
  808. /* modified 2021-03-29T02:30:44, size 37615 */
  809. ////////////////////////////////////////////////////////////////////////////////////////////////////
  810. //////////////////// QCPLayer
  811. ////////////////////////////////////////////////////////////////////////////////////////////////////
  812. /*! \class QCPLayer
  813. \brief A layer that may contain objects, to control the rendering order
  814. The Layering system of QCustomPlot is the mechanism to control the rendering order of the
  815. elements inside the plot.
  816. It is based on the two classes QCPLayer and QCPLayerable. QCustomPlot holds an ordered list of
  817. one or more instances of QCPLayer (see QCustomPlot::addLayer, QCustomPlot::layer,
  818. QCustomPlot::moveLayer, etc.). When replotting, QCustomPlot goes through the list of layers
  819. bottom to top and successively draws the layerables of the layers into the paint buffer(s).
  820. A QCPLayer contains an ordered list of QCPLayerable instances. QCPLayerable is an abstract base
  821. class from which almost all visible objects derive, like axes, grids, graphs, items, etc.
  822. \section qcplayer-defaultlayers Default layers
  823. Initially, QCustomPlot has six layers: "background", "grid", "main", "axes", "legend" and
  824. "overlay" (in that order). On top is the "overlay" layer, which only contains the QCustomPlot's
  825. selection rect (\ref QCustomPlot::selectionRect). The next two layers "axes" and "legend" contain
  826. the default axes and legend, so they will be drawn above plottables. In the middle, there is the
  827. "main" layer. It is initially empty and set as the current layer (see
  828. QCustomPlot::setCurrentLayer). This means, all new plottables, items etc. are created on this
  829. layer by default. Then comes the "grid" layer which contains the QCPGrid instances (which belong
  830. tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background shall be drawn behind
  831. everything else, thus the default QCPAxisRect instance is placed on the "background" layer. Of
  832. course, the layer affiliation of the individual objects can be changed as required (\ref
  833. QCPLayerable::setLayer).
  834. \section qcplayer-ordering Controlling the rendering order via layers
  835. Controlling the ordering of layerables in the plot is easy: Create a new layer in the position
  836. you want the layerable to be in, e.g. above "main", with \ref QCustomPlot::addLayer. Then set the
  837. current layer with \ref QCustomPlot::setCurrentLayer to that new layer and finally create the
  838. objects normally. They will be placed on the new layer automatically, due to the current layer
  839. setting. Alternatively you could have also ignored the current layer setting and just moved the
  840. objects with \ref QCPLayerable::setLayer to the desired layer after creating them.
  841. It is also possible to move whole layers. For example, If you want the grid to be shown in front
  842. of all plottables/items on the "main" layer, just move it above "main" with
  843. QCustomPlot::moveLayer.
  844. The rendering order within one layer is simply by order of creation or insertion. The item
  845. created last (or added last to the layer), is drawn on top of all other objects on that layer.
  846. When a layer is deleted, the objects on it are not deleted with it, but fall on the layer below
  847. the deleted layer, see QCustomPlot::removeLayer.
  848. \section qcplayer-buffering Replotting only a specific layer
  849. If the layer mode (\ref setMode) is set to \ref lmBuffered, you can replot only this specific
  850. layer by calling \ref replot. In certain situations this can provide better replot performance,
  851. compared with a full replot of all layers. Upon creation of a new layer, the layer mode is
  852. initialized to \ref lmLogical. The only layer that is set to \ref lmBuffered in a new \ref
  853. QCustomPlot instance is the "overlay" layer, containing the selection rect.
  854. */
  855. /* start documentation of inline functions */
  856. /*! \fn QList<QCPLayerable*> QCPLayer::children() const
  857. Returns a list of all layerables on this layer. The order corresponds to the rendering order:
  858. layerables with higher indices are drawn above layerables with lower indices.
  859. */
  860. /*! \fn int QCPLayer::index() const
  861. Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be
  862. accessed via \ref QCustomPlot::layer.
  863. Layers with higher indices will be drawn above layers with lower indices.
  864. */
  865. /* end documentation of inline functions */
  866. /*!
  867. Creates a new QCPLayer instance.
  868. Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead.
  869. \warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot.
  870. This check is only performed by \ref QCustomPlot::addLayer.
  871. */
  872. QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) :
  873. QObject(parentPlot),
  874. mParentPlot(parentPlot),
  875. mName(layerName),
  876. mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function
  877. mVisible(true),
  878. mMode(lmLogical)
  879. {
  880. // Note: no need to make sure layerName is unique, because layer
  881. // management is done with QCustomPlot functions.
  882. }
  883. QCPLayer::~QCPLayer()
  884. {
  885. // If child layerables are still on this layer, detach them, so they don't try to reach back to this
  886. // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted
  887. // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to
  888. // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.)
  889. while (!mChildren.isEmpty())
  890. mChildren.last()->setLayer(nullptr); // removes itself from mChildren via removeChild()
  891. if (mParentPlot->currentLayer() == this)
  892. qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or nullptr beforehand.";
  893. }
  894. /*!
  895. Sets whether this layer is visible or not. If \a visible is set to false, all layerables on this
  896. layer will be invisible.
  897. This function doesn't change the visibility property of the layerables (\ref
  898. QCPLayerable::setVisible), but the \ref QCPLayerable::realVisibility of each layerable takes the
  899. visibility of the parent layer into account.
  900. */
  901. void QCPLayer::setVisible(bool visible)
  902. {
  903. mVisible = visible;
  904. }
  905. /*!
  906. Sets the rendering mode of this layer.
  907. If \a mode is set to \ref lmBuffered for a layer, it will be given a dedicated paint buffer by
  908. the parent QCustomPlot instance. This means it may be replotted individually by calling \ref
  909. QCPLayer::replot, without needing to replot all other layers.
  910. Layers which are set to \ref lmLogical (the default) are used only to define the rendering order
  911. and can't be replotted individually.
  912. Note that each layer which is set to \ref lmBuffered requires additional paint buffers for the
  913. layers below, above and for the layer itself. This increases the memory consumption and
  914. (slightly) decreases the repainting speed because multiple paint buffers need to be joined. So
  915. you should carefully choose which layers benefit from having their own paint buffer. A typical
  916. example would be a layer which contains certain layerables (e.g. items) that need to be changed
  917. and thus replotted regularly, while all other layerables on other layers stay static. By default,
  918. only the topmost layer called "overlay" is in mode \ref lmBuffered, and contains the selection
  919. rect.
  920. \see replot
  921. */
  922. void QCPLayer::setMode(QCPLayer::LayerMode mode)
  923. {
  924. if (mMode != mode)
  925. {
  926. mMode = mode;
  927. if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
  928. pb->setInvalidated();
  929. }
  930. }
  931. /*! \internal
  932. Draws the contents of this layer with the provided \a painter.
  933. \see replot, drawToPaintBuffer
  934. */
  935. void QCPLayer::draw(QCPPainter *painter)
  936. {
  937. foreach (QCPLayerable *child, mChildren)
  938. {
  939. if (child->realVisibility())
  940. {
  941. painter->save();
  942. // painter->setClipRect(child->clipRect().translated(0, -1));
  943. painter->setClipRect(child->clipRect().adjusted(0,0,1,1));
  944. child->applyDefaultAntialiasingHint(painter);
  945. child->draw(painter);
  946. painter->restore();
  947. }
  948. }
  949. }
  950. /*! \internal
  951. Draws the contents of this layer into the paint buffer which is associated with this layer. The
  952. association is established by the parent QCustomPlot, which manages all paint buffers (see \ref
  953. QCustomPlot::setupPaintBuffers).
  954. \see draw
  955. */
  956. void QCPLayer::drawToPaintBuffer()
  957. {
  958. if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
  959. {
  960. if (QCPPainter *painter = pb->startPainting())
  961. {
  962. if (painter->isActive())
  963. draw(painter);
  964. else
  965. qDebug() << Q_FUNC_INFO << "paint buffer returned inactive painter";
  966. delete painter;
  967. pb->donePainting();
  968. } else
  969. qDebug() << Q_FUNC_INFO << "paint buffer returned nullptr painter";
  970. } else
  971. qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer";
  972. }
  973. /*!
  974. If the layer mode (\ref setMode) is set to \ref lmBuffered, this method allows replotting only
  975. the layerables on this specific layer, without the need to replot all other layers (as a call to
  976. \ref QCustomPlot::replot would do).
  977. QCustomPlot also makes sure to replot all layers instead of only this one, if the layer ordering
  978. or any layerable-layer-association has changed since the last full replot and any other paint
  979. buffers were thus invalidated.
  980. If the layer mode is \ref lmLogical however, this method simply calls \ref QCustomPlot::replot on
  981. the parent QCustomPlot instance.
  982. \see draw
  983. */
  984. void QCPLayer::replot()
  985. {
  986. if (mMode == lmBuffered && !mParentPlot->hasInvalidatedPaintBuffers())
  987. {
  988. if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
  989. {
  990. pb->clear(Qt::transparent);
  991. drawToPaintBuffer();
  992. pb->setInvalidated(false); // since layer is lmBuffered, we know only this layer is on buffer and we can reset invalidated flag
  993. mParentPlot->update();
  994. } else
  995. qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer";
  996. } else {
  997. mParentPlot->replot();
  998. }
  999. }
  1000. /*! \internal
  1001. Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will
  1002. be prepended to the list, i.e. be drawn beneath the other layerables already in the list.
  1003. This function does not change the \a mLayer member of \a layerable to this layer. (Use
  1004. QCPLayerable::setLayer to change the layer of an object, not this function.)
  1005. \see removeChild
  1006. */
  1007. void QCPLayer::addChild(QCPLayerable *layerable, bool prepend)
  1008. {
  1009. if (!mChildren.contains(layerable))
  1010. {
  1011. if (prepend)
  1012. mChildren.prepend(layerable);
  1013. else
  1014. mChildren.append(layerable);
  1015. if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
  1016. pb->setInvalidated();
  1017. } else
  1018. qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast<quintptr>(layerable);
  1019. }
  1020. /*! \internal
  1021. Removes the \a layerable from the list of this layer.
  1022. This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer
  1023. to change the layer of an object, not this function.)
  1024. \see addChild
  1025. */
  1026. void QCPLayer::removeChild(QCPLayerable *layerable)
  1027. {
  1028. if (mChildren.removeOne(layerable))
  1029. {
  1030. if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
  1031. pb->setInvalidated();
  1032. } else
  1033. qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast<quintptr>(layerable);
  1034. }
  1035. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1036. //////////////////// QCPLayerable
  1037. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1038. /*! \class QCPLayerable
  1039. \brief Base class for all drawable objects
  1040. This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid
  1041. etc.
  1042. Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking
  1043. the layers accordingly.
  1044. For details about the layering mechanism, see the QCPLayer documentation.
  1045. */
  1046. /* start documentation of inline functions */
  1047. /*! \fn QCPLayerable *QCPLayerable::parentLayerable() const
  1048. Returns the parent layerable of this layerable. The parent layerable is used to provide
  1049. visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables
  1050. only get drawn if their parent layerables are visible, too.
  1051. Note that a parent layerable is not necessarily also the QObject parent for memory management.
  1052. Further, a layerable doesn't always have a parent layerable, so this function may return \c
  1053. nullptr.
  1054. A parent layerable is set implicitly when placed inside layout elements and doesn't need to be
  1055. set manually by the user.
  1056. */
  1057. /* end documentation of inline functions */
  1058. /* start documentation of pure virtual functions */
  1059. /*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0
  1060. \internal
  1061. This function applies the default antialiasing setting to the specified \a painter, using the
  1062. function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when
  1063. \ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing
  1064. setting may be specified individually, this function should set the antialiasing state of the
  1065. most prominent entity. In this case however, the \ref draw function usually calls the specialized
  1066. versions of this function before drawing each entity, effectively overriding the setting of the
  1067. default antialiasing hint.
  1068. <b>First example:</b> QCPGraph has multiple entities that have an antialiasing setting: The graph
  1069. line, fills and scatters. Those can be configured via QCPGraph::setAntialiased,
  1070. QCPGraph::setAntialiasedFill and QCPGraph::setAntialiasedScatters. Consequently, there isn't only
  1071. the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's
  1072. antialiasing), but specialized ones like QCPGraph::applyFillAntialiasingHint and
  1073. QCPGraph::applyScattersAntialiasingHint. So before drawing one of those entities, QCPGraph::draw
  1074. calls the respective specialized applyAntialiasingHint function.
  1075. <b>Second example:</b> QCPItemLine consists only of a line so there is only one antialiasing
  1076. setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by
  1077. all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the
  1078. respective layerable subclass.) Consequently it only has the normal
  1079. QCPItemLine::applyDefaultAntialiasingHint. The \ref QCPItemLine::draw function doesn't need to
  1080. care about setting any antialiasing states, because the default antialiasing hint is already set
  1081. on the painter when the \ref draw function is called, and that's the state it wants to draw the
  1082. line with.
  1083. */
  1084. /*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0
  1085. \internal
  1086. This function draws the layerable with the specified \a painter. It is only called by
  1087. QCustomPlot, if the layerable is visible (\ref setVisible).
  1088. Before this function is called, the painter's antialiasing state is set via \ref
  1089. applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was
  1090. set to \ref clipRect.
  1091. */
  1092. /* end documentation of pure virtual functions */
  1093. /* start documentation of signals */
  1094. /*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer);
  1095. This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to
  1096. a different layer.
  1097. \see setLayer
  1098. */
  1099. /* end documentation of signals */
  1100. /*!
  1101. Creates a new QCPLayerable instance.
  1102. Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the
  1103. derived classes.
  1104. If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a
  1105. targetLayer is an empty string, it places itself on the current layer of the plot (see \ref
  1106. QCustomPlot::setCurrentLayer).
  1107. It is possible to provide \c nullptr as \a plot. In that case, you should assign a parent plot at
  1108. a later time with \ref initializeParentPlot.
  1109. The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable
  1110. parents are mainly used to control visibility in a hierarchy of layerables. This means a
  1111. layerable is only drawn, if all its ancestor layerables are also visible. Note that \a
  1112. parentLayerable does not become the QObject-parent (for memory management) of this layerable, \a
  1113. plot does. It is not uncommon to set the QObject-parent to something else in the constructors of
  1114. QCPLayerable subclasses, to guarantee a working destruction hierarchy.
  1115. */
  1116. QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) :
  1117. QObject(plot),
  1118. mVisible(true),
  1119. mParentPlot(plot),
  1120. mParentLayerable(parentLayerable),
  1121. mLayer(nullptr),
  1122. mAntialiased(true)
  1123. {
  1124. if (mParentPlot)
  1125. {
  1126. if (targetLayer.isEmpty())
  1127. setLayer(mParentPlot->currentLayer());
  1128. else if (!setLayer(targetLayer))
  1129. qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed.";
  1130. }
  1131. }
  1132. QCPLayerable::~QCPLayerable()
  1133. {
  1134. if (mLayer)
  1135. {
  1136. mLayer->removeChild(this);
  1137. mLayer = nullptr;
  1138. }
  1139. }
  1140. /*!
  1141. Sets the visibility of this layerable object. If an object is not visible, it will not be drawn
  1142. on the QCustomPlot surface, and user interaction with it (e.g. click and selection) is not
  1143. possible.
  1144. */
  1145. void QCPLayerable::setVisible(bool on)
  1146. {
  1147. mVisible = on;
  1148. }
  1149. /*!
  1150. Sets the \a layer of this layerable object. The object will be placed on top of the other objects
  1151. already on \a layer.
  1152. If \a layer is 0, this layerable will not be on any layer and thus not appear in the plot (or
  1153. interact/receive events).
  1154. Returns true if the layer of this layerable was successfully changed to \a layer.
  1155. */
  1156. bool QCPLayerable::setLayer(QCPLayer *layer)
  1157. {
  1158. return moveToLayer(layer, false);
  1159. }
  1160. /*! \overload
  1161. Sets the layer of this layerable object by name
  1162. Returns true on success, i.e. if \a layerName is a valid layer name.
  1163. */
  1164. bool QCPLayerable::setLayer(const QString &layerName)
  1165. {
  1166. if (!mParentPlot)
  1167. {
  1168. qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
  1169. return false;
  1170. }
  1171. if (QCPLayer *layer = mParentPlot->layer(layerName))
  1172. {
  1173. return setLayer(layer);
  1174. } else
  1175. {
  1176. qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName;
  1177. return false;
  1178. }
  1179. }
  1180. /*!
  1181. Sets whether this object will be drawn antialiased or not.
  1182. Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and
  1183. QCustomPlot::setNotAntialiasedElements.
  1184. */
  1185. void QCPLayerable::setAntialiased(bool enabled)
  1186. {
  1187. mAntialiased = enabled;
  1188. }
  1189. /*!
  1190. Returns whether this layerable is visible, taking the visibility of the layerable parent and the
  1191. visibility of this layerable's layer into account. This is the method that is consulted to decide
  1192. whether a layerable shall be drawn or not.
  1193. If this layerable has a direct layerable parent (usually set via hierarchies implemented in
  1194. subclasses, like in the case of \ref QCPLayoutElement), this function returns true only if this
  1195. layerable has its visibility set to true and the parent layerable's \ref realVisibility returns
  1196. true.
  1197. */
  1198. bool QCPLayerable::realVisibility() const
  1199. {
  1200. return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility());
  1201. }
  1202. /*!
  1203. This function is used to decide whether a click hits a layerable object or not.
  1204. \a pos is a point in pixel coordinates on the QCustomPlot surface. This function returns the
  1205. shortest pixel distance of this point to the object. If the object is either invisible or the
  1206. distance couldn't be determined, -1.0 is returned. Further, if \a onlySelectable is true and the
  1207. object is not selectable, -1.0 is returned, too.
  1208. If the object is represented not by single lines but by an area like a \ref QCPItemText or the
  1209. bars of a \ref QCPBars plottable, a click inside the area should also be considered a hit. In
  1210. these cases this function thus returns a constant value greater zero but still below the parent
  1211. plot's selection tolerance. (typically the selectionTolerance multiplied by 0.99).
  1212. Providing a constant value for area objects allows selecting line objects even when they are
  1213. obscured by such area objects, by clicking close to the lines (i.e. closer than
  1214. 0.99*selectionTolerance).
  1215. The actual setting of the selection state is not done by this function. This is handled by the
  1216. parent QCustomPlot when the mouseReleaseEvent occurs, and the finally selected object is notified
  1217. via the \ref selectEvent/\ref deselectEvent methods.
  1218. \a details is an optional output parameter. Every layerable subclass may place any information
  1219. in \a details. This information will be passed to \ref selectEvent when the parent QCustomPlot
  1220. decides on the basis of this selectTest call, that the object was successfully selected. The
  1221. subsequent call to \ref selectEvent will carry the \a details. This is useful for multi-part
  1222. objects (like QCPAxis). This way, a possibly complex calculation to decide which part was clicked
  1223. is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be
  1224. placed in \a details. So in the subsequent \ref selectEvent, the decision which part was
  1225. selected doesn't have to be done a second time for a single selection operation.
  1226. In the case of 1D Plottables (\ref QCPAbstractPlottable1D, like \ref QCPGraph or \ref QCPBars) \a
  1227. details will be set to a \ref QCPDataSelection, describing the closest data point to \a pos.
  1228. You may pass \c nullptr as \a details to indicate that you are not interested in those selection
  1229. details.
  1230. \see selectEvent, deselectEvent, mousePressEvent, wheelEvent, QCustomPlot::setInteractions,
  1231. QCPAbstractPlottable1D::selectTestRect
  1232. */
  1233. double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  1234. {
  1235. Q_UNUSED(pos)
  1236. Q_UNUSED(onlySelectable)
  1237. Q_UNUSED(details)
  1238. return -1.0;
  1239. }
  1240. /*! \internal
  1241. Sets the parent plot of this layerable. Use this function once to set the parent plot if you have
  1242. passed \c nullptr in the constructor. It can not be used to move a layerable from one QCustomPlot
  1243. to another one.
  1244. Note that, unlike when passing a non \c nullptr parent plot in the constructor, this function
  1245. does not make \a parentPlot the QObject-parent of this layerable. If you want this, call
  1246. QObject::setParent(\a parentPlot) in addition to this function.
  1247. Further, you will probably want to set a layer (\ref setLayer) after calling this function, to
  1248. make the layerable appear on the QCustomPlot.
  1249. The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized
  1250. so they can react accordingly (e.g. also initialize the parent plot of child layerables, like
  1251. QCPLayout does).
  1252. */
  1253. void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot)
  1254. {
  1255. if (mParentPlot)
  1256. {
  1257. qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized";
  1258. return;
  1259. }
  1260. if (!parentPlot)
  1261. qDebug() << Q_FUNC_INFO << "called with parentPlot zero";
  1262. mParentPlot = parentPlot;
  1263. parentPlotInitialized(mParentPlot);
  1264. }
  1265. /*! \internal
  1266. Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not
  1267. become the QObject-parent (for memory management) of this layerable.
  1268. The parent layerable has influence on the return value of the \ref realVisibility method. Only
  1269. layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be
  1270. drawn.
  1271. \see realVisibility
  1272. */
  1273. void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable)
  1274. {
  1275. mParentLayerable = parentLayerable;
  1276. }
  1277. /*! \internal
  1278. Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to
  1279. the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is
  1280. false, the object will be appended.
  1281. Returns true on success, i.e. if \a layer is a valid layer.
  1282. */
  1283. bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend)
  1284. {
  1285. if (layer && !mParentPlot)
  1286. {
  1287. qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
  1288. return false;
  1289. }
  1290. if (layer && layer->parentPlot() != mParentPlot)
  1291. {
  1292. qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable";
  1293. return false;
  1294. }
  1295. QCPLayer *oldLayer = mLayer;
  1296. if (mLayer)
  1297. mLayer->removeChild(this);
  1298. mLayer = layer;
  1299. if (mLayer)
  1300. mLayer->addChild(this, prepend);
  1301. if (mLayer != oldLayer)
  1302. emit layerChanged(mLayer);
  1303. return true;
  1304. }
  1305. /*! \internal
  1306. Sets the QCPainter::setAntialiasing state on the provided \a painter, depending on the \a
  1307. localAntialiased value as well as the overrides \ref QCustomPlot::setAntialiasedElements and \ref
  1308. QCustomPlot::setNotAntialiasedElements. Which override enum this function takes into account is
  1309. controlled via \a overrideElement.
  1310. */
  1311. void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const
  1312. {
  1313. if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement))
  1314. painter->setAntialiasing(false);
  1315. else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement))
  1316. painter->setAntialiasing(true);
  1317. else
  1318. painter->setAntialiasing(localAntialiased);
  1319. }
  1320. /*! \internal
  1321. This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting
  1322. of a parent plot. This is the case when \c nullptr was passed as parent plot in the constructor,
  1323. and the parent plot is set at a later time.
  1324. For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any
  1325. QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level
  1326. element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To
  1327. propagate the parent plot to all the children of the hierarchy, the top level element then uses
  1328. this function to pass the parent plot on to its child elements.
  1329. The default implementation does nothing.
  1330. \see initializeParentPlot
  1331. */
  1332. void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot)
  1333. {
  1334. Q_UNUSED(parentPlot)
  1335. }
  1336. /*! \internal
  1337. Returns the selection category this layerable shall belong to. The selection category is used in
  1338. conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and
  1339. which aren't.
  1340. Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref
  1341. QCP::iSelectOther. This is what the default implementation returns.
  1342. \see QCustomPlot::setInteractions
  1343. */
  1344. QCP::Interaction QCPLayerable::selectionCategory() const
  1345. {
  1346. return QCP::iSelectOther;
  1347. }
  1348. /*! \internal
  1349. Returns the clipping rectangle of this layerable object. By default, this is the viewport of the
  1350. parent QCustomPlot. Specific subclasses may reimplement this function to provide different
  1351. clipping rects.
  1352. The returned clipping rect is set on the painter before the draw function of the respective
  1353. object is called.
  1354. */
  1355. QRectF QCPLayerable::clipRect() const
  1356. {
  1357. if (mParentPlot)
  1358. return mParentPlot->viewport();
  1359. else
  1360. return {};
  1361. }
  1362. /*! \internal
  1363. This event is called when the layerable shall be selected, as a consequence of a click by the
  1364. user. Subclasses should react to it by setting their selection state appropriately. The default
  1365. implementation does nothing.
  1366. \a event is the mouse event that caused the selection. \a additive indicates, whether the user
  1367. was holding the multi-select-modifier while performing the selection (see \ref
  1368. QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled
  1369. (i.e. become selected when unselected and unselected when selected).
  1370. Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e.
  1371. returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot).
  1372. The \a details data you output from \ref selectTest is fed back via \a details here. You may
  1373. use it to transport any kind of information from the selectTest to the possibly subsequent
  1374. selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable
  1375. that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need
  1376. to do the calculation again to find out which part was actually clicked.
  1377. \a selectionStateChanged is an output parameter. If the pointer is non-null, this function must
  1378. set the value either to true or false, depending on whether the selection state of this layerable
  1379. was actually changed. For layerables that only are selectable as a whole and not in parts, this
  1380. is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the
  1381. selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the
  1382. layerable was previously unselected and now is switched to the selected state.
  1383. \see selectTest, deselectEvent
  1384. */
  1385. void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  1386. {
  1387. Q_UNUSED(event)
  1388. Q_UNUSED(additive)
  1389. Q_UNUSED(details)
  1390. Q_UNUSED(selectionStateChanged)
  1391. }
  1392. /*! \internal
  1393. This event is called when the layerable shall be deselected, either as consequence of a user
  1394. interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by
  1395. unsetting their selection appropriately.
  1396. just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must
  1397. return true or false when the selection state of this layerable has changed or not changed,
  1398. respectively.
  1399. \see selectTest, selectEvent
  1400. */
  1401. void QCPLayerable::deselectEvent(bool *selectionStateChanged)
  1402. {
  1403. Q_UNUSED(selectionStateChanged)
  1404. }
  1405. /*!
  1406. This event gets called when the user presses a mouse button while the cursor is over the
  1407. layerable. Whether a cursor is over the layerable is decided by a preceding call to \ref
  1408. selectTest.
  1409. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
  1410. event->pos(). The parameter \a details contains layerable-specific details about the hit, which
  1411. were generated in the previous call to \ref selectTest. For example, One-dimensional plottables
  1412. like \ref QCPGraph or \ref QCPBars convey the clicked data point in the \a details parameter, as
  1413. \ref QCPDataSelection packed as QVariant. Multi-part objects convey the specific \c
  1414. SelectablePart that was hit (e.g. \ref QCPAxis::SelectablePart in the case of axes).
  1415. QCustomPlot uses an event propagation system that works the same as Qt's system. If your
  1416. layerable doesn't reimplement the \ref mousePressEvent or explicitly calls \c event->ignore() in
  1417. its reimplementation, the event will be propagated to the next layerable in the stacking order.
  1418. Once a layerable has accepted the \ref mousePressEvent, it is considered the mouse grabber and
  1419. will receive all following calls to \ref mouseMoveEvent or \ref mouseReleaseEvent for this mouse
  1420. interaction (a "mouse interaction" in this context ends with the release).
  1421. The default implementation does nothing except explicitly ignoring the event with \c
  1422. event->ignore().
  1423. \see mouseMoveEvent, mouseReleaseEvent, mouseDoubleClickEvent, wheelEvent
  1424. */
  1425. void QCPLayerable::mousePressEvent(QMouseEvent *event, const QVariant &details)
  1426. {
  1427. Q_UNUSED(details)
  1428. event->ignore();
  1429. }
  1430. /*!
  1431. This event gets called when the user moves the mouse while holding a mouse button, after this
  1432. layerable has become the mouse grabber by accepting the preceding \ref mousePressEvent.
  1433. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
  1434. event->pos(). The parameter \a startPos indicates the position where the initial \ref
  1435. mousePressEvent occurred, that started the mouse interaction.
  1436. The default implementation does nothing.
  1437. \see mousePressEvent, mouseReleaseEvent, mouseDoubleClickEvent, wheelEvent
  1438. */
  1439. void QCPLayerable::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  1440. {
  1441. Q_UNUSED(startPos)
  1442. event->ignore();
  1443. }
  1444. /*!
  1445. This event gets called when the user releases the mouse button, after this layerable has become
  1446. the mouse grabber by accepting the preceding \ref mousePressEvent.
  1447. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
  1448. event->pos(). The parameter \a startPos indicates the position where the initial \ref
  1449. mousePressEvent occurred, that started the mouse interaction.
  1450. The default implementation does nothing.
  1451. \see mousePressEvent, mouseMoveEvent, mouseDoubleClickEvent, wheelEvent
  1452. */
  1453. void QCPLayerable::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  1454. {
  1455. Q_UNUSED(startPos)
  1456. event->ignore();
  1457. }
  1458. /*!
  1459. This event gets called when the user presses the mouse button a second time in a double-click,
  1460. while the cursor is over the layerable. Whether a cursor is over the layerable is decided by a
  1461. preceding call to \ref selectTest.
  1462. The \ref mouseDoubleClickEvent is called instead of the second \ref mousePressEvent. So in the
  1463. case of a double-click, the event succession is
  1464. <i>pressEvent &ndash; releaseEvent &ndash; doubleClickEvent &ndash; releaseEvent</i>.
  1465. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
  1466. event->pos(). The parameter \a details contains layerable-specific details about the hit, which
  1467. were generated in the previous call to \ref selectTest. For example, One-dimensional plottables
  1468. like \ref QCPGraph or \ref QCPBars convey the clicked data point in the \a details parameter, as
  1469. \ref QCPDataSelection packed as QVariant. Multi-part objects convey the specific \c
  1470. SelectablePart that was hit (e.g. \ref QCPAxis::SelectablePart in the case of axes).
  1471. Similarly to \ref mousePressEvent, once a layerable has accepted the \ref mouseDoubleClickEvent,
  1472. it is considered the mouse grabber and will receive all following calls to \ref mouseMoveEvent
  1473. and \ref mouseReleaseEvent for this mouse interaction (a "mouse interaction" in this context ends
  1474. with the release).
  1475. The default implementation does nothing except explicitly ignoring the event with \c
  1476. event->ignore().
  1477. \see mousePressEvent, mouseMoveEvent, mouseReleaseEvent, wheelEvent
  1478. */
  1479. void QCPLayerable::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details)
  1480. {
  1481. Q_UNUSED(details)
  1482. event->ignore();
  1483. }
  1484. /*!
  1485. This event gets called when the user turns the mouse scroll wheel while the cursor is over the
  1486. layerable. Whether a cursor is over the layerable is decided by a preceding call to \ref
  1487. selectTest.
  1488. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
  1489. event->pos().
  1490. The \c event->angleDelta() indicates how far the mouse wheel was turned, which is usually +/- 120
  1491. for single rotation steps. However, if the mouse wheel is turned rapidly, multiple steps may
  1492. accumulate to one event, making the delta larger. On the other hand, if the wheel has very smooth
  1493. steps or none at all, the delta may be smaller.
  1494. The default implementation does nothing.
  1495. \see mousePressEvent, mouseMoveEvent, mouseReleaseEvent, mouseDoubleClickEvent
  1496. */
  1497. void QCPLayerable::wheelEvent(QWheelEvent *event)
  1498. {
  1499. event->ignore();
  1500. }
  1501. /* end of 'src/layer.cpp' */
  1502. /* including file 'src/axis/range.cpp' */
  1503. /* modified 2021-03-29T02:30:44, size 12221 */
  1504. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1505. //////////////////// QCPRange
  1506. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1507. /*! \class QCPRange
  1508. \brief Represents the range an axis is encompassing.
  1509. contains a \a lower and \a upper double value and provides convenience input, output and
  1510. modification functions.
  1511. \see QCPAxis::setRange
  1512. */
  1513. /* start of documentation of inline functions */
  1514. /*! \fn double QCPRange::size() const
  1515. Returns the size of the range, i.e. \a upper-\a lower
  1516. */
  1517. /*! \fn double QCPRange::center() const
  1518. Returns the center of the range, i.e. (\a upper+\a lower)*0.5
  1519. */
  1520. /*! \fn void QCPRange::normalize()
  1521. Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values are
  1522. swapped.
  1523. */
  1524. /*! \fn bool QCPRange::contains(double value) const
  1525. Returns true when \a value lies within or exactly on the borders of the range.
  1526. */
  1527. /*! \fn QCPRange &QCPRange::operator+=(const double& value)
  1528. Adds \a value to both boundaries of the range.
  1529. */
  1530. /*! \fn QCPRange &QCPRange::operator-=(const double& value)
  1531. Subtracts \a value from both boundaries of the range.
  1532. */
  1533. /*! \fn QCPRange &QCPRange::operator*=(const double& value)
  1534. Multiplies both boundaries of the range by \a value.
  1535. */
  1536. /*! \fn QCPRange &QCPRange::operator/=(const double& value)
  1537. Divides both boundaries of the range by \a value.
  1538. */
  1539. /* end of documentation of inline functions */
  1540. /*!
  1541. Minimum range size (\a upper - \a lower) the range changing functions will accept. Smaller
  1542. intervals would cause errors due to the 11-bit exponent of double precision numbers,
  1543. corresponding to a minimum magnitude of roughly 1e-308.
  1544. \warning Do not use this constant to indicate "arbitrarily small" values in plotting logic (as
  1545. values that will appear in the plot)! It is intended only as a bound to compare against, e.g. to
  1546. prevent axis ranges from obtaining underflowing ranges.
  1547. \see validRange, maxRange
  1548. */
  1549. const double QCPRange::minRange = 1e-280;
  1550. /*!
  1551. Maximum values (negative and positive) the range will accept in range-changing functions.
  1552. Larger absolute values would cause errors due to the 11-bit exponent of double precision numbers,
  1553. corresponding to a maximum magnitude of roughly 1e308.
  1554. \warning Do not use this constant to indicate "arbitrarily large" values in plotting logic (as
  1555. values that will appear in the plot)! It is intended only as a bound to compare against, e.g. to
  1556. prevent axis ranges from obtaining overflowing ranges.
  1557. \see validRange, minRange
  1558. */
  1559. const double QCPRange::maxRange = 1e250;
  1560. /*!
  1561. Constructs a range with \a lower and \a upper set to zero.
  1562. */
  1563. QCPRange::QCPRange() :
  1564. lower(0),
  1565. upper(0)
  1566. {
  1567. }
  1568. /*! \overload
  1569. Constructs a range with the specified \a lower and \a upper values.
  1570. The resulting range will be normalized (see \ref normalize), so if \a lower is not numerically
  1571. smaller than \a upper, they will be swapped.
  1572. */
  1573. QCPRange::QCPRange(double lower, double upper) :
  1574. lower(lower),
  1575. upper(upper)
  1576. {
  1577. normalize();
  1578. }
  1579. /*! \overload
  1580. Expands this range such that \a otherRange is contained in the new range. It is assumed that both
  1581. this range and \a otherRange are normalized (see \ref normalize).
  1582. If this range contains NaN as lower or upper bound, it will be replaced by the respective bound
  1583. of \a otherRange.
  1584. If \a otherRange is already inside the current range, this function does nothing.
  1585. \see expanded
  1586. */
  1587. void QCPRange::expand(const QCPRange &otherRange)
  1588. {
  1589. if (lower > otherRange.lower || qIsNaN(lower))
  1590. lower = otherRange.lower;
  1591. if (upper < otherRange.upper || qIsNaN(upper))
  1592. upper = otherRange.upper;
  1593. }
  1594. /*! \overload
  1595. Expands this range such that \a includeCoord is contained in the new range. It is assumed that
  1596. this range is normalized (see \ref normalize).
  1597. If this range contains NaN as lower or upper bound, the respective bound will be set to \a
  1598. includeCoord.
  1599. If \a includeCoord is already inside the current range, this function does nothing.
  1600. \see expand
  1601. */
  1602. void QCPRange::expand(double includeCoord)
  1603. {
  1604. if (lower > includeCoord || qIsNaN(lower))
  1605. lower = includeCoord;
  1606. if (upper < includeCoord || qIsNaN(upper))
  1607. upper = includeCoord;
  1608. }
  1609. /*! \overload
  1610. Returns an expanded range that contains this and \a otherRange. It is assumed that both this
  1611. range and \a otherRange are normalized (see \ref normalize).
  1612. If this range contains NaN as lower or upper bound, the returned range's bound will be taken from
  1613. \a otherRange.
  1614. \see expand
  1615. */
  1616. QCPRange QCPRange::expanded(const QCPRange &otherRange) const
  1617. {
  1618. QCPRange result = *this;
  1619. result.expand(otherRange);
  1620. return result;
  1621. }
  1622. /*! \overload
  1623. Returns an expanded range that includes the specified \a includeCoord. It is assumed that this
  1624. range is normalized (see \ref normalize).
  1625. If this range contains NaN as lower or upper bound, the returned range's bound will be set to \a
  1626. includeCoord.
  1627. \see expand
  1628. */
  1629. QCPRange QCPRange::expanded(double includeCoord) const
  1630. {
  1631. QCPRange result = *this;
  1632. result.expand(includeCoord);
  1633. return result;
  1634. }
  1635. /*!
  1636. Returns this range, possibly modified to not exceed the bounds provided as \a lowerBound and \a
  1637. upperBound. If possible, the size of the current range is preserved in the process.
  1638. If the range shall only be bounded at the lower side, you can set \a upperBound to \ref
  1639. QCPRange::maxRange. If it shall only be bounded at the upper side, set \a lowerBound to -\ref
  1640. QCPRange::maxRange.
  1641. */
  1642. QCPRange QCPRange::bounded(double lowerBound, double upperBound) const
  1643. {
  1644. if (lowerBound > upperBound)
  1645. qSwap(lowerBound, upperBound);
  1646. QCPRange result(lower, upper);
  1647. if (result.lower < lowerBound)
  1648. {
  1649. result.lower = lowerBound;
  1650. result.upper = lowerBound + size();
  1651. if (result.upper > upperBound || qFuzzyCompare(size(), upperBound-lowerBound))
  1652. result.upper = upperBound;
  1653. } else if (result.upper > upperBound)
  1654. {
  1655. result.upper = upperBound;
  1656. result.lower = upperBound - size();
  1657. if (result.lower < lowerBound || qFuzzyCompare(size(), upperBound-lowerBound))
  1658. result.lower = lowerBound;
  1659. }
  1660. return result;
  1661. }
  1662. /*!
  1663. Returns a sanitized version of the range. Sanitized means for logarithmic scales, that
  1664. the range won't span the positive and negative sign domain, i.e. contain zero. Further
  1665. \a lower will always be numerically smaller (or equal) to \a upper.
  1666. If the original range does span positive and negative sign domains or contains zero,
  1667. the returned range will try to approximate the original range as good as possible.
  1668. If the positive interval of the original range is wider than the negative interval, the
  1669. returned range will only contain the positive interval, with lower bound set to \a rangeFac or
  1670. \a rangeFac *\a upper, whichever is closer to zero. Same procedure is used if the negative interval
  1671. is wider than the positive interval, this time by changing the \a upper bound.
  1672. */
  1673. QCPRange QCPRange::sanitizedForLogScale() const
  1674. {
  1675. double rangeFac = 1e-3;
  1676. QCPRange sanitizedRange(lower, upper);
  1677. sanitizedRange.normalize();
  1678. // can't have range spanning negative and positive values in log plot, so change range to fix it
  1679. //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1))
  1680. if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0)
  1681. {
  1682. // case lower is 0
  1683. if (rangeFac < sanitizedRange.upper*rangeFac)
  1684. sanitizedRange.lower = rangeFac;
  1685. else
  1686. sanitizedRange.lower = sanitizedRange.upper*rangeFac;
  1687. } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1))
  1688. else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0)
  1689. {
  1690. // case upper is 0
  1691. if (-rangeFac > sanitizedRange.lower*rangeFac)
  1692. sanitizedRange.upper = -rangeFac;
  1693. else
  1694. sanitizedRange.upper = sanitizedRange.lower*rangeFac;
  1695. } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0)
  1696. {
  1697. // find out whether negative or positive interval is wider to decide which sign domain will be chosen
  1698. if (-sanitizedRange.lower > sanitizedRange.upper)
  1699. {
  1700. // negative is wider, do same as in case upper is 0
  1701. if (-rangeFac > sanitizedRange.lower*rangeFac)
  1702. sanitizedRange.upper = -rangeFac;
  1703. else
  1704. sanitizedRange.upper = sanitizedRange.lower*rangeFac;
  1705. } else
  1706. {
  1707. // positive is wider, do same as in case lower is 0
  1708. if (rangeFac < sanitizedRange.upper*rangeFac)
  1709. sanitizedRange.lower = rangeFac;
  1710. else
  1711. sanitizedRange.lower = sanitizedRange.upper*rangeFac;
  1712. }
  1713. }
  1714. // due to normalization, case lower>0 && upper<0 should never occur, because that implies upper<lower
  1715. return sanitizedRange;
  1716. }
  1717. /*!
  1718. Returns a sanitized version of the range. Sanitized means for linear scales, that
  1719. \a lower will always be numerically smaller (or equal) to \a upper.
  1720. */
  1721. QCPRange QCPRange::sanitizedForLinScale() const
  1722. {
  1723. QCPRange sanitizedRange(lower, upper);
  1724. sanitizedRange.normalize();
  1725. return sanitizedRange;
  1726. }
  1727. /*!
  1728. Checks, whether the specified range is within valid bounds, which are defined
  1729. as QCPRange::maxRange and QCPRange::minRange.
  1730. A valid range means:
  1731. \li range bounds within -maxRange and maxRange
  1732. \li range size above minRange
  1733. \li range size below maxRange
  1734. */
  1735. bool QCPRange::validRange(double lower, double upper)
  1736. {
  1737. return (lower > -maxRange &&
  1738. upper < maxRange &&
  1739. qAbs(lower-upper) > minRange &&
  1740. qAbs(lower-upper) < maxRange &&
  1741. !(lower > 0 && qIsInf(upper/lower)) &&
  1742. !(upper < 0 && qIsInf(lower/upper)));
  1743. }
  1744. /*!
  1745. \overload
  1746. Checks, whether the specified range is within valid bounds, which are defined
  1747. as QCPRange::maxRange and QCPRange::minRange.
  1748. A valid range means:
  1749. \li range bounds within -maxRange and maxRange
  1750. \li range size above minRange
  1751. \li range size below maxRange
  1752. */
  1753. bool QCPRange::validRange(const QCPRange &range)
  1754. {
  1755. return (range.lower > -maxRange &&
  1756. range.upper < maxRange &&
  1757. qAbs(range.lower-range.upper) > minRange &&
  1758. qAbs(range.lower-range.upper) < maxRange &&
  1759. !(range.lower > 0 && qIsInf(range.upper/range.lower)) &&
  1760. !(range.upper < 0 && qIsInf(range.lower/range.upper)));
  1761. }
  1762. /* end of 'src/axis/range.cpp' */
  1763. /* including file 'src/selection.cpp' */
  1764. /* modified 2021-03-29T02:30:44, size 21837 */
  1765. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1766. //////////////////// QCPDataRange
  1767. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1768. /*! \class QCPDataRange
  1769. \brief Describes a data range given by begin and end index
  1770. QCPDataRange holds two integers describing the begin (\ref setBegin) and end (\ref setEnd) index
  1771. of a contiguous set of data points. The \a end index corresponds to the data point just after the
  1772. last data point of the data range, like in standard iterators.
  1773. Data Ranges are not bound to a certain plottable, thus they can be freely exchanged, created and
  1774. modified. If a non-contiguous data set shall be described, the class \ref QCPDataSelection is
  1775. used, which holds and manages multiple instances of \ref QCPDataRange. In most situations, \ref
  1776. QCPDataSelection is thus used.
  1777. Both \ref QCPDataRange and \ref QCPDataSelection offer convenience methods to work with them,
  1778. e.g. \ref bounded, \ref expanded, \ref intersects, \ref intersection, \ref adjusted, \ref
  1779. contains. Further, addition and subtraction operators (defined in \ref QCPDataSelection) can be
  1780. used to join/subtract data ranges and data selections (or mixtures), to retrieve a corresponding
  1781. \ref QCPDataSelection.
  1782. %QCustomPlot's \ref dataselection "data selection mechanism" is based on \ref QCPDataSelection and
  1783. QCPDataRange.
  1784. \note Do not confuse \ref QCPDataRange with \ref QCPRange. A \ref QCPRange describes an interval
  1785. in floating point plot coordinates, e.g. the current axis range.
  1786. */
  1787. /* start documentation of inline functions */
  1788. /*! \fn int QCPDataRange::size() const
  1789. Returns the number of data points described by this data range. This is equal to the end index
  1790. minus the begin index.
  1791. \see length
  1792. */
  1793. /*! \fn int QCPDataRange::length() const
  1794. Returns the number of data points described by this data range. Equivalent to \ref size.
  1795. */
  1796. /*! \fn void QCPDataRange::setBegin(int begin)
  1797. Sets the begin of this data range. The \a begin index points to the first data point that is part
  1798. of the data range.
  1799. No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
  1800. \see setEnd
  1801. */
  1802. /*! \fn void QCPDataRange::setEnd(int end)
  1803. Sets the end of this data range. The \a end index points to the data point just after the last
  1804. data point that is part of the data range.
  1805. No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
  1806. \see setBegin
  1807. */
  1808. /*! \fn bool QCPDataRange::isValid() const
  1809. Returns whether this range is valid. A valid range has a begin index greater or equal to 0, and
  1810. an end index greater or equal to the begin index.
  1811. \note Invalid ranges should be avoided and are never the result of any of QCustomPlot's methods
  1812. (unless they are themselves fed with invalid ranges). Do not pass invalid ranges to QCustomPlot's
  1813. methods. The invalid range is not inherently prevented in QCPDataRange, to allow temporary
  1814. invalid begin/end values while manipulating the range. An invalid range is not necessarily empty
  1815. (\ref isEmpty), since its \ref length can be negative and thus non-zero.
  1816. */
  1817. /*! \fn bool QCPDataRange::isEmpty() const
  1818. Returns whether this range is empty, i.e. whether its begin index equals its end index.
  1819. \see size, length
  1820. */
  1821. /*! \fn QCPDataRange QCPDataRange::adjusted(int changeBegin, int changeEnd) const
  1822. Returns a data range where \a changeBegin and \a changeEnd were added to the begin and end
  1823. indices, respectively.
  1824. */
  1825. /* end documentation of inline functions */
  1826. /*!
  1827. Creates an empty QCPDataRange, with begin and end set to 0.
  1828. */
  1829. QCPDataRange::QCPDataRange() :
  1830. mBegin(0),
  1831. mEnd(0)
  1832. {
  1833. }
  1834. /*!
  1835. Creates a QCPDataRange, initialized with the specified \a begin and \a end.
  1836. No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
  1837. */
  1838. QCPDataRange::QCPDataRange(int begin, int end) :
  1839. mBegin(begin),
  1840. mEnd(end)
  1841. {
  1842. }
  1843. /*!
  1844. Returns a data range that matches this data range, except that parts exceeding \a other are
  1845. excluded.
  1846. This method is very similar to \ref intersection, with one distinction: If this range and the \a
  1847. other range share no intersection, the returned data range will be empty with begin and end set
  1848. to the respective boundary side of \a other, at which this range is residing. (\ref intersection
  1849. would just return a range with begin and end set to 0.)
  1850. */
  1851. QCPDataRange QCPDataRange::bounded(const QCPDataRange &other) const
  1852. {
  1853. QCPDataRange result(intersection(other));
  1854. if (result.isEmpty()) // no intersection, preserve respective bounding side of otherRange as both begin and end of return value
  1855. {
  1856. if (mEnd <= other.mBegin)
  1857. result = QCPDataRange(other.mBegin, other.mBegin);
  1858. else
  1859. result = QCPDataRange(other.mEnd, other.mEnd);
  1860. }
  1861. return result;
  1862. }
  1863. /*!
  1864. Returns a data range that contains both this data range as well as \a other.
  1865. */
  1866. QCPDataRange QCPDataRange::expanded(const QCPDataRange &other) const
  1867. {
  1868. return {qMin(mBegin, other.mBegin), qMax(mEnd, other.mEnd)};
  1869. }
  1870. /*!
  1871. Returns the data range which is contained in both this data range and \a other.
  1872. This method is very similar to \ref bounded, with one distinction: If this range and the \a other
  1873. range share no intersection, the returned data range will be empty with begin and end set to 0.
  1874. (\ref bounded would return a range with begin and end set to one of the boundaries of \a other,
  1875. depending on which side this range is on.)
  1876. \see QCPDataSelection::intersection
  1877. */
  1878. QCPDataRange QCPDataRange::intersection(const QCPDataRange &other) const
  1879. {
  1880. QCPDataRange result(qMax(mBegin, other.mBegin), qMin(mEnd, other.mEnd));
  1881. if (result.isValid())
  1882. return result;
  1883. else
  1884. return {};
  1885. }
  1886. /*!
  1887. Returns whether this data range and \a other share common data points.
  1888. \see intersection, contains
  1889. */
  1890. bool QCPDataRange::intersects(const QCPDataRange &other) const
  1891. {
  1892. return !( (mBegin > other.mBegin && mBegin >= other.mEnd) ||
  1893. (mEnd <= other.mBegin && mEnd < other.mEnd) );
  1894. }
  1895. /*!
  1896. Returns whether all data points of \a other are also contained inside this data range.
  1897. \see intersects
  1898. */
  1899. bool QCPDataRange::contains(const QCPDataRange &other) const
  1900. {
  1901. return mBegin <= other.mBegin && mEnd >= other.mEnd;
  1902. }
  1903. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1904. //////////////////// QCPDataSelection
  1905. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1906. /*! \class QCPDataSelection
  1907. \brief Describes a data set by holding multiple QCPDataRange instances
  1908. QCPDataSelection manages multiple instances of QCPDataRange in order to represent any (possibly
  1909. disjoint) set of data selection.
  1910. The data selection can be modified with addition and subtraction operators which take
  1911. QCPDataSelection and QCPDataRange instances, as well as methods such as \ref addDataRange and
  1912. \ref clear. Read access is provided by \ref dataRange, \ref dataRanges, \ref dataRangeCount, etc.
  1913. The method \ref simplify is used to join directly adjacent or even overlapping QCPDataRange
  1914. instances. QCPDataSelection automatically simplifies when using the addition/subtraction
  1915. operators. The only case when \ref simplify is left to the user, is when calling \ref
  1916. addDataRange, with the parameter \a simplify explicitly set to false. This is useful if many data
  1917. ranges will be added to the selection successively and the overhead for simplifying after each
  1918. iteration shall be avoided. In this case, you should make sure to call \ref simplify after
  1919. completing the operation.
  1920. Use \ref enforceType to bring the data selection into a state complying with the constraints for
  1921. selections defined in \ref QCP::SelectionType.
  1922. %QCustomPlot's \ref dataselection "data selection mechanism" is based on QCPDataSelection and
  1923. QCPDataRange.
  1924. \section qcpdataselection-iterating Iterating over a data selection
  1925. As an example, the following code snippet calculates the average value of a graph's data
  1926. \ref QCPAbstractPlottable::selection "selection":
  1927. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpdataselection-iterating-1
  1928. */
  1929. /* start documentation of inline functions */
  1930. /*! \fn int QCPDataSelection::dataRangeCount() const
  1931. Returns the number of ranges that make up the data selection. The ranges can be accessed by \ref
  1932. dataRange via their index.
  1933. \see dataRange, dataPointCount
  1934. */
  1935. /*! \fn QList<QCPDataRange> QCPDataSelection::dataRanges() const
  1936. Returns all data ranges that make up the data selection. If the data selection is simplified (the
  1937. usual state of the selection, see \ref simplify), the ranges are sorted by ascending data point
  1938. index.
  1939. \see dataRange
  1940. */
  1941. /*! \fn bool QCPDataSelection::isEmpty() const
  1942. Returns true if there are no data ranges, and thus no data points, in this QCPDataSelection
  1943. instance.
  1944. \see dataRangeCount
  1945. */
  1946. /* end documentation of inline functions */
  1947. /*!
  1948. Creates an empty QCPDataSelection.
  1949. */
  1950. QCPDataSelection::QCPDataSelection()
  1951. {
  1952. }
  1953. /*!
  1954. Creates a QCPDataSelection containing the provided \a range.
  1955. */
  1956. QCPDataSelection::QCPDataSelection(const QCPDataRange &range)
  1957. {
  1958. mDataRanges.append(range);
  1959. }
  1960. /*!
  1961. Returns true if this selection is identical (contains the same data ranges with the same begin
  1962. and end indices) to \a other.
  1963. Note that both data selections must be in simplified state (the usual state of the selection, see
  1964. \ref simplify) for this operator to return correct results.
  1965. */
  1966. bool QCPDataSelection::operator==(const QCPDataSelection &other) const
  1967. {
  1968. if (mDataRanges.size() != other.mDataRanges.size())
  1969. return false;
  1970. for (int i=0; i<mDataRanges.size(); ++i)
  1971. {
  1972. if (mDataRanges.at(i) != other.mDataRanges.at(i))
  1973. return false;
  1974. }
  1975. return true;
  1976. }
  1977. /*!
  1978. Adds the data selection of \a other to this data selection, and then simplifies this data
  1979. selection (see \ref simplify).
  1980. */
  1981. QCPDataSelection &QCPDataSelection::operator+=(const QCPDataSelection &other)
  1982. {
  1983. mDataRanges << other.mDataRanges;
  1984. simplify();
  1985. return *this;
  1986. }
  1987. /*!
  1988. Adds the data range \a other to this data selection, and then simplifies this data selection (see
  1989. \ref simplify).
  1990. */
  1991. QCPDataSelection &QCPDataSelection::operator+=(const QCPDataRange &other)
  1992. {
  1993. addDataRange(other);
  1994. return *this;
  1995. }
  1996. /*!
  1997. Removes all data point indices that are described by \a other from this data selection.
  1998. */
  1999. QCPDataSelection &QCPDataSelection::operator-=(const QCPDataSelection &other)
  2000. {
  2001. for (int i=0; i<other.dataRangeCount(); ++i)
  2002. *this -= other.dataRange(i);
  2003. return *this;
  2004. }
  2005. /*!
  2006. Removes all data point indices that are described by \a other from this data selection.
  2007. */
  2008. QCPDataSelection &QCPDataSelection::operator-=(const QCPDataRange &other)
  2009. {
  2010. if (other.isEmpty() || isEmpty())
  2011. return *this;
  2012. simplify();
  2013. int i=0;
  2014. while (i < mDataRanges.size())
  2015. {
  2016. const int thisBegin = mDataRanges.at(i).begin();
  2017. const int thisEnd = mDataRanges.at(i).end();
  2018. if (thisBegin >= other.end())
  2019. break; // since data ranges are sorted after the simplify() call, no ranges which contain other will come after this
  2020. if (thisEnd > other.begin()) // ranges which don't fulfill this are entirely before other and can be ignored
  2021. {
  2022. if (thisBegin >= other.begin()) // range leading segment is encompassed
  2023. {
  2024. if (thisEnd <= other.end()) // range fully encompassed, remove completely
  2025. {
  2026. mDataRanges.removeAt(i);
  2027. continue;
  2028. } else // only leading segment is encompassed, trim accordingly
  2029. mDataRanges[i].setBegin(other.end());
  2030. } else // leading segment is not encompassed
  2031. {
  2032. if (thisEnd <= other.end()) // only trailing segment is encompassed, trim accordingly
  2033. {
  2034. mDataRanges[i].setEnd(other.begin());
  2035. } else // other lies inside this range, so split range
  2036. {
  2037. mDataRanges[i].setEnd(other.begin());
  2038. mDataRanges.insert(i+1, QCPDataRange(other.end(), thisEnd));
  2039. break; // since data ranges are sorted (and don't overlap) after simplify() call, we're done here
  2040. }
  2041. }
  2042. }
  2043. ++i;
  2044. }
  2045. return *this;
  2046. }
  2047. /*!
  2048. Returns the total number of data points contained in all data ranges that make up this data
  2049. selection.
  2050. */
  2051. int QCPDataSelection::dataPointCount() const
  2052. {
  2053. int result = 0;
  2054. foreach (QCPDataRange dataRange, mDataRanges)
  2055. result += dataRange.length();
  2056. return result;
  2057. }
  2058. /*!
  2059. Returns the data range with the specified \a index.
  2060. If the data selection is simplified (the usual state of the selection, see \ref simplify), the
  2061. ranges are sorted by ascending data point index.
  2062. \see dataRangeCount
  2063. */
  2064. QCPDataRange QCPDataSelection::dataRange(int index) const
  2065. {
  2066. if (index >= 0 && index < mDataRanges.size())
  2067. {
  2068. return mDataRanges.at(index);
  2069. } else
  2070. {
  2071. qDebug() << Q_FUNC_INFO << "index out of range:" << index;
  2072. return {};
  2073. }
  2074. }
  2075. /*!
  2076. Returns a \ref QCPDataRange which spans the entire data selection, including possible
  2077. intermediate segments which are not part of the original data selection.
  2078. */
  2079. QCPDataRange QCPDataSelection::span() const
  2080. {
  2081. if (isEmpty())
  2082. return {};
  2083. else
  2084. return {mDataRanges.first().begin(), mDataRanges.last().end()};
  2085. }
  2086. /*!
  2087. Adds the given \a dataRange to this data selection. This is equivalent to the += operator but
  2088. allows disabling immediate simplification by setting \a simplify to false. This can improve
  2089. performance if adding a very large amount of data ranges successively. In this case, make sure to
  2090. call \ref simplify manually, after the operation.
  2091. */
  2092. void QCPDataSelection::addDataRange(const QCPDataRange &dataRange, bool simplify)
  2093. {
  2094. mDataRanges.append(dataRange);
  2095. if (simplify)
  2096. this->simplify();
  2097. }
  2098. /*!
  2099. Removes all data ranges. The data selection then contains no data points.
  2100. \ref isEmpty
  2101. */
  2102. void QCPDataSelection::clear()
  2103. {
  2104. mDataRanges.clear();
  2105. }
  2106. /*!
  2107. Sorts all data ranges by range begin index in ascending order, and then joins directly adjacent
  2108. or overlapping ranges. This can reduce the number of individual data ranges in the selection, and
  2109. prevents possible double-counting when iterating over the data points held by the data ranges.
  2110. This method is automatically called when using the addition/subtraction operators. The only case
  2111. when \ref simplify is left to the user, is when calling \ref addDataRange, with the parameter \a
  2112. simplify explicitly set to false.
  2113. */
  2114. void QCPDataSelection::simplify()
  2115. {
  2116. // remove any empty ranges:
  2117. for (int i=mDataRanges.size()-1; i>=0; --i)
  2118. {
  2119. if (mDataRanges.at(i).isEmpty())
  2120. mDataRanges.removeAt(i);
  2121. }
  2122. if (mDataRanges.isEmpty())
  2123. return;
  2124. // sort ranges by starting value, ascending:
  2125. std::sort(mDataRanges.begin(), mDataRanges.end(), lessThanDataRangeBegin);
  2126. // join overlapping/contiguous ranges:
  2127. int i = 1;
  2128. while (i < mDataRanges.size())
  2129. {
  2130. 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
  2131. {
  2132. mDataRanges[i-1].setEnd(qMax(mDataRanges.at(i-1).end(), mDataRanges.at(i).end()));
  2133. mDataRanges.removeAt(i);
  2134. } else
  2135. ++i;
  2136. }
  2137. }
  2138. /*!
  2139. Makes sure this data selection conforms to the specified \a type selection type. Before the type
  2140. is enforced, \ref simplify is called.
  2141. Depending on \a type, enforcing means adding new data points that were previously not part of the
  2142. selection, or removing data points from the selection. If the current selection already conforms
  2143. to \a type, the data selection is not changed.
  2144. \see QCP::SelectionType
  2145. */
  2146. void QCPDataSelection::enforceType(QCP::SelectionType type)
  2147. {
  2148. simplify();
  2149. switch (type)
  2150. {
  2151. case QCP::stNone:
  2152. {
  2153. mDataRanges.clear();
  2154. break;
  2155. }
  2156. case QCP::stWhole:
  2157. {
  2158. // whole selection isn't defined by data range, so don't change anything (is handled in plottable methods)
  2159. break;
  2160. }
  2161. case QCP::stSingleData:
  2162. {
  2163. // reduce all data ranges to the single first data point:
  2164. if (!mDataRanges.isEmpty())
  2165. {
  2166. if (mDataRanges.size() > 1)
  2167. mDataRanges = QList<QCPDataRange>() << mDataRanges.first();
  2168. if (mDataRanges.first().length() > 1)
  2169. mDataRanges.first().setEnd(mDataRanges.first().begin()+1);
  2170. }
  2171. break;
  2172. }
  2173. case QCP::stDataRange:
  2174. {
  2175. if (!isEmpty())
  2176. mDataRanges = QList<QCPDataRange>() << span();
  2177. break;
  2178. }
  2179. case QCP::stMultipleDataRanges:
  2180. {
  2181. // this is the selection type that allows all concievable combinations of ranges, so do nothing
  2182. break;
  2183. }
  2184. }
  2185. }
  2186. /*!
  2187. Returns true if the data selection \a other is contained entirely in this data selection, i.e.
  2188. all data point indices that are in \a other are also in this data selection.
  2189. \see QCPDataRange::contains
  2190. */
  2191. bool QCPDataSelection::contains(const QCPDataSelection &other) const
  2192. {
  2193. if (other.isEmpty()) return false;
  2194. int otherIndex = 0;
  2195. int thisIndex = 0;
  2196. while (thisIndex < mDataRanges.size() && otherIndex < other.mDataRanges.size())
  2197. {
  2198. if (mDataRanges.at(thisIndex).contains(other.mDataRanges.at(otherIndex)))
  2199. ++otherIndex;
  2200. else
  2201. ++thisIndex;
  2202. }
  2203. 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
  2204. }
  2205. /*!
  2206. Returns a data selection containing the points which are both in this data selection and in the
  2207. data range \a other.
  2208. A common use case is to limit an unknown data selection to the valid range of a data container,
  2209. using \ref QCPDataContainer::dataRange as \a other. One can then safely iterate over the returned
  2210. data selection without exceeding the data container's bounds.
  2211. */
  2212. QCPDataSelection QCPDataSelection::intersection(const QCPDataRange &other) const
  2213. {
  2214. QCPDataSelection result;
  2215. foreach (QCPDataRange dataRange, mDataRanges)
  2216. result.addDataRange(dataRange.intersection(other), false);
  2217. result.simplify();
  2218. return result;
  2219. }
  2220. /*!
  2221. Returns a data selection containing the points which are both in this data selection and in the
  2222. data selection \a other.
  2223. */
  2224. QCPDataSelection QCPDataSelection::intersection(const QCPDataSelection &other) const
  2225. {
  2226. QCPDataSelection result;
  2227. for (int i=0; i<other.dataRangeCount(); ++i)
  2228. result += intersection(other.dataRange(i));
  2229. result.simplify();
  2230. return result;
  2231. }
  2232. /*!
  2233. Returns a data selection which is the exact inverse of this data selection, with \a outerRange
  2234. defining the base range on which to invert. If \a outerRange is smaller than the \ref span of
  2235. this data selection, it is expanded accordingly.
  2236. For example, this method can be used to retrieve all unselected segments by setting \a outerRange
  2237. to the full data range of the plottable, and calling this method on a data selection holding the
  2238. selected segments.
  2239. */
  2240. QCPDataSelection QCPDataSelection::inverse(const QCPDataRange &outerRange) const
  2241. {
  2242. if (isEmpty())
  2243. return QCPDataSelection(outerRange);
  2244. QCPDataRange fullRange = outerRange.expanded(span());
  2245. QCPDataSelection result;
  2246. // first unselected segment:
  2247. if (mDataRanges.first().begin() != fullRange.begin())
  2248. result.addDataRange(QCPDataRange(fullRange.begin(), mDataRanges.first().begin()), false);
  2249. // intermediate unselected segments:
  2250. for (int i=1; i<mDataRanges.size(); ++i)
  2251. result.addDataRange(QCPDataRange(mDataRanges.at(i-1).end(), mDataRanges.at(i).begin()), false);
  2252. // last unselected segment:
  2253. if (mDataRanges.last().end() != fullRange.end())
  2254. result.addDataRange(QCPDataRange(mDataRanges.last().end(), fullRange.end()), false);
  2255. result.simplify();
  2256. return result;
  2257. }
  2258. /* end of 'src/selection.cpp' */
  2259. /* including file 'src/selectionrect.cpp' */
  2260. /* modified 2021-03-29T02:30:44, size 9215 */
  2261. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2262. //////////////////// QCPSelectionRect
  2263. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2264. /*! \class QCPSelectionRect
  2265. \brief Provides rect/rubber-band data selection and range zoom interaction
  2266. QCPSelectionRect is used by QCustomPlot when the \ref QCustomPlot::setSelectionRectMode is not
  2267. \ref QCP::srmNone. When the user drags the mouse across the plot, the current selection rect
  2268. instance (\ref QCustomPlot::setSelectionRect) is forwarded these events and makes sure an
  2269. according rect shape is drawn. At the begin, during, and after completion of the interaction, it
  2270. emits the corresponding signals \ref started, \ref changed, \ref canceled, and \ref accepted.
  2271. The QCustomPlot instance connects own slots to the current selection rect instance, in order to
  2272. react to an accepted selection rect interaction accordingly.
  2273. \ref isActive can be used to check whether the selection rect is currently active. An ongoing
  2274. selection interaction can be cancelled programmatically via calling \ref cancel at any time.
  2275. The appearance of the selection rect can be controlled via \ref setPen and \ref setBrush.
  2276. If you wish to provide custom behaviour, e.g. a different visual representation of the selection
  2277. rect (\ref QCPSelectionRect::draw), you can subclass QCPSelectionRect and pass an instance of
  2278. your subclass to \ref QCustomPlot::setSelectionRect.
  2279. */
  2280. /* start of documentation of inline functions */
  2281. /*! \fn bool QCPSelectionRect::isActive() const
  2282. Returns true if there is currently a selection going on, i.e. the user has started dragging a
  2283. selection rect, but hasn't released the mouse button yet.
  2284. \see cancel
  2285. */
  2286. /* end of documentation of inline functions */
  2287. /* start documentation of signals */
  2288. /*! \fn void QCPSelectionRect::started(QMouseEvent *event);
  2289. This signal is emitted when a selection rect interaction was initiated, i.e. the user just
  2290. started dragging the selection rect with the mouse.
  2291. */
  2292. /*! \fn void QCPSelectionRect::changed(const QRect &rect, QMouseEvent *event);
  2293. This signal is emitted while the selection rect interaction is ongoing and the \a rect has
  2294. changed its size due to the user moving the mouse.
  2295. Note that \a rect may have a negative width or height, if the selection is being dragged to the
  2296. upper or left side of the selection rect origin.
  2297. */
  2298. /*! \fn void QCPSelectionRect::canceled(const QRect &rect, QInputEvent *event);
  2299. This signal is emitted when the selection interaction was cancelled. Note that \a event is \c
  2300. nullptr if the selection interaction was cancelled programmatically, by a call to \ref cancel.
  2301. The user may cancel the selection interaction by pressing the escape key. In this case, \a event
  2302. holds the respective input event.
  2303. Note that \a rect may have a negative width or height, if the selection is being dragged to the
  2304. upper or left side of the selection rect origin.
  2305. */
  2306. /*! \fn void QCPSelectionRect::accepted(const QRect &rect, QMouseEvent *event);
  2307. This signal is emitted when the selection interaction was completed by the user releasing the
  2308. mouse button.
  2309. Note that \a rect may have a negative width or height, if the selection is being dragged to the
  2310. upper or left side of the selection rect origin.
  2311. */
  2312. /* end documentation of signals */
  2313. /*!
  2314. Creates a new QCPSelectionRect instance. To make QCustomPlot use the selection rect instance,
  2315. pass it to \ref QCustomPlot::setSelectionRect. \a parentPlot should be set to the same
  2316. QCustomPlot widget.
  2317. */
  2318. QCPSelectionRect::QCPSelectionRect(QCustomPlot *parentPlot) :
  2319. QCPLayerable(parentPlot),
  2320. mPen(QBrush(Qt::gray), 0, Qt::DashLine),
  2321. mBrush(Qt::NoBrush),
  2322. mActive(false)
  2323. {
  2324. }
  2325. QCPSelectionRect::~QCPSelectionRect()
  2326. {
  2327. cancel();
  2328. }
  2329. /*!
  2330. A convenience function which returns the coordinate range of the provided \a axis, that this
  2331. selection rect currently encompasses.
  2332. */
  2333. QCPRange QCPSelectionRect::range(const QCPAxis *axis) const
  2334. {
  2335. if (axis)
  2336. {
  2337. if (axis->orientation() == Qt::Horizontal)
  2338. return {axis->pixelToCoord(mRect.left()), axis->pixelToCoord(mRect.left()+mRect.width())};
  2339. else
  2340. return {axis->pixelToCoord(mRect.top()+mRect.height()), axis->pixelToCoord(mRect.top())};
  2341. } else
  2342. {
  2343. qDebug() << Q_FUNC_INFO << "called with axis zero";
  2344. return {};
  2345. }
  2346. }
  2347. /*!
  2348. Sets the pen that will be used to draw the selection rect outline.
  2349. \see setBrush
  2350. */
  2351. void QCPSelectionRect::setPen(const QPen &pen)
  2352. {
  2353. mPen = pen;
  2354. }
  2355. /*!
  2356. Sets the brush that will be used to fill the selection rect. By default the selection rect is not
  2357. filled, i.e. \a brush is <tt>Qt::NoBrush</tt>.
  2358. \see setPen
  2359. */
  2360. void QCPSelectionRect::setBrush(const QBrush &brush)
  2361. {
  2362. mBrush = brush;
  2363. }
  2364. /*!
  2365. If there is currently a selection interaction going on (\ref isActive), the interaction is
  2366. canceled. The selection rect will emit the \ref canceled signal.
  2367. */
  2368. void QCPSelectionRect::cancel()
  2369. {
  2370. if (mActive)
  2371. {
  2372. mActive = false;
  2373. emit canceled(mRect, nullptr);
  2374. }
  2375. }
  2376. /*! \internal
  2377. This method is called by QCustomPlot to indicate that a selection rect interaction was initiated.
  2378. The default implementation sets the selection rect to active, initializes the selection rect
  2379. geometry and emits the \ref started signal.
  2380. */
  2381. void QCPSelectionRect::startSelection(QMouseEvent *event)
  2382. {
  2383. mActive = true;
  2384. mRect = QRect(event->pos(), event->pos());
  2385. emit started(event);
  2386. }
  2387. /*! \internal
  2388. This method is called by QCustomPlot to indicate that an ongoing selection rect interaction needs
  2389. to update its geometry. The default implementation updates the rect and emits the \ref changed
  2390. signal.
  2391. */
  2392. void QCPSelectionRect::moveSelection(QMouseEvent *event)
  2393. {
  2394. mRect.setBottomRight(event->pos());
  2395. emit changed(mRect, event);
  2396. layer()->replot();
  2397. }
  2398. /*! \internal
  2399. This method is called by QCustomPlot to indicate that an ongoing selection rect interaction has
  2400. finished by the user releasing the mouse button. The default implementation deactivates the
  2401. selection rect and emits the \ref accepted signal.
  2402. */
  2403. void QCPSelectionRect::endSelection(QMouseEvent *event)
  2404. {
  2405. mRect.setBottomRight(event->pos());
  2406. mActive = false;
  2407. emit accepted(mRect, event);
  2408. }
  2409. /*! \internal
  2410. This method is called by QCustomPlot when a key has been pressed by the user while the selection
  2411. rect interaction is active. The default implementation allows to \ref cancel the interaction by
  2412. hitting the escape key.
  2413. */
  2414. void QCPSelectionRect::keyPressEvent(QKeyEvent *event)
  2415. {
  2416. if (event->key() == Qt::Key_Escape && mActive)
  2417. {
  2418. mActive = false;
  2419. emit canceled(mRect, event);
  2420. }
  2421. }
  2422. /* inherits documentation from base class */
  2423. void QCPSelectionRect::applyDefaultAntialiasingHint(QCPPainter *painter) const
  2424. {
  2425. applyAntialiasingHint(painter, mAntialiased, QCP::aeOther);
  2426. }
  2427. /*! \internal
  2428. If the selection rect is active (\ref isActive), draws the selection rect defined by \a mRect.
  2429. \seebaseclassmethod
  2430. */
  2431. void QCPSelectionRect::draw(QCPPainter *painter)
  2432. {
  2433. if (mActive)
  2434. {
  2435. painter->setPen(mPen);
  2436. painter->setBrush(mBrush);
  2437. painter->drawRect(mRect);
  2438. }
  2439. }
  2440. /* end of 'src/selectionrect.cpp' */
  2441. /* including file 'src/layout.cpp' */
  2442. /* modified 2021-03-29T02:30:44, size 78863 */
  2443. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2444. //////////////////// QCPMarginGroup
  2445. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2446. /*! \class QCPMarginGroup
  2447. \brief A margin group allows synchronization of margin sides if working with multiple layout elements.
  2448. QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that
  2449. they will all have the same size, based on the largest required margin in the group.
  2450. \n
  2451. \image html QCPMarginGroup.png "Demonstration of QCPMarginGroup"
  2452. \n
  2453. In certain situations it is desirable that margins at specific sides are synchronized across
  2454. layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will
  2455. provide a cleaner look to the user if the left and right margins of the two axis rects are of the
  2456. same size. The left axis of the top axis rect will then be at the same horizontal position as the
  2457. left axis of the lower axis rect, making them appear aligned. The same applies for the right
  2458. axes. This is what QCPMarginGroup makes possible.
  2459. To add/remove a specific side of a layout element to/from a margin group, use the \ref
  2460. QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call
  2461. \ref clear, or just delete the margin group.
  2462. \section QCPMarginGroup-example Example
  2463. First create a margin group:
  2464. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-1
  2465. Then set this group on the layout element sides:
  2466. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-2
  2467. Here, we've used the first two axis rects of the plot and synchronized their left margins with
  2468. each other and their right margins with each other.
  2469. */
  2470. /* start documentation of inline functions */
  2471. /*! \fn QList<QCPLayoutElement*> QCPMarginGroup::elements(QCP::MarginSide side) const
  2472. Returns a list of all layout elements that have their margin \a side associated with this margin
  2473. group.
  2474. */
  2475. /* end documentation of inline functions */
  2476. /*!
  2477. Creates a new QCPMarginGroup instance in \a parentPlot.
  2478. */
  2479. QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) :
  2480. QObject(parentPlot),
  2481. mParentPlot(parentPlot)
  2482. {
  2483. mChildren.insert(QCP::msLeft, QList<QCPLayoutElement*>());
  2484. mChildren.insert(QCP::msRight, QList<QCPLayoutElement*>());
  2485. mChildren.insert(QCP::msTop, QList<QCPLayoutElement*>());
  2486. mChildren.insert(QCP::msBottom, QList<QCPLayoutElement*>());
  2487. }
  2488. QCPMarginGroup::~QCPMarginGroup()
  2489. {
  2490. clear();
  2491. }
  2492. /*!
  2493. Returns whether this margin group is empty. If this function returns true, no layout elements use
  2494. this margin group to synchronize margin sides.
  2495. */
  2496. bool QCPMarginGroup::isEmpty() const
  2497. {
  2498. QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
  2499. while (it.hasNext())
  2500. {
  2501. it.next();
  2502. if (!it.value().isEmpty())
  2503. return false;
  2504. }
  2505. return true;
  2506. }
  2507. /*!
  2508. Clears this margin group. The synchronization of the margin sides that use this margin group is
  2509. lifted and they will use their individual margin sizes again.
  2510. */
  2511. void QCPMarginGroup::clear()
  2512. {
  2513. // make all children remove themselves from this margin group:
  2514. QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
  2515. while (it.hasNext())
  2516. {
  2517. it.next();
  2518. const QList<QCPLayoutElement*> elements = it.value();
  2519. for (int i=elements.size()-1; i>=0; --i)
  2520. elements.at(i)->setMarginGroup(it.key(), nullptr); // removes itself from mChildren via removeChild
  2521. }
  2522. }
  2523. /*! \internal
  2524. Returns the synchronized common margin for \a side. This is the margin value that will be used by
  2525. the layout element on the respective side, if it is part of this margin group.
  2526. The common margin is calculated by requesting the automatic margin (\ref
  2527. QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin
  2528. group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into
  2529. account, too.)
  2530. */
  2531. double QCPMarginGroup::commonMargin(QCP::MarginSide side) const
  2532. {
  2533. // query all automatic margins of the layout elements in this margin group side and find maximum:
  2534. double result = 0;
  2535. foreach (QCPLayoutElement *el, mChildren.value(side))
  2536. {
  2537. if (!el->autoMargins().testFlag(side))
  2538. continue;
  2539. double m = qMax(el->calculateAutoMargin(side), QCP::getMarginValue(el->minimumMargins(), side));
  2540. if (m > result)
  2541. result = m;
  2542. }
  2543. return result;
  2544. }
  2545. /*! \internal
  2546. Adds \a element to the internal list of child elements, for the margin \a side.
  2547. This function does not modify the margin group property of \a element.
  2548. */
  2549. void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element)
  2550. {
  2551. if (!mChildren[side].contains(element))
  2552. mChildren[side].append(element);
  2553. else
  2554. qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast<quintptr>(element);
  2555. }
  2556. /*! \internal
  2557. Removes \a element from the internal list of child elements, for the margin \a side.
  2558. This function does not modify the margin group property of \a element.
  2559. */
  2560. void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element)
  2561. {
  2562. if (!mChildren[side].removeOne(element))
  2563. qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast<quintptr>(element);
  2564. }
  2565. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2566. //////////////////// QCPLayoutElement
  2567. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2568. /*! \class QCPLayoutElement
  2569. \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system".
  2570. This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses.
  2571. A Layout element is a rectangular object which can be placed in layouts. It has an outer rect
  2572. (QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference
  2573. between outer and inner rect is called its margin. The margin can either be set to automatic or
  2574. manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be
  2575. set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic,
  2576. the layout element subclass will control the value itself (via \ref calculateAutoMargin).
  2577. Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level
  2578. layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref
  2579. QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested.
  2580. Thus in QCustomPlot one can divide layout elements into two categories: The ones that are
  2581. invisible by themselves, because they don't draw anything. Their only purpose is to manage the
  2582. position and size of other layout elements. This category of layout elements usually use
  2583. QCPLayout as base class. Then there is the category of layout elements which actually draw
  2584. something. For example, QCPAxisRect, QCPLegend and QCPTextElement are of this category. This does
  2585. not necessarily mean that the latter category can't have child layout elements. QCPLegend for
  2586. instance, actually derives from QCPLayoutGrid and the individual legend items are child layout
  2587. elements in the grid layout.
  2588. */
  2589. /* start documentation of inline functions */
  2590. /*! \fn QCPLayout *QCPLayoutElement::layout() const
  2591. Returns the parent layout of this layout element.
  2592. */
  2593. /*! \fn QRect QCPLayoutElement::rect() const
  2594. Returns the inner rect of this layout element. The inner rect is the outer rect (\ref outerRect, \ref
  2595. setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins).
  2596. In some cases, the area between outer and inner rect is left blank. In other cases the margin
  2597. area is used to display peripheral graphics while the main content is in the inner rect. This is
  2598. where automatic margin calculation becomes interesting because it allows the layout element to
  2599. adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect
  2600. draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if
  2601. \ref setAutoMargins is enabled) according to the space required by the labels of the axes.
  2602. \see outerRect
  2603. */
  2604. /*! \fn QRect QCPLayoutElement::outerRect() const
  2605. Returns the outer rect of this layout element. The outer rect is the inner rect expanded by the
  2606. margins (\ref setMargins, \ref setAutoMargins). The outer rect is used (and set via \ref
  2607. setOuterRect) by the parent \ref QCPLayout to control the size of this layout element.
  2608. \see rect
  2609. */
  2610. /* end documentation of inline functions */
  2611. /*!
  2612. Creates an instance of QCPLayoutElement and sets default values.
  2613. */
  2614. QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) :
  2615. QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout)
  2616. mParentLayout(nullptr),
  2617. mMinimumSize(),
  2618. mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX),
  2619. mSizeConstraintRect(scrInnerRect),
  2620. mRect(0, 0, 0, 0),
  2621. mOuterRect(0, 0, 0, 0),
  2622. mMargins(0, 0, 0, 0),
  2623. mMinimumMargins(0, 0, 0, 0),
  2624. mAutoMargins(QCP::msAll)
  2625. {
  2626. }
  2627. QCPLayoutElement::~QCPLayoutElement()
  2628. {
  2629. setMarginGroup(QCP::msAll, nullptr); // unregister at margin groups, if there are any
  2630. // unregister at layout:
  2631. 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
  2632. mParentLayout->take(this);
  2633. }
  2634. /*!
  2635. Sets the outer rect of this layout element. If the layout element is inside a layout, the layout
  2636. sets the position and size of this layout element using this function.
  2637. Calling this function externally has no effect, since the layout will overwrite any changes to
  2638. the outer rect upon the next replot.
  2639. The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect.
  2640. \see rect
  2641. */
  2642. void QCPLayoutElement::setOuterRect(const QRectF &rect)
  2643. {
  2644. if (mOuterRect != rect)
  2645. {
  2646. mOuterRect = rect;
  2647. mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
  2648. }
  2649. }
  2650. /*!
  2651. Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all
  2652. sides, this function is used to manually set the margin on those sides. Sides that are still set
  2653. to be handled automatically are ignored and may have any value in \a margins.
  2654. The margin is the distance between the outer rect (controlled by the parent layout via \ref
  2655. setOuterRect) and the inner \ref rect (which usually contains the main content of this layout
  2656. element).
  2657. \see setAutoMargins
  2658. */
  2659. void QCPLayoutElement::setMargins(const QMarginsF &margins)
  2660. {
  2661. if (mMargins != margins)
  2662. {
  2663. mMargins = margins;
  2664. mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
  2665. }
  2666. }
  2667. /*!
  2668. If \ref setAutoMargins is enabled on some or all margins, this function is used to provide
  2669. minimum values for those margins.
  2670. The minimum values are not enforced on margin sides that were set to be under manual control via
  2671. \ref setAutoMargins.
  2672. \see setAutoMargins
  2673. */
  2674. void QCPLayoutElement::setMinimumMargins(const QMarginsF &margins)
  2675. {
  2676. if (mMinimumMargins != margins)
  2677. {
  2678. mMinimumMargins = margins;
  2679. }
  2680. }
  2681. /*!
  2682. Sets on which sides the margin shall be calculated automatically. If a side is calculated
  2683. automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is
  2684. set to be controlled manually, the value may be specified with \ref setMargins.
  2685. Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref
  2686. setMarginGroup), to synchronize (align) it with other layout elements in the plot.
  2687. \see setMinimumMargins, setMargins, QCP::MarginSide
  2688. */
  2689. void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides)
  2690. {
  2691. mAutoMargins = sides;
  2692. }
  2693. /*!
  2694. Sets the minimum size of this layout element. A parent layout tries to respect the \a size here
  2695. by changing row/column sizes in the layout accordingly.
  2696. If the parent layout size is not sufficient to satisfy all minimum size constraints of its child
  2697. layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot
  2698. propagates the layout's size constraints to the outside by setting its own minimum QWidget size
  2699. accordingly, so violations of \a size should be exceptions.
  2700. Whether this constraint applies to the inner or the outer rect can be specified with \ref
  2701. setSizeConstraintRect (see \ref rect and \ref outerRect).
  2702. */
  2703. void QCPLayoutElement::setMinimumSize(const QSizeF &size)
  2704. {
  2705. if (mMinimumSize != size)
  2706. {
  2707. mMinimumSize = size;
  2708. if (mParentLayout)
  2709. mParentLayout->sizeConstraintsChanged();
  2710. }
  2711. }
  2712. /*! \overload
  2713. Sets the minimum size of this layout element.
  2714. Whether this constraint applies to the inner or the outer rect can be specified with \ref
  2715. setSizeConstraintRect (see \ref rect and \ref outerRect).
  2716. */
  2717. void QCPLayoutElement::setMinimumSize(double width, double height)
  2718. {
  2719. setMinimumSize(QSizeF(width, height));
  2720. }
  2721. /*!
  2722. Sets the maximum size of this layout element. A parent layout tries to respect the \a size here
  2723. by changing row/column sizes in the layout accordingly.
  2724. Whether this constraint applies to the inner or the outer rect can be specified with \ref
  2725. setSizeConstraintRect (see \ref rect and \ref outerRect).
  2726. */
  2727. void QCPLayoutElement::setMaximumSize(const QSizeF &size)
  2728. {
  2729. if (mMaximumSize != size)
  2730. {
  2731. mMaximumSize = size;
  2732. if (mParentLayout)
  2733. mParentLayout->sizeConstraintsChanged();
  2734. }
  2735. }
  2736. /*! \overload
  2737. Sets the maximum size of this layout element.
  2738. Whether this constraint applies to the inner or the outer rect can be specified with \ref
  2739. setSizeConstraintRect (see \ref rect and \ref outerRect).
  2740. */
  2741. void QCPLayoutElement::setMaximumSize(double width, double height)
  2742. {
  2743. setMaximumSize(QSizeF(width, height));
  2744. }
  2745. /*!
  2746. Sets to which rect of a layout element the size constraints apply. Size constraints can be set
  2747. via \ref setMinimumSize and \ref setMaximumSize.
  2748. The outer rect (\ref outerRect) includes the margins (e.g. in the case of a QCPAxisRect the axis
  2749. labels), whereas the inner rect (\ref rect) does not.
  2750. \see setMinimumSize, setMaximumSize
  2751. */
  2752. void QCPLayoutElement::setSizeConstraintRect(SizeConstraintRect constraintRect)
  2753. {
  2754. if (mSizeConstraintRect != constraintRect)
  2755. {
  2756. mSizeConstraintRect = constraintRect;
  2757. if (mParentLayout)
  2758. mParentLayout->sizeConstraintsChanged();
  2759. }
  2760. }
  2761. /*!
  2762. Sets the margin \a group of the specified margin \a sides.
  2763. Margin groups allow synchronizing specified margins across layout elements, see the documentation
  2764. of \ref QCPMarginGroup.
  2765. To unset the margin group of \a sides, set \a group to \c nullptr.
  2766. Note that margin groups only work for margin sides that are set to automatic (\ref
  2767. setAutoMargins).
  2768. \see QCP::MarginSide
  2769. */
  2770. void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group)
  2771. {
  2772. QVector<QCP::MarginSide> sideVector;
  2773. if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft);
  2774. if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight);
  2775. if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop);
  2776. if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom);
  2777. foreach (QCP::MarginSide side, sideVector)
  2778. {
  2779. if (marginGroup(side) != group)
  2780. {
  2781. QCPMarginGroup *oldGroup = marginGroup(side);
  2782. if (oldGroup) // unregister at old group
  2783. oldGroup->removeChild(side, this);
  2784. if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there
  2785. {
  2786. mMarginGroups.remove(side);
  2787. } else // setting to a new group
  2788. {
  2789. mMarginGroups[side] = group;
  2790. group->addChild(side, this);
  2791. }
  2792. }
  2793. }
  2794. }
  2795. /*!
  2796. Updates the layout element and sub-elements. This function is automatically called before every
  2797. replot by the parent layout element. It is called multiple times, once for every \ref
  2798. UpdatePhase. The phases are run through in the order of the enum values. For details about what
  2799. happens at the different phases, see the documentation of \ref UpdatePhase.
  2800. Layout elements that have child elements should call the \ref update method of their child
  2801. elements, and pass the current \a phase unchanged.
  2802. The default implementation executes the automatic margin mechanism in the \ref upMargins phase.
  2803. Subclasses should make sure to call the base class implementation.
  2804. */
  2805. void QCPLayoutElement::update(UpdatePhase phase)
  2806. {
  2807. if (phase == upMargins)
  2808. {
  2809. if (mAutoMargins != QCP::msNone)
  2810. {
  2811. // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group:
  2812. QMarginsF newMargins = mMargins;
  2813. const QList<QCP::MarginSide> allMarginSides = QList<QCP::MarginSide>() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom;
  2814. foreach (QCP::MarginSide side, allMarginSides)
  2815. {
  2816. if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically
  2817. {
  2818. if (mMarginGroups.contains(side))
  2819. QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group
  2820. else
  2821. QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly
  2822. // apply minimum margin restrictions:
  2823. if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side))
  2824. QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side));
  2825. }
  2826. }
  2827. setMargins(newMargins);
  2828. }
  2829. }
  2830. }
  2831. /*!
  2832. Returns the suggested minimum size this layout element (the \ref outerRect) may be compressed to,
  2833. if no manual minimum size is set.
  2834. if a minimum size (\ref setMinimumSize) was not set manually, parent layouts use the returned size
  2835. (usually indirectly through \ref QCPLayout::getFinalMinimumOuterSize) to determine the minimum
  2836. allowed size of this layout element.
  2837. A manual minimum size is considered set if it is non-zero.
  2838. The default implementation simply returns the sum of the horizontal margins for the width and the
  2839. sum of the vertical margins for the height. Reimplementations may use their detailed knowledge
  2840. about the layout element's content to provide size hints.
  2841. */
  2842. QSizeF QCPLayoutElement::minimumOuterSizeHint() const
  2843. {
  2844. return {mMargins.left()+mMargins.right(), mMargins.top()+mMargins.bottom()};
  2845. }
  2846. /*!
  2847. Returns the suggested maximum size this layout element (the \ref outerRect) may be expanded to,
  2848. if no manual maximum size is set.
  2849. if a maximum size (\ref setMaximumSize) was not set manually, parent layouts use the returned
  2850. size (usually indirectly through \ref QCPLayout::getFinalMaximumOuterSize) to determine the
  2851. maximum allowed size of this layout element.
  2852. A manual maximum size is considered set if it is smaller than Qt's \c QWIDGETSIZE_MAX.
  2853. The default implementation simply returns \c QWIDGETSIZE_MAX for both width and height, implying
  2854. no suggested maximum size. Reimplementations may use their detailed knowledge about the layout
  2855. element's content to provide size hints.
  2856. */
  2857. QSizeF QCPLayoutElement::maximumOuterSizeHint() const
  2858. {
  2859. return {QWIDGETSIZE_MAX, QWIDGETSIZE_MAX};
  2860. }
  2861. /*!
  2862. Returns a list of all child elements in this layout element. If \a recursive is true, all
  2863. sub-child elements are included in the list, too.
  2864. \warning There may be \c nullptr entries in the returned list. For example, QCPLayoutGrid may
  2865. have empty cells which yield \c nullptr at the respective index.
  2866. */
  2867. QList<QCPLayoutElement*> QCPLayoutElement::elements(bool recursive) const
  2868. {
  2869. Q_UNUSED(recursive)
  2870. return QList<QCPLayoutElement*>();
  2871. }
  2872. /*!
  2873. Layout elements are sensitive to events inside their outer rect. If \a pos is within the outer
  2874. rect, this method returns a value corresponding to 0.99 times the parent plot's selection
  2875. tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is
  2876. true, -1.0 is returned.
  2877. See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
  2878. QCPLayoutElement subclasses may reimplement this method to provide more specific selection test
  2879. behaviour.
  2880. */
  2881. double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  2882. {
  2883. Q_UNUSED(details)
  2884. if (onlySelectable)
  2885. return -1;
  2886. if (QRectF(mOuterRect).contains(pos))
  2887. {
  2888. if (mParentPlot)
  2889. return mParentPlot->selectionTolerance()*0.99;
  2890. else
  2891. {
  2892. qDebug() << Q_FUNC_INFO << "parent plot not defined";
  2893. return -1;
  2894. }
  2895. } else
  2896. return -1;
  2897. }
  2898. /*! \internal
  2899. propagates the parent plot initialization to all child elements, by calling \ref
  2900. QCPLayerable::initializeParentPlot on them.
  2901. */
  2902. void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot)
  2903. {
  2904. foreach (QCPLayoutElement* el, elements(false))
  2905. {
  2906. if (!el->parentPlot())
  2907. el->initializeParentPlot(parentPlot);
  2908. }
  2909. }
  2910. /*! \internal
  2911. Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a
  2912. side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the
  2913. returned value will not be smaller than the specified minimum margin.
  2914. The default implementation just returns the respective manual margin (\ref setMargins) or the
  2915. minimum margin, whichever is larger.
  2916. */
  2917. double QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side)
  2918. {
  2919. return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side));
  2920. }
  2921. /*! \internal
  2922. This virtual method is called when this layout element was moved to a different QCPLayout, or
  2923. when this layout element has changed its logical position (e.g. row and/or column) within the
  2924. same QCPLayout. Subclasses may use this to react accordingly.
  2925. Since this method is called after the completion of the move, you can access the new parent
  2926. layout via \ref layout().
  2927. The default implementation does nothing.
  2928. */
  2929. void QCPLayoutElement::layoutChanged()
  2930. {
  2931. }
  2932. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2933. //////////////////// QCPLayout
  2934. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2935. /*! \class QCPLayout
  2936. \brief The abstract base class for layouts
  2937. This is an abstract base class for layout elements whose main purpose is to define the position
  2938. and size of other child layout elements. In most cases, layouts don't draw anything themselves
  2939. (but there are exceptions to this, e.g. QCPLegend).
  2940. QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts.
  2941. QCPLayout introduces a common interface for accessing and manipulating the child elements. Those
  2942. functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref
  2943. simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions
  2944. to this interface which are more specialized to the form of the layout. For example, \ref
  2945. QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid
  2946. more conveniently.
  2947. Since this is an abstract base class, you can't instantiate it directly. Rather use one of its
  2948. subclasses like QCPLayoutGrid or QCPLayoutInset.
  2949. For a general introduction to the layout system, see the dedicated documentation page \ref
  2950. thelayoutsystem "The Layout System".
  2951. */
  2952. /* start documentation of pure virtual functions */
  2953. /*! \fn virtual int QCPLayout::elementCount() const = 0
  2954. Returns the number of elements/cells in the layout.
  2955. \see elements, elementAt
  2956. */
  2957. /*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0
  2958. Returns the element in the cell with the given \a index. If \a index is invalid, returns \c
  2959. nullptr.
  2960. Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g.
  2961. QCPLayoutGrid), so this function may return \c nullptr in those cases. You may use this function
  2962. to check whether a cell is empty or not.
  2963. \see elements, elementCount, takeAt
  2964. */
  2965. /*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0
  2966. Removes the element with the given \a index from the layout and returns it.
  2967. If the \a index is invalid or the cell with that index is empty, returns \c nullptr.
  2968. Note that some layouts don't remove the respective cell right away but leave an empty cell after
  2969. successful removal of the layout element. To collapse empty cells, use \ref simplify.
  2970. \see elementAt, take
  2971. */
  2972. /*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0
  2973. Removes the specified \a element from the layout and returns true on success.
  2974. If the \a element isn't in this layout, returns false.
  2975. Note that some layouts don't remove the respective cell right away but leave an empty cell after
  2976. successful removal of the layout element. To collapse empty cells, use \ref simplify.
  2977. \see takeAt
  2978. */
  2979. /* end documentation of pure virtual functions */
  2980. /*!
  2981. Creates an instance of QCPLayout and sets default values. Note that since QCPLayout
  2982. is an abstract base class, it can't be instantiated directly.
  2983. */
  2984. QCPLayout::QCPLayout()
  2985. {
  2986. }
  2987. /*!
  2988. If \a phase is \ref upLayout, calls \ref updateLayout, which subclasses may reimplement to
  2989. reposition and resize their cells.
  2990. Finally, the call is propagated down to all child \ref QCPLayoutElement "QCPLayoutElements".
  2991. For details about this method and the update phases, see the documentation of \ref
  2992. QCPLayoutElement::update.
  2993. */
  2994. void QCPLayout::update(UpdatePhase phase)
  2995. {
  2996. QCPLayoutElement::update(phase);
  2997. // set child element rects according to layout:
  2998. if (phase == upLayout)
  2999. updateLayout();
  3000. // propagate update call to child elements:
  3001. const int elCount = elementCount();
  3002. for (int i=0; i<elCount; ++i)
  3003. {
  3004. if (QCPLayoutElement *el = elementAt(i))
  3005. el->update(phase);
  3006. }
  3007. }
  3008. /* inherits documentation from base class */
  3009. QList<QCPLayoutElement*> QCPLayout::elements(bool recursive) const
  3010. {
  3011. const int c = elementCount();
  3012. QList<QCPLayoutElement*> result;
  3013. #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
  3014. result.reserve(c);
  3015. #endif
  3016. for (int i=0; i<c; ++i)
  3017. result.append(elementAt(i));
  3018. if (recursive)
  3019. {
  3020. for (int i=0; i<c; ++i)
  3021. {
  3022. if (result.at(i))
  3023. result << result.at(i)->elements(recursive);
  3024. }
  3025. }
  3026. return result;
  3027. }
  3028. /*!
  3029. Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the
  3030. default implementation does nothing.
  3031. Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit
  3032. simplification while QCPLayoutGrid does.
  3033. */
  3034. void QCPLayout::simplify()
  3035. {
  3036. }
  3037. /*!
  3038. Removes and deletes the element at the provided \a index. Returns true on success. If \a index is
  3039. invalid or points to an empty cell, returns false.
  3040. This function internally uses \ref takeAt to remove the element from the layout and then deletes
  3041. the returned element. Note that some layouts don't remove the respective cell right away but leave an
  3042. empty cell after successful removal of the layout element. To collapse empty cells, use \ref
  3043. simplify.
  3044. \see remove, takeAt
  3045. */
  3046. bool QCPLayout::removeAt(int index)
  3047. {
  3048. if (QCPLayoutElement *el = takeAt(index))
  3049. {
  3050. delete el;
  3051. return true;
  3052. } else
  3053. return false;
  3054. }
  3055. /*!
  3056. Removes and deletes the provided \a element. Returns true on success. If \a element is not in the
  3057. layout, returns false.
  3058. This function internally uses \ref takeAt to remove the element from the layout and then deletes
  3059. the element. Note that some layouts don't remove the respective cell right away but leave an
  3060. empty cell after successful removal of the layout element. To collapse empty cells, use \ref
  3061. simplify.
  3062. \see removeAt, take
  3063. */
  3064. bool QCPLayout::remove(QCPLayoutElement *element)
  3065. {
  3066. if (take(element))
  3067. {
  3068. delete element;
  3069. return true;
  3070. } else
  3071. return false;
  3072. }
  3073. /*!
  3074. Removes and deletes all layout elements in this layout. Finally calls \ref simplify to make sure
  3075. all empty cells are collapsed.
  3076. \see remove, removeAt
  3077. */
  3078. void QCPLayout::clear()
  3079. {
  3080. for (int i=elementCount()-1; i>=0; --i)
  3081. {
  3082. if (elementAt(i))
  3083. removeAt(i);
  3084. }
  3085. simplify();
  3086. }
  3087. /*!
  3088. Subclasses call this method to report changed (minimum/maximum) size constraints.
  3089. If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref
  3090. sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of
  3091. QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout,
  3092. it may update itself and resize cells accordingly.
  3093. */
  3094. void QCPLayout::sizeConstraintsChanged() const
  3095. {
  3096. if (QWidget *w = qobject_cast<QWidget*>(parent()))
  3097. w->updateGeometry();
  3098. else if (QCPLayout *l = qobject_cast<QCPLayout*>(parent()))
  3099. l->sizeConstraintsChanged();
  3100. }
  3101. /*! \internal
  3102. Subclasses reimplement this method to update the position and sizes of the child elements/cells
  3103. via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing.
  3104. The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay
  3105. within that rect.
  3106. \ref getSectionSizes may help with the reimplementation of this function.
  3107. \see update
  3108. */
  3109. void QCPLayout::updateLayout()
  3110. {
  3111. }
  3112. /*! \internal
  3113. Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the
  3114. \ref QCPLayerable::parentLayerable and the QObject parent to this layout.
  3115. Further, if \a el didn't previously have a parent plot, calls \ref
  3116. QCPLayerable::initializeParentPlot on \a el to set the paret plot.
  3117. This method is used by subclass specific methods that add elements to the layout. Note that this
  3118. method only changes properties in \a el. The removal from the old layout and the insertion into
  3119. the new layout must be done additionally.
  3120. */
  3121. void QCPLayout::adoptElement(QCPLayoutElement *el)
  3122. {
  3123. if (el)
  3124. {
  3125. el->mParentLayout = this;
  3126. el->setParentLayerable(this);
  3127. el->setParent(this);
  3128. if (!el->parentPlot())
  3129. el->initializeParentPlot(mParentPlot);
  3130. el->layoutChanged();
  3131. } else
  3132. qDebug() << Q_FUNC_INFO << "Null element passed";
  3133. }
  3134. /*! \internal
  3135. Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout
  3136. and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent
  3137. QCustomPlot.
  3138. This method is used by subclass specific methods that remove elements from the layout (e.g. \ref
  3139. take or \ref takeAt). Note that this method only changes properties in \a el. The removal from
  3140. the old layout must be done additionally.
  3141. */
  3142. void QCPLayout::releaseElement(QCPLayoutElement *el)
  3143. {
  3144. if (el)
  3145. {
  3146. el->mParentLayout = nullptr;
  3147. el->setParentLayerable(nullptr);
  3148. el->setParent(mParentPlot);
  3149. // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot
  3150. } else
  3151. qDebug() << Q_FUNC_INFO << "Null element passed";
  3152. }
  3153. /*! \internal
  3154. This is a helper function for the implementation of \ref updateLayout in subclasses.
  3155. It calculates the sizes of one-dimensional sections with provided constraints on maximum section
  3156. sizes, minimum section sizes, relative stretch factors and the final total size of all sections.
  3157. The QVector entries refer to the sections. Thus all QVectors must have the same size.
  3158. \a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size
  3159. imposed, set all vector values to Qt's QWIDGETSIZE_MAX.
  3160. \a minSizes gives the minimum allowed size of each section. If there shall be no minimum size
  3161. imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than
  3162. \a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words,
  3163. not exceeding the allowed total size is taken to be more important than not going below minimum
  3164. section sizes.)
  3165. \a stretchFactors give the relative proportions of the sections to each other. If all sections
  3166. shall be scaled equally, set all values equal. If the first section shall be double the size of
  3167. each individual other section, set the first number of \a stretchFactors to double the value of
  3168. the other individual values (e.g. {2, 1, 1, 1}).
  3169. \a totalSize is the value that the final section sizes will add up to. Due to rounding, the
  3170. actual sum may differ slightly. If you want the section sizes to sum up to exactly that value,
  3171. you could distribute the remaining difference on the sections.
  3172. The return value is a QVector containing the section sizes.
  3173. */
  3174. QVector<double> QCPLayout::getSectionSizes(QVector<double> maxSizes, QVector<double> minSizes, QVector<double> stretchFactors, double totalSize) const
  3175. {
  3176. if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size())
  3177. {
  3178. qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors;
  3179. return QVector<double>();
  3180. }
  3181. if (stretchFactors.isEmpty())
  3182. return QVector<double>();
  3183. int sectionCount = stretchFactors.size();
  3184. QVector<double> sectionSizes(sectionCount);
  3185. // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections):
  3186. double minSizeSum = 0;
  3187. for (int i=0; i<sectionCount; ++i)
  3188. minSizeSum += minSizes.at(i);
  3189. if (totalSize < minSizeSum)
  3190. {
  3191. // new stretch factors are minimum sizes and minimum sizes are set to zero:
  3192. for (int i=0; i<sectionCount; ++i)
  3193. {
  3194. stretchFactors[i] = minSizes.at(i);
  3195. minSizes[i] = 0;
  3196. }
  3197. }
  3198. QList<int> minimumLockedSections;
  3199. QList<int> unfinishedSections;
  3200. for (int i=0; i<sectionCount; ++i)
  3201. unfinishedSections.append(i);
  3202. double freeSize = totalSize;
  3203. int outerIterations = 0;
  3204. while (!unfinishedSections.isEmpty() && outerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
  3205. {
  3206. ++outerIterations;
  3207. int innerIterations = 0;
  3208. while (!unfinishedSections.isEmpty() && innerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
  3209. {
  3210. ++innerIterations;
  3211. // find section that hits its maximum next:
  3212. int nextId = -1;
  3213. double nextMax = 1e12;
  3214. foreach (int secId, unfinishedSections)
  3215. {
  3216. double hitsMaxAt = (maxSizes.at(secId)-sectionSizes.at(secId))/stretchFactors.at(secId);
  3217. if (hitsMaxAt < nextMax)
  3218. {
  3219. nextMax = hitsMaxAt;
  3220. nextId = secId;
  3221. }
  3222. }
  3223. // 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
  3224. // actually hits its maximum, without exceeding the total size when we add up all sections)
  3225. double stretchFactorSum = 0;
  3226. foreach (int secId, unfinishedSections)
  3227. stretchFactorSum += stretchFactors.at(secId);
  3228. double nextMaxLimit = freeSize/stretchFactorSum;
  3229. if (nextMax < nextMaxLimit) // next maximum is actually hit, move forward to that point and fix the size of that section
  3230. {
  3231. foreach (int secId, unfinishedSections)
  3232. {
  3233. sectionSizes[secId] += nextMax*stretchFactors.at(secId); // increment all sections
  3234. freeSize -= nextMax*stretchFactors.at(secId);
  3235. }
  3236. unfinishedSections.removeOne(nextId); // exclude the section that is now at maximum from further changes
  3237. } else // next maximum isn't hit, just distribute rest of free space on remaining sections
  3238. {
  3239. foreach (int secId, unfinishedSections)
  3240. sectionSizes[secId] += nextMaxLimit*stretchFactors.at(secId); // increment all sections
  3241. unfinishedSections.clear();
  3242. }
  3243. }
  3244. if (innerIterations == sectionCount*2)
  3245. qDebug() << Q_FUNC_INFO << "Exceeded maximum expected inner iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
  3246. // now check whether the resulting section sizes violate minimum restrictions:
  3247. bool foundMinimumViolation = false;
  3248. for (int i=0; i<sectionSizes.size(); ++i)
  3249. {
  3250. if (minimumLockedSections.contains(i))
  3251. continue;
  3252. if (sectionSizes.at(i) < minSizes.at(i)) // section violates minimum
  3253. {
  3254. sectionSizes[i] = minSizes.at(i); // set it to minimum
  3255. foundMinimumViolation = true; // make sure we repeat the whole optimization process
  3256. minimumLockedSections.append(i);
  3257. }
  3258. }
  3259. if (foundMinimumViolation)
  3260. {
  3261. freeSize = totalSize;
  3262. for (int i=0; i<sectionCount; ++i)
  3263. {
  3264. if (!minimumLockedSections.contains(i)) // only put sections that haven't hit their minimum back into the pool
  3265. unfinishedSections.append(i);
  3266. else
  3267. freeSize -= sectionSizes.at(i); // remove size of minimum locked sections from available space in next round
  3268. }
  3269. // reset all section sizes to zero that are in unfinished sections (all others have been set to their minimum):
  3270. foreach (int secId, unfinishedSections)
  3271. sectionSizes[secId] = 0;
  3272. }
  3273. }
  3274. if (outerIterations == sectionCount*2)
  3275. qDebug() << Q_FUNC_INFO << "Exceeded maximum expec ted outer iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
  3276. // qDebug() << Q_FUNC_INFO << sectionSizes << std::accumulate(sectionSizes.begin(),sectionSizes.end(),.0 );
  3277. // QVector<int> result(sectionCount);
  3278. // for (int i=0; i<sectionCount; ++i)
  3279. // result[i] = int(sectionSizes.at(i));
  3280. return sectionSizes;
  3281. }
  3282. /*! \internal
  3283. This is a helper function for the implementation of subclasses.
  3284. It returns the minimum size that should finally be used for the outer rect of the passed layout
  3285. element \a el.
  3286. It takes into account whether a manual minimum size is set (\ref
  3287. QCPLayoutElement::setMinimumSize), which size constraint is set (\ref
  3288. QCPLayoutElement::setSizeConstraintRect), as well as the minimum size hint, if no manual minimum
  3289. size was set (\ref QCPLayoutElement::minimumOuterSizeHint).
  3290. */
  3291. QSizeF QCPLayout::getFinalMinimumOuterSize(const QCPLayoutElement *el)
  3292. {
  3293. QSizeF minOuterHint = el->minimumOuterSizeHint();
  3294. QSizeF 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)
  3295. if (minOuter.width() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
  3296. minOuter.rwidth() += el->margins().left() + el->margins().right();
  3297. if (minOuter.height() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
  3298. minOuter.rheight() += el->margins().top() + el->margins().bottom();
  3299. return {minOuter.width() > 0 ? minOuter.width() : minOuterHint.width(),
  3300. minOuter.height() > 0 ? minOuter.height() : minOuterHint.height()};
  3301. }
  3302. /*! \internal
  3303. This is a helper function for the implementation of subclasses.
  3304. It returns the maximum size that should finally be used for the outer rect of the passed layout
  3305. element \a el.
  3306. It takes into account whether a manual maximum size is set (\ref
  3307. QCPLayoutElement::setMaximumSize), which size constraint is set (\ref
  3308. QCPLayoutElement::setSizeConstraintRect), as well as the maximum size hint, if no manual maximum
  3309. size was set (\ref QCPLayoutElement::maximumOuterSizeHint).
  3310. */
  3311. QSizeF QCPLayout::getFinalMaximumOuterSize(const QCPLayoutElement *el)
  3312. {
  3313. QSizeF maxOuterHint = el->maximumOuterSizeHint();
  3314. QSizeF 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)
  3315. if (maxOuter.width() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
  3316. maxOuter.rwidth() += el->margins().left() + el->margins().right();
  3317. if (maxOuter.height() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
  3318. maxOuter.rheight() += el->margins().top() + el->margins().bottom();
  3319. return {maxOuter.width() < QWIDGETSIZE_MAX ? maxOuter.width() : maxOuterHint.width(),
  3320. maxOuter.height() < QWIDGETSIZE_MAX ? maxOuter.height() : maxOuterHint.height()};
  3321. }
  3322. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3323. //////////////////// QCPLayoutGrid
  3324. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3325. /*! \class QCPLayoutGrid
  3326. \brief A layout that arranges child elements in a grid
  3327. Elements are laid out in a grid with configurable stretch factors (\ref setColumnStretchFactor,
  3328. \ref setRowStretchFactor) and spacing (\ref setColumnSpacing, \ref setRowSpacing).
  3329. Elements can be added to cells via \ref addElement. The grid is expanded if the specified row or
  3330. column doesn't exist yet. Whether a cell contains a valid layout element can be checked with \ref
  3331. hasElement, that element can be retrieved with \ref element. If rows and columns that only have
  3332. empty cells shall be removed, call \ref simplify. Removal of elements is either done by just
  3333. adding the element to a different layout or by using the QCPLayout interface \ref take or \ref
  3334. remove.
  3335. If you use \ref addElement(QCPLayoutElement*) without explicit parameters for \a row and \a
  3336. column, the grid layout will choose the position according to the current \ref setFillOrder and
  3337. the wrapping (\ref setWrap).
  3338. Row and column insertion can be performed with \ref insertRow and \ref insertColumn.
  3339. */
  3340. /* start documentation of inline functions */
  3341. /*! \fn int QCPLayoutGrid::rowCount() const
  3342. Returns the number of rows in the layout.
  3343. \see columnCount
  3344. */
  3345. /*! \fn int QCPLayoutGrid::columnCount() const
  3346. Returns the number of columns in the layout.
  3347. \see rowCount
  3348. */
  3349. /* end documentation of inline functions */
  3350. /*!
  3351. Creates an instance of QCPLayoutGrid and sets default values.
  3352. */
  3353. QCPLayoutGrid::QCPLayoutGrid() :
  3354. mColumnSpacing(5),
  3355. mRowSpacing(5),
  3356. mWrap(0),
  3357. mFillOrder(foColumnsFirst)
  3358. {
  3359. }
  3360. QCPLayoutGrid::~QCPLayoutGrid()
  3361. {
  3362. // clear all child layout elements. This is important because only the specific layouts know how
  3363. // to handle removing elements (clear calls virtual removeAt method to do that).
  3364. clear();
  3365. }
  3366. /*!
  3367. Returns the element in the cell in \a row and \a column.
  3368. Returns \c nullptr if either the row/column is invalid or if the cell is empty. In those cases, a
  3369. qDebug message is printed. To check whether a cell exists and isn't empty, use \ref hasElement.
  3370. \see addElement, hasElement
  3371. */
  3372. QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const
  3373. {
  3374. if (row >= 0 && row < mElements.size())
  3375. {
  3376. if (column >= 0 && column < mElements.first().size())
  3377. {
  3378. if (QCPLayoutElement *result = mElements.at(row).at(column))
  3379. return result;
  3380. else
  3381. qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column;
  3382. } else
  3383. qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column;
  3384. } else
  3385. qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column;
  3386. return nullptr;
  3387. }
  3388. /*! \overload
  3389. Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it
  3390. is first removed from there. If \a row or \a column don't exist yet, the layout is expanded
  3391. accordingly.
  3392. Returns true if the element was added successfully, i.e. if the cell at \a row and \a column
  3393. didn't already have an element.
  3394. Use the overload of this method without explicit row/column index to place the element according
  3395. to the configured fill order and wrapping settings.
  3396. \see element, hasElement, take, remove
  3397. */
  3398. bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element)
  3399. {
  3400. if (!hasElement(row, column))
  3401. {
  3402. if (element && element->layout()) // remove from old layout first
  3403. element->layout()->take(element);
  3404. expandTo(row+1, column+1);
  3405. mElements[row][column] = element;
  3406. if (element)
  3407. adoptElement(element);
  3408. return true;
  3409. } else
  3410. qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column;
  3411. return false;
  3412. }
  3413. /*! \overload
  3414. Adds the \a element to the next empty cell according to the current fill order (\ref
  3415. setFillOrder) and wrapping (\ref setWrap). If \a element is already in a layout, it is first
  3416. removed from there. If necessary, the layout is expanded to hold the new element.
  3417. Returns true if the element was added successfully.
  3418. \see setFillOrder, setWrap, element, hasElement, take, remove
  3419. */
  3420. bool QCPLayoutGrid::addElement(QCPLayoutElement *element)
  3421. {
  3422. int rowIndex = 0;
  3423. int colIndex = 0;
  3424. if (mFillOrder == foColumnsFirst)
  3425. {
  3426. while (hasElement(rowIndex, colIndex))
  3427. {
  3428. ++colIndex;
  3429. if (colIndex >= mWrap && mWrap > 0)
  3430. {
  3431. colIndex = 0;
  3432. ++rowIndex;
  3433. }
  3434. }
  3435. } else
  3436. {
  3437. while (hasElement(rowIndex, colIndex))
  3438. {
  3439. ++rowIndex;
  3440. if (rowIndex >= mWrap && mWrap > 0)
  3441. {
  3442. rowIndex = 0;
  3443. ++colIndex;
  3444. }
  3445. }
  3446. }
  3447. return addElement(rowIndex, colIndex, element);
  3448. }
  3449. /*!
  3450. Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't
  3451. empty.
  3452. \see element
  3453. */
  3454. bool QCPLayoutGrid::hasElement(int row, int column)
  3455. {
  3456. if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount())
  3457. return mElements.at(row).at(column);
  3458. else
  3459. return false;
  3460. }
  3461. /*!
  3462. Sets the stretch \a factor of \a column.
  3463. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  3464. their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
  3465. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
  3466. QCPLayoutElement::setSizeConstraintRect.)
  3467. The default stretch factor of newly created rows/columns is 1.
  3468. \see setColumnStretchFactors, setRowStretchFactor
  3469. */
  3470. void QCPLayoutGrid::setColumnStretchFactor(int column, double factor)
  3471. {
  3472. if (column >= 0 && column < columnCount())
  3473. {
  3474. if (factor > 0)
  3475. mColumnStretchFactors[column] = factor;
  3476. else
  3477. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
  3478. } else
  3479. qDebug() << Q_FUNC_INFO << "Invalid column:" << column;
  3480. }
  3481. /*!
  3482. Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount.
  3483. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  3484. their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
  3485. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
  3486. QCPLayoutElement::setSizeConstraintRect.)
  3487. The default stretch factor of newly created rows/columns is 1.
  3488. \see setColumnStretchFactor, setRowStretchFactors
  3489. */
  3490. void QCPLayoutGrid::setColumnStretchFactors(const QList<double> &factors)
  3491. {
  3492. if (factors.size() == mColumnStretchFactors.size())
  3493. {
  3494. mColumnStretchFactors = factors;
  3495. for (int i=0; i<mColumnStretchFactors.size(); ++i)
  3496. {
  3497. if (mColumnStretchFactors.at(i) <= 0)
  3498. {
  3499. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mColumnStretchFactors.at(i);
  3500. mColumnStretchFactors[i] = 1;
  3501. }
  3502. }
  3503. } else
  3504. qDebug() << Q_FUNC_INFO << "Column count not equal to passed stretch factor count:" << factors;
  3505. }
  3506. /*!
  3507. Sets the stretch \a factor of \a row.
  3508. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  3509. their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
  3510. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
  3511. QCPLayoutElement::setSizeConstraintRect.)
  3512. The default stretch factor of newly created rows/columns is 1.
  3513. \see setColumnStretchFactors, setRowStretchFactor
  3514. */
  3515. void QCPLayoutGrid::setRowStretchFactor(int row, double factor)
  3516. {
  3517. if (row >= 0 && row < rowCount())
  3518. {
  3519. if (factor > 0)
  3520. mRowStretchFactors[row] = factor;
  3521. else
  3522. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
  3523. } else
  3524. qDebug() << Q_FUNC_INFO << "Invalid row:" << row;
  3525. }
  3526. /*!
  3527. Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount.
  3528. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  3529. their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
  3530. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
  3531. QCPLayoutElement::setSizeConstraintRect.)
  3532. The default stretch factor of newly created rows/columns is 1.
  3533. \see setRowStretchFactor, setColumnStretchFactors
  3534. */
  3535. void QCPLayoutGrid::setRowStretchFactors(const QList<double> &factors)
  3536. {
  3537. if (factors.size() == mRowStretchFactors.size())
  3538. {
  3539. mRowStretchFactors = factors;
  3540. for (int i=0; i<mRowStretchFactors.size(); ++i)
  3541. {
  3542. if (mRowStretchFactors.at(i) <= 0)
  3543. {
  3544. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mRowStretchFactors.at(i);
  3545. mRowStretchFactors[i] = 1;
  3546. }
  3547. }
  3548. } else
  3549. qDebug() << Q_FUNC_INFO << "Row count not equal to passed stretch factor count:" << factors;
  3550. }
  3551. /*!
  3552. Sets the gap that is left blank between columns to \a pixels.
  3553. \see setRowSpacing
  3554. */
  3555. void QCPLayoutGrid::setColumnSpacing(int pixels)
  3556. {
  3557. mColumnSpacing = pixels;
  3558. }
  3559. /*!
  3560. Sets the gap that is left blank between rows to \a pixels.
  3561. \see setColumnSpacing
  3562. */
  3563. void QCPLayoutGrid::setRowSpacing(int pixels)
  3564. {
  3565. mRowSpacing = pixels;
  3566. }
  3567. /*!
  3568. Sets the maximum number of columns or rows that are used, before new elements added with \ref
  3569. addElement(QCPLayoutElement*) will start to fill the next row or column, respectively. It depends
  3570. on \ref setFillOrder, whether rows or columns are wrapped.
  3571. If \a count is set to zero, no wrapping will ever occur.
  3572. If you wish to re-wrap the elements currently in the layout, call \ref setFillOrder with \a
  3573. rearrange set to true (the actual fill order doesn't need to be changed for the rearranging to be
  3574. done).
  3575. Note that the method \ref addElement(int row, int column, QCPLayoutElement *element) with
  3576. explicitly stated row and column is not subject to wrapping and can place elements even beyond
  3577. the specified wrapping point.
  3578. \see setFillOrder
  3579. */
  3580. void QCPLayoutGrid::setWrap(int count)
  3581. {
  3582. mWrap = qMax(0, count);
  3583. }
  3584. /*!
  3585. Sets the filling order and wrapping behaviour that is used when adding new elements with the
  3586. method \ref addElement(QCPLayoutElement*).
  3587. The specified \a order defines whether rows or columns are filled first. Using \ref setWrap, you
  3588. can control at which row/column count wrapping into the next column/row will occur. If you set it
  3589. to zero, no wrapping will ever occur. Changing the fill order also changes the meaning of the
  3590. linear index used e.g. in \ref elementAt and \ref takeAt. The default fill order for \ref
  3591. QCPLayoutGrid is \ref foColumnsFirst.
  3592. If you want to have all current elements arranged in the new order, set \a rearrange to true. The
  3593. elements will be rearranged in a way that tries to preserve their linear index. However, empty
  3594. cells are skipped during build-up of the new cell order, which shifts the succeeding element's
  3595. index. The rearranging is performed even if the specified \a order is already the current fill
  3596. order. Thus this method can be used to re-wrap the current elements.
  3597. If \a rearrange is false, the current element arrangement is not changed, which means the
  3598. linear indexes change (because the linear index is dependent on the fill order).
  3599. Note that the method \ref addElement(int row, int column, QCPLayoutElement *element) with
  3600. explicitly stated row and column is not subject to wrapping and can place elements even beyond
  3601. the specified wrapping point.
  3602. \see setWrap, addElement(QCPLayoutElement*)
  3603. */
  3604. void QCPLayoutGrid::setFillOrder(FillOrder order, bool rearrange)
  3605. {
  3606. // if rearranging, take all elements via linear index of old fill order:
  3607. const int elCount = elementCount();
  3608. QVector<QCPLayoutElement*> tempElements;
  3609. if (rearrange)
  3610. {
  3611. tempElements.reserve(elCount);
  3612. for (int i=0; i<elCount; ++i)
  3613. {
  3614. if (elementAt(i))
  3615. tempElements.append(takeAt(i));
  3616. }
  3617. simplify();
  3618. }
  3619. // change fill order as requested:
  3620. mFillOrder = order;
  3621. // if rearranging, re-insert via linear index according to new fill order:
  3622. if (rearrange)
  3623. {
  3624. foreach (QCPLayoutElement *tempElement, tempElements)
  3625. addElement(tempElement);
  3626. }
  3627. }
  3628. /*!
  3629. Expands the layout to have \a newRowCount rows and \a newColumnCount columns. So the last valid
  3630. row index will be \a newRowCount-1, the last valid column index will be \a newColumnCount-1.
  3631. If the current column/row count is already larger or equal to \a newColumnCount/\a newRowCount,
  3632. this function does nothing in that dimension.
  3633. Newly created cells are empty, new rows and columns have the stretch factor 1.
  3634. Note that upon a call to \ref addElement, the layout is expanded automatically to contain the
  3635. specified row and column, using this function.
  3636. \see simplify
  3637. */
  3638. void QCPLayoutGrid::expandTo(int newRowCount, int newColumnCount)
  3639. {
  3640. // add rows as necessary:
  3641. while (rowCount() < newRowCount)
  3642. {
  3643. mElements.append(QList<QCPLayoutElement*>());
  3644. mRowStretchFactors.append(1);
  3645. }
  3646. // go through rows and expand columns as necessary:
  3647. int newColCount = qMax(columnCount(), newColumnCount);
  3648. for (int i=0; i<rowCount(); ++i)
  3649. {
  3650. while (mElements.at(i).size() < newColCount)
  3651. mElements[i].append(nullptr);
  3652. }
  3653. while (mColumnStretchFactors.size() < newColCount)
  3654. mColumnStretchFactors.append(1);
  3655. }
  3656. /*!
  3657. Inserts a new row with empty cells at the row index \a newIndex. Valid values for \a newIndex
  3658. range from 0 (inserts a row at the top) to \a rowCount (appends a row at the bottom).
  3659. \see insertColumn
  3660. */
  3661. void QCPLayoutGrid::insertRow(int newIndex)
  3662. {
  3663. if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
  3664. {
  3665. expandTo(1, 1);
  3666. return;
  3667. }
  3668. if (newIndex < 0)
  3669. newIndex = 0;
  3670. if (newIndex > rowCount())
  3671. newIndex = rowCount();
  3672. mRowStretchFactors.insert(newIndex, 1);
  3673. QList<QCPLayoutElement*> newRow;
  3674. for (int col=0; col<columnCount(); ++col)
  3675. newRow.append(nullptr);
  3676. mElements.insert(newIndex, newRow);
  3677. }
  3678. /*!
  3679. Inserts a new column with empty cells at the column index \a newIndex. Valid values for \a
  3680. newIndex range from 0 (inserts a column at the left) to \a columnCount (appends a column at the
  3681. right).
  3682. \see insertRow
  3683. */
  3684. void QCPLayoutGrid::insertColumn(int newIndex)
  3685. {
  3686. if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
  3687. {
  3688. expandTo(1, 1);
  3689. return;
  3690. }
  3691. if (newIndex < 0)
  3692. newIndex = 0;
  3693. if (newIndex > columnCount())
  3694. newIndex = columnCount();
  3695. mColumnStretchFactors.insert(newIndex, 1);
  3696. for (int row=0; row<rowCount(); ++row)
  3697. mElements[row].insert(newIndex, nullptr);
  3698. }
  3699. /*!
  3700. Converts the given \a row and \a column to the linear index used by some methods of \ref
  3701. QCPLayoutGrid and \ref QCPLayout.
  3702. The way the cells are indexed depends on \ref setFillOrder. If it is \ref foRowsFirst, the
  3703. indices increase left to right and then top to bottom. If it is \ref foColumnsFirst, the indices
  3704. increase top to bottom and then left to right.
  3705. For the returned index to be valid, \a row and \a column must be valid indices themselves, i.e.
  3706. greater or equal to zero and smaller than the current \ref rowCount/\ref columnCount.
  3707. \see indexToRowCol
  3708. */
  3709. int QCPLayoutGrid::rowColToIndex(int row, int column) const
  3710. {
  3711. if (row >= 0 && row < rowCount())
  3712. {
  3713. if (column >= 0 && column < columnCount())
  3714. {
  3715. switch (mFillOrder)
  3716. {
  3717. case foRowsFirst: return column*rowCount() + row;
  3718. case foColumnsFirst: return row*columnCount() + column;
  3719. }
  3720. } else
  3721. qDebug() << Q_FUNC_INFO << "row index out of bounds:" << row;
  3722. } else
  3723. qDebug() << Q_FUNC_INFO << "column index out of bounds:" << column;
  3724. return 0;
  3725. }
  3726. /*!
  3727. Converts the linear index to row and column indices and writes the result to \a row and \a
  3728. column.
  3729. The way the cells are indexed depends on \ref setFillOrder. If it is \ref foRowsFirst, the
  3730. indices increase left to right and then top to bottom. If it is \ref foColumnsFirst, the indices
  3731. increase top to bottom and then left to right.
  3732. If there are no cells (i.e. column or row count is zero), sets \a row and \a column to -1.
  3733. For the retrieved \a row and \a column to be valid, the passed \a index must be valid itself,
  3734. i.e. greater or equal to zero and smaller than the current \ref elementCount.
  3735. \see rowColToIndex
  3736. */
  3737. void QCPLayoutGrid::indexToRowCol(int index, int &row, int &column) const
  3738. {
  3739. row = -1;
  3740. column = -1;
  3741. const int nCols = columnCount();
  3742. const int nRows = rowCount();
  3743. if (nCols == 0 || nRows == 0)
  3744. return;
  3745. if (index < 0 || index >= elementCount())
  3746. {
  3747. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  3748. return;
  3749. }
  3750. switch (mFillOrder)
  3751. {
  3752. case foRowsFirst:
  3753. {
  3754. column = index / nRows;
  3755. row = index % nRows;
  3756. break;
  3757. }
  3758. case foColumnsFirst:
  3759. {
  3760. row = index / nCols;
  3761. column = index % nCols;
  3762. break;
  3763. }
  3764. }
  3765. }
  3766. /* inherits documentation from base class */
  3767. void QCPLayoutGrid::updateLayout()
  3768. {
  3769. QVector<double> minColWidths, minRowHeights, maxColWidths, maxRowHeights;
  3770. getMinimumRowColSizes(&minColWidths, &minRowHeights);
  3771. getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
  3772. int totalRowSpacing = (rowCount()-1) * mRowSpacing;
  3773. int totalColSpacing = (columnCount()-1) * mColumnSpacing;
  3774. QVector<double> colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing);
  3775. QVector<double> rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing);
  3776. // go through cells and set rects accordingly:
  3777. double yOffset = mRect.top();
  3778. for (int row=0; row<rowCount(); ++row)
  3779. {
  3780. if (row > 0)
  3781. yOffset += rowHeights.at(row-1)+mRowSpacing;
  3782. double xOffset = mRect.left();
  3783. for (int col=0; col<columnCount(); ++col)
  3784. {
  3785. if (col > 0)
  3786. xOffset += colWidths.at(col-1)+mColumnSpacing;
  3787. if (mElements.at(row).at(col))
  3788. mElements.at(row).at(col)->setOuterRect(QRectF(xOffset, yOffset, colWidths.at(col), rowHeights.at(row)));
  3789. }
  3790. }
  3791. }
  3792. /*!
  3793. \seebaseclassmethod
  3794. Note that the association of the linear \a index to the row/column based cells depends on the
  3795. current setting of \ref setFillOrder.
  3796. \see rowColToIndex
  3797. */
  3798. QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const
  3799. {
  3800. if (index >= 0 && index < elementCount())
  3801. {
  3802. int row, col;
  3803. indexToRowCol(index, row, col);
  3804. return mElements.at(row).at(col);
  3805. } else
  3806. return nullptr;
  3807. }
  3808. /*!
  3809. \seebaseclassmethod
  3810. Note that the association of the linear \a index to the row/column based cells depends on the
  3811. current setting of \ref setFillOrder.
  3812. \see rowColToIndex
  3813. */
  3814. QCPLayoutElement *QCPLayoutGrid::takeAt(int index)
  3815. {
  3816. if (QCPLayoutElement *el = elementAt(index))
  3817. {
  3818. releaseElement(el);
  3819. int row, col;
  3820. indexToRowCol(index, row, col);
  3821. mElements[row][col] = nullptr;
  3822. return el;
  3823. } else
  3824. {
  3825. qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
  3826. return nullptr;
  3827. }
  3828. }
  3829. /* inherits documentation from base class */
  3830. bool QCPLayoutGrid::take(QCPLayoutElement *element)
  3831. {
  3832. if (element)
  3833. {
  3834. for (int i=0; i<elementCount(); ++i)
  3835. {
  3836. if (elementAt(i) == element)
  3837. {
  3838. takeAt(i);
  3839. return true;
  3840. }
  3841. }
  3842. qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
  3843. } else
  3844. qDebug() << Q_FUNC_INFO << "Can't take nullptr element";
  3845. return false;
  3846. }
  3847. /* inherits documentation from base class */
  3848. QList<QCPLayoutElement*> QCPLayoutGrid::elements(bool recursive) const
  3849. {
  3850. QList<QCPLayoutElement*> result;
  3851. const int elCount = elementCount();
  3852. #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
  3853. result.reserve(elCount);
  3854. #endif
  3855. for (int i=0; i<elCount; ++i)
  3856. result.append(elementAt(i));
  3857. if (recursive)
  3858. {
  3859. for (int i=0; i<elCount; ++i)
  3860. {
  3861. if (result.at(i))
  3862. result << result.at(i)->elements(recursive);
  3863. }
  3864. }
  3865. return result;
  3866. }
  3867. /*!
  3868. Simplifies the layout by collapsing rows and columns which only contain empty cells.
  3869. */
  3870. void QCPLayoutGrid::simplify()
  3871. {
  3872. // remove rows with only empty cells:
  3873. for (int row=rowCount()-1; row>=0; --row)
  3874. {
  3875. bool hasElements = false;
  3876. for (int col=0; col<columnCount(); ++col)
  3877. {
  3878. if (mElements.at(row).at(col))
  3879. {
  3880. hasElements = true;
  3881. break;
  3882. }
  3883. }
  3884. if (!hasElements)
  3885. {
  3886. mRowStretchFactors.removeAt(row);
  3887. mElements.removeAt(row);
  3888. if (mElements.isEmpty()) // removed last element, also remove stretch factor (wouldn't happen below because also columnCount changed to 0 now)
  3889. mColumnStretchFactors.clear();
  3890. }
  3891. }
  3892. // remove columns with only empty cells:
  3893. for (int col=columnCount()-1; col>=0; --col)
  3894. {
  3895. bool hasElements = false;
  3896. for (int row=0; row<rowCount(); ++row)
  3897. {
  3898. if (mElements.at(row).at(col))
  3899. {
  3900. hasElements = true;
  3901. break;
  3902. }
  3903. }
  3904. if (!hasElements)
  3905. {
  3906. mColumnStretchFactors.removeAt(col);
  3907. for (int row=0; row<rowCount(); ++row)
  3908. mElements[row].removeAt(col);
  3909. }
  3910. }
  3911. }
  3912. /* inherits documentation from base class */
  3913. QSizeF QCPLayoutGrid::minimumOuterSizeHint() const
  3914. {
  3915. QVector<double> minColWidths, minRowHeights;
  3916. getMinimumRowColSizes(&minColWidths, &minRowHeights);
  3917. QSizeF result(0, 0);
  3918. foreach (double w, minColWidths)
  3919. result.rwidth() += w;
  3920. foreach (double h, minRowHeights)
  3921. result.rheight() += h;
  3922. result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing;
  3923. result.rheight() += qMax(0, rowCount()-1) * mRowSpacing;
  3924. result.rwidth() += mMargins.left()+mMargins.right();
  3925. result.rheight() += mMargins.top()+mMargins.bottom();
  3926. return result;
  3927. }
  3928. /* inherits documentation from base class */
  3929. QSizeF QCPLayoutGrid::maximumOuterSizeHint() const
  3930. {
  3931. QVector<double> maxColWidths, maxRowHeights;
  3932. getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
  3933. QSizeF result(0, 0);
  3934. foreach (double w, maxColWidths)
  3935. result.setWidth(qMin(double(result.width())+w, double(QWIDGETSIZE_MAX)));
  3936. foreach (double h, maxRowHeights)
  3937. result.setHeight(qMin(double(result.height())+h, double(QWIDGETSIZE_MAX)));
  3938. result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing;
  3939. result.rheight() += qMax(0, rowCount()-1) * mRowSpacing;
  3940. result.rwidth() += mMargins.left()+mMargins.right();
  3941. result.rheight() += mMargins.top()+mMargins.bottom();
  3942. if (result.height() > QWIDGETSIZE_MAX)
  3943. result.setHeight(QWIDGETSIZE_MAX);
  3944. if (result.width() > QWIDGETSIZE_MAX)
  3945. result.setWidth(QWIDGETSIZE_MAX);
  3946. return result;
  3947. }
  3948. /*! \internal
  3949. Places the minimum column widths and row heights into \a minColWidths and \a minRowHeights
  3950. respectively.
  3951. The minimum height of a row is the largest minimum height of any element's outer rect in that
  3952. row. The minimum width of a column is the largest minimum width of any element's outer rect in
  3953. that column.
  3954. This is a helper function for \ref updateLayout.
  3955. \see getMaximumRowColSizes
  3956. */
  3957. void QCPLayoutGrid::getMinimumRowColSizes(QVector<double> *minColWidths, QVector<double> *minRowHeights) const
  3958. {
  3959. *minColWidths = QVector<double>(columnCount(), 0);
  3960. *minRowHeights = QVector<double>(rowCount(), 0);
  3961. for (int row=0; row<rowCount(); ++row)
  3962. {
  3963. for (int col=0; col<columnCount(); ++col)
  3964. {
  3965. if (QCPLayoutElement *el = mElements.at(row).at(col))
  3966. {
  3967. QSizeF minSize = getFinalMinimumOuterSize(el);
  3968. if (minColWidths->at(col) < minSize.width())
  3969. (*minColWidths)[col] = minSize.width();
  3970. if (minRowHeights->at(row) < minSize.height())
  3971. (*minRowHeights)[row] = minSize.height();
  3972. }
  3973. }
  3974. }
  3975. }
  3976. /*! \internal
  3977. Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights
  3978. respectively.
  3979. The maximum height of a row is the smallest maximum height of any element's outer rect in that
  3980. row. The maximum width of a column is the smallest maximum width of any element's outer rect in
  3981. that column.
  3982. This is a helper function for \ref updateLayout.
  3983. \see getMinimumRowColSizes
  3984. */
  3985. void QCPLayoutGrid::getMaximumRowColSizes(QVector<double> *maxColWidths, QVector<double> *maxRowHeights) const
  3986. {
  3987. *maxColWidths = QVector<double>(columnCount(), QWIDGETSIZE_MAX);
  3988. *maxRowHeights = QVector<double>(rowCount(), QWIDGETSIZE_MAX);
  3989. for (int row=0; row<rowCount(); ++row)
  3990. {
  3991. for (int col=0; col<columnCount(); ++col)
  3992. {
  3993. if (QCPLayoutElement *el = mElements.at(row).at(col))
  3994. {
  3995. QSizeF maxSize = getFinalMaximumOuterSize(el);
  3996. if (maxColWidths->at(col) > maxSize.width())
  3997. (*maxColWidths)[col] = maxSize.width();
  3998. if (maxRowHeights->at(row) > maxSize.height())
  3999. (*maxRowHeights)[row] = maxSize.height();
  4000. }
  4001. }
  4002. }
  4003. }
  4004. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4005. //////////////////// QCPLayoutInset
  4006. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4007. /*! \class QCPLayoutInset
  4008. \brief A layout that places child elements aligned to the border or arbitrarily positioned
  4009. Elements are placed either aligned to the border or at arbitrary position in the area of the
  4010. layout. Which placement applies is controlled with the \ref InsetPlacement (\ref
  4011. setInsetPlacement).
  4012. Elements are added via \ref addElement(QCPLayoutElement *element, Qt::Alignment alignment) or
  4013. addElement(QCPLayoutElement *element, const QRectF &rect). If the first method is used, the inset
  4014. placement will default to \ref ipBorderAligned and the element will be aligned according to the
  4015. \a alignment parameter. The second method defaults to \ref ipFree and allows placing elements at
  4016. arbitrary position and size, defined by \a rect.
  4017. The alignment or rect can be set via \ref setInsetAlignment or \ref setInsetRect, respectively.
  4018. This is the layout that every QCPAxisRect has as \ref QCPAxisRect::insetLayout.
  4019. */
  4020. /* start documentation of inline functions */
  4021. /*! \fn virtual void QCPLayoutInset::simplify()
  4022. The QCPInsetLayout does not need simplification since it can never have empty cells due to its
  4023. linear index structure. This method does nothing.
  4024. */
  4025. /* end documentation of inline functions */
  4026. /*!
  4027. Creates an instance of QCPLayoutInset and sets default values.
  4028. */
  4029. QCPLayoutInset::QCPLayoutInset()
  4030. {
  4031. }
  4032. QCPLayoutInset::~QCPLayoutInset()
  4033. {
  4034. // clear all child layout elements. This is important because only the specific layouts know how
  4035. // to handle removing elements (clear calls virtual removeAt method to do that).
  4036. clear();
  4037. }
  4038. /*!
  4039. Returns the placement type of the element with the specified \a index.
  4040. */
  4041. QCPLayoutInset::InsetPlacement QCPLayoutInset::insetPlacement(int index) const
  4042. {
  4043. if (elementAt(index))
  4044. return mInsetPlacement.at(index);
  4045. else
  4046. {
  4047. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4048. return ipFree;
  4049. }
  4050. }
  4051. /*!
  4052. Returns the alignment of the element with the specified \a index. The alignment only has a
  4053. meaning, if the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned.
  4054. */
  4055. Qt::Alignment QCPLayoutInset::insetAlignment(int index) const
  4056. {
  4057. if (elementAt(index))
  4058. return mInsetAlignment.at(index);
  4059. else
  4060. {
  4061. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4062. #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0)
  4063. return nullptr;
  4064. #else
  4065. return {};
  4066. #endif
  4067. }
  4068. }
  4069. /*!
  4070. Returns the rect of the element with the specified \a index. The rect only has a
  4071. meaning, if the inset placement (\ref setInsetPlacement) is \ref ipFree.
  4072. */
  4073. QRectF QCPLayoutInset::insetRect(int index) const
  4074. {
  4075. if (elementAt(index))
  4076. return mInsetRect.at(index);
  4077. else
  4078. {
  4079. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4080. return {};
  4081. }
  4082. }
  4083. /*!
  4084. Sets the inset placement type of the element with the specified \a index to \a placement.
  4085. \see InsetPlacement
  4086. */
  4087. void QCPLayoutInset::setInsetPlacement(int index, QCPLayoutInset::InsetPlacement placement)
  4088. {
  4089. if (elementAt(index))
  4090. mInsetPlacement[index] = placement;
  4091. else
  4092. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4093. }
  4094. /*!
  4095. If the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned, this function
  4096. is used to set the alignment of the element with the specified \a index to \a alignment.
  4097. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
  4098. Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
  4099. alignment flags will be ignored.
  4100. */
  4101. void QCPLayoutInset::setInsetAlignment(int index, Qt::Alignment alignment)
  4102. {
  4103. if (elementAt(index))
  4104. mInsetAlignment[index] = alignment;
  4105. else
  4106. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4107. }
  4108. /*!
  4109. If the inset placement (\ref setInsetPlacement) is \ref ipFree, this function is used to set the
  4110. position and size of the element with the specified \a index to \a rect.
  4111. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
  4112. will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
  4113. corner of the layout, with 35% width and height of the parent layout.
  4114. Note that the minimum and maximum sizes of the embedded element (\ref
  4115. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize) are enforced.
  4116. */
  4117. void QCPLayoutInset::setInsetRect(int index, const QRectF &rect)
  4118. {
  4119. if (elementAt(index))
  4120. mInsetRect[index] = rect;
  4121. else
  4122. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4123. }
  4124. /* inherits documentation from base class */
  4125. void QCPLayoutInset::updateLayout()
  4126. {
  4127. for (int i=0; i<mElements.size(); ++i)
  4128. {
  4129. QCPLayoutElement *el = mElements.at(i);
  4130. QRectF insetRect;
  4131. QSizeF finalMinSize = getFinalMinimumOuterSize(el);
  4132. QSizeF finalMaxSize = getFinalMaximumOuterSize(el);
  4133. if (mInsetPlacement.at(i) == ipFree)
  4134. {
  4135. insetRect = QRectF(rect().x()+rect().width()*mInsetRect.at(i).x(),
  4136. rect().y()+rect().height()*mInsetRect.at(i).y(),
  4137. rect().width()*mInsetRect.at(i).width(),
  4138. rect().height()*mInsetRect.at(i).height());
  4139. if (insetRect.size().width() < finalMinSize.width())
  4140. insetRect.setWidth(finalMinSize.width());
  4141. if (insetRect.size().height() < finalMinSize.height())
  4142. insetRect.setHeight(finalMinSize.height());
  4143. if (insetRect.size().width() > finalMaxSize.width())
  4144. insetRect.setWidth(finalMaxSize.width());
  4145. if (insetRect.size().height() > finalMaxSize.height())
  4146. insetRect.setHeight(finalMaxSize.height());
  4147. } else if (mInsetPlacement.at(i) == ipBorderAligned)
  4148. {
  4149. insetRect.setSize(finalMinSize);
  4150. Qt::Alignment al = mInsetAlignment.at(i);
  4151. if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x());
  4152. else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width());
  4153. else insetRect.moveLeft(rect().x()+rect().width()*0.5-finalMinSize.width()*0.5); // default to Qt::AlignHCenter
  4154. if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y());
  4155. else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height());
  4156. else insetRect.moveTop(rect().y()+rect().height()*0.5-finalMinSize.height()*0.5); // default to Qt::AlignVCenter
  4157. }
  4158. mElements.at(i)->setOuterRect(insetRect);
  4159. }
  4160. }
  4161. /* inherits documentation from base class */
  4162. int QCPLayoutInset::elementCount() const
  4163. {
  4164. return mElements.size();
  4165. }
  4166. /* inherits documentation from base class */
  4167. QCPLayoutElement *QCPLayoutInset::elementAt(int index) const
  4168. {
  4169. if (index >= 0 && index < mElements.size())
  4170. return mElements.at(index);
  4171. else
  4172. return nullptr;
  4173. }
  4174. /* inherits documentation from base class */
  4175. QCPLayoutElement *QCPLayoutInset::takeAt(int index)
  4176. {
  4177. if (QCPLayoutElement *el = elementAt(index))
  4178. {
  4179. releaseElement(el);
  4180. mElements.removeAt(index);
  4181. mInsetPlacement.removeAt(index);
  4182. mInsetAlignment.removeAt(index);
  4183. mInsetRect.removeAt(index);
  4184. return el;
  4185. } else
  4186. {
  4187. qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
  4188. return nullptr;
  4189. }
  4190. }
  4191. /* inherits documentation from base class */
  4192. bool QCPLayoutInset::take(QCPLayoutElement *element)
  4193. {
  4194. if (element)
  4195. {
  4196. for (int i=0; i<elementCount(); ++i)
  4197. {
  4198. if (elementAt(i) == element)
  4199. {
  4200. takeAt(i);
  4201. return true;
  4202. }
  4203. }
  4204. qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
  4205. } else
  4206. qDebug() << Q_FUNC_INFO << "Can't take nullptr element";
  4207. return false;
  4208. }
  4209. /*!
  4210. The inset layout is sensitive to events only at areas where its (visible) child elements are
  4211. sensitive. If the selectTest method of any of the child elements returns a positive number for \a
  4212. pos, this method returns a value corresponding to 0.99 times the parent plot's selection
  4213. tolerance. The inset layout is not selectable itself by default. So if \a onlySelectable is true,
  4214. -1.0 is returned.
  4215. See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
  4216. */
  4217. double QCPLayoutInset::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  4218. {
  4219. Q_UNUSED(details)
  4220. if (onlySelectable)
  4221. return -1;
  4222. foreach (QCPLayoutElement *el, mElements)
  4223. {
  4224. // inset layout shall only return positive selectTest, if actually an inset object is at pos
  4225. // else it would block the entire underlying QCPAxisRect with its surface.
  4226. if (el->realVisibility() && el->selectTest(pos, onlySelectable) >= 0)
  4227. return mParentPlot->selectionTolerance()*0.99;
  4228. }
  4229. return -1;
  4230. }
  4231. /*!
  4232. Adds the specified \a element to the layout as an inset aligned at the border (\ref
  4233. setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a
  4234. alignment.
  4235. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
  4236. Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
  4237. alignment flags will be ignored.
  4238. \see addElement(QCPLayoutElement *element, const QRectF &rect)
  4239. */
  4240. void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment)
  4241. {
  4242. if (element)
  4243. {
  4244. if (element->layout()) // remove from old layout first
  4245. element->layout()->take(element);
  4246. mElements.append(element);
  4247. mInsetPlacement.append(ipBorderAligned);
  4248. mInsetAlignment.append(alignment);
  4249. mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4));
  4250. adoptElement(element);
  4251. } else
  4252. qDebug() << Q_FUNC_INFO << "Can't add nullptr element";
  4253. }
  4254. /*!
  4255. Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref
  4256. setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a
  4257. rect.
  4258. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
  4259. will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
  4260. corner of the layout, with 35% width and height of the parent layout.
  4261. \see addElement(QCPLayoutElement *element, Qt::Alignment alignment)
  4262. */
  4263. void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect)
  4264. {
  4265. if (element)
  4266. {
  4267. if (element->layout()) // remove from old layout first
  4268. element->layout()->take(element);
  4269. mElements.append(element);
  4270. mInsetPlacement.append(ipFree);
  4271. mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop);
  4272. mInsetRect.append(rect);
  4273. adoptElement(element);
  4274. } else
  4275. qDebug() << Q_FUNC_INFO << "Can't add nullptr element";
  4276. }
  4277. /* end of 'src/layout.cpp' */
  4278. /* including file 'src/lineending.cpp' */
  4279. /* modified 2021-03-29T02:30:44, size 11189 */
  4280. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4281. //////////////////// QCPLineEnding
  4282. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4283. /*! \class QCPLineEnding
  4284. \brief Handles the different ending decorations for line-like items
  4285. \image html QCPLineEnding.png "The various ending styles currently supported"
  4286. For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine
  4287. has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail.
  4288. The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can
  4289. be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of
  4290. the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item.
  4291. For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite
  4292. directions, e.g. "outward". This can be changed by \ref setInverted, which would make the
  4293. respective arrow point inward.
  4294. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a
  4295. QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g.
  4296. \snippet documentation/doc-code-snippets/mainwindow.cpp qcplineending-sethead
  4297. */
  4298. /*!
  4299. Creates a QCPLineEnding instance with default values (style \ref esNone).
  4300. */
  4301. QCPLineEnding::QCPLineEnding() :
  4302. mStyle(esNone),
  4303. mWidth(8),
  4304. mLength(10),
  4305. mInverted(false)
  4306. {
  4307. }
  4308. /*!
  4309. Creates a QCPLineEnding instance with the specified values.
  4310. */
  4311. QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) :
  4312. mStyle(style),
  4313. mWidth(width),
  4314. mLength(length),
  4315. mInverted(inverted)
  4316. {
  4317. }
  4318. /*!
  4319. Sets the style of the ending decoration.
  4320. */
  4321. void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style)
  4322. {
  4323. mStyle = style;
  4324. }
  4325. /*!
  4326. Sets the width of the ending decoration, if the style supports it. On arrows, for example, the
  4327. width defines the size perpendicular to the arrow's pointing direction.
  4328. \see setLength
  4329. */
  4330. void QCPLineEnding::setWidth(double width)
  4331. {
  4332. mWidth = width;
  4333. }
  4334. /*!
  4335. Sets the length of the ending decoration, if the style supports it. On arrows, for example, the
  4336. length defines the size in pointing direction.
  4337. \see setWidth
  4338. */
  4339. void QCPLineEnding::setLength(double length)
  4340. {
  4341. mLength = length;
  4342. }
  4343. /*!
  4344. Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point
  4345. inward when \a inverted is set to true.
  4346. Note that also the \a width direction is inverted. For symmetrical ending styles like arrows or
  4347. discs, this doesn't make a difference. However, asymmetric styles like \ref esHalfBar are
  4348. affected by it, which can be used to control to which side the half bar points to.
  4349. */
  4350. void QCPLineEnding::setInverted(bool inverted)
  4351. {
  4352. mInverted = inverted;
  4353. }
  4354. /*! \internal
  4355. Returns the maximum pixel radius the ending decoration might cover, starting from the position
  4356. the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item).
  4357. This is relevant for clipping. Only omit painting of the decoration when the position where the
  4358. decoration is supposed to be drawn is farther away from the clipping rect than the returned
  4359. distance.
  4360. */
  4361. double QCPLineEnding::boundingDistance() const
  4362. {
  4363. switch (mStyle)
  4364. {
  4365. case esNone:
  4366. return 0;
  4367. case esFlatArrow:
  4368. case esSpikeArrow:
  4369. case esLineArrow:
  4370. case esSkewedBar:
  4371. return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length
  4372. case esDisc:
  4373. case esSquare:
  4374. case esDiamond:
  4375. case esBar:
  4376. case esHalfBar:
  4377. return mWidth*1.42; // items that only have a width -> width*sqrt(2)
  4378. }
  4379. return 0;
  4380. }
  4381. /*!
  4382. Starting from the origin of this line ending (which is style specific), returns the length
  4383. covered by the line ending symbol, in backward direction.
  4384. For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if
  4385. both have the same \ref setLength value, because the spike arrow has an inward curved back, which
  4386. reduces the length along its center axis (the drawing origin for arrows is at the tip).
  4387. This function is used for precise, style specific placement of line endings, for example in
  4388. QCPAxes.
  4389. */
  4390. double QCPLineEnding::realLength() const
  4391. {
  4392. switch (mStyle)
  4393. {
  4394. case esNone:
  4395. case esLineArrow:
  4396. case esSkewedBar:
  4397. case esBar:
  4398. case esHalfBar:
  4399. return 0;
  4400. case esFlatArrow:
  4401. return mLength;
  4402. case esDisc:
  4403. case esSquare:
  4404. case esDiamond:
  4405. return mWidth*0.5;
  4406. case esSpikeArrow:
  4407. return mLength*0.8;
  4408. }
  4409. return 0;
  4410. }
  4411. /*! \internal
  4412. Draws the line ending with the specified \a painter at the position \a pos. The direction of the
  4413. line ending is controlled with \a dir.
  4414. */
  4415. void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, const QCPVector2D &dir) const
  4416. {
  4417. if (mStyle == esNone)
  4418. return;
  4419. QCPVector2D lengthVec = dir.normalized() * mLength*(mInverted ? -1 : 1);
  4420. if (lengthVec.isNull())
  4421. lengthVec = QCPVector2D(1, 0);
  4422. QCPVector2D widthVec = dir.normalized().perpendicular() * mWidth*0.5*(mInverted ? -1 : 1);
  4423. QPen penBackup = painter->pen();
  4424. QBrush brushBackup = painter->brush();
  4425. QPen miterPen = penBackup;
  4426. miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey
  4427. QBrush brush(painter->pen().color(), Qt::SolidPattern);
  4428. switch (mStyle)
  4429. {
  4430. case esNone: break;
  4431. case esFlatArrow:
  4432. {
  4433. QPointF points[3] = {pos.toPointF(),
  4434. (pos-lengthVec+widthVec).toPointF(),
  4435. (pos-lengthVec-widthVec).toPointF()
  4436. };
  4437. painter->setPen(miterPen);
  4438. painter->setBrush(brush);
  4439. painter->drawConvexPolygon(points, 3);
  4440. painter->setBrush(brushBackup);
  4441. painter->setPen(penBackup);
  4442. break;
  4443. }
  4444. case esSpikeArrow:
  4445. {
  4446. QPointF points[4] = {pos.toPointF(),
  4447. (pos-lengthVec+widthVec).toPointF(),
  4448. (pos-lengthVec*0.8).toPointF(),
  4449. (pos-lengthVec-widthVec).toPointF()
  4450. };
  4451. painter->setPen(miterPen);
  4452. painter->setBrush(brush);
  4453. painter->drawConvexPolygon(points, 4);
  4454. painter->setBrush(brushBackup);
  4455. painter->setPen(penBackup);
  4456. break;
  4457. }
  4458. case esLineArrow:
  4459. {
  4460. QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(),
  4461. pos.toPointF(),
  4462. (pos-lengthVec-widthVec).toPointF()
  4463. };
  4464. painter->setPen(miterPen);
  4465. painter->drawPolyline(points, 3);
  4466. painter->setPen(penBackup);
  4467. break;
  4468. }
  4469. case esDisc:
  4470. {
  4471. painter->setBrush(brush);
  4472. painter->drawEllipse(pos.toPointF(), mWidth*0.5, mWidth*0.5);
  4473. painter->setBrush(brushBackup);
  4474. break;
  4475. }
  4476. case esSquare:
  4477. {
  4478. QCPVector2D widthVecPerp = widthVec.perpendicular();
  4479. QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(),
  4480. (pos-widthVecPerp-widthVec).toPointF(),
  4481. (pos+widthVecPerp-widthVec).toPointF(),
  4482. (pos+widthVecPerp+widthVec).toPointF()
  4483. };
  4484. painter->setPen(miterPen);
  4485. painter->setBrush(brush);
  4486. painter->drawConvexPolygon(points, 4);
  4487. painter->setBrush(brushBackup);
  4488. painter->setPen(penBackup);
  4489. break;
  4490. }
  4491. case esDiamond:
  4492. {
  4493. QCPVector2D widthVecPerp = widthVec.perpendicular();
  4494. QPointF points[4] = {(pos-widthVecPerp).toPointF(),
  4495. (pos-widthVec).toPointF(),
  4496. (pos+widthVecPerp).toPointF(),
  4497. (pos+widthVec).toPointF()
  4498. };
  4499. painter->setPen(miterPen);
  4500. painter->setBrush(brush);
  4501. painter->drawConvexPolygon(points, 4);
  4502. painter->setBrush(brushBackup);
  4503. painter->setPen(penBackup);
  4504. break;
  4505. }
  4506. case esBar:
  4507. {
  4508. painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF());
  4509. break;
  4510. }
  4511. case esHalfBar:
  4512. {
  4513. painter->drawLine((pos+widthVec).toPointF(), pos.toPointF());
  4514. break;
  4515. }
  4516. case esSkewedBar:
  4517. {
  4518. QCPVector2D shift;
  4519. if (!qFuzzyIsNull(painter->pen().widthF()) || painter->modes().testFlag(QCPPainter::pmNonCosmetic))
  4520. shift = dir.normalized()*qMax(qreal(1.0), painter->pen().widthF())*qreal(0.5);
  4521. // if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly
  4522. painter->drawLine((pos+widthVec+lengthVec*0.2*(mInverted?-1:1)+shift).toPointF(),
  4523. (pos-widthVec-lengthVec*0.2*(mInverted?-1:1)+shift).toPointF());
  4524. break;
  4525. }
  4526. }
  4527. }
  4528. /*! \internal
  4529. \overload
  4530. Draws the line ending. The direction is controlled with the \a angle parameter in radians.
  4531. */
  4532. void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, double angle) const
  4533. {
  4534. draw(painter, pos, QCPVector2D(qCos(angle), qSin(angle)));
  4535. }
  4536. /* end of 'src/lineending.cpp' */
  4537. /* including file 'src/axis/labelpainter.cpp' */
  4538. /* modified 2021-03-29T02:30:44, size 27296 */
  4539. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4540. //////////////////// QCPLabelPainterPrivate
  4541. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4542. /*! \class QCPLabelPainterPrivate
  4543. \internal
  4544. \brief (Private)
  4545. This is a private class and not part of the public QCustomPlot interface.
  4546. */
  4547. const QChar QCPLabelPainterPrivate::SymbolDot(183);
  4548. const QChar QCPLabelPainterPrivate::SymbolCross(215);
  4549. /*!
  4550. Constructs a QCPLabelPainterPrivate instance. Make sure to not create a new
  4551. instance on every redraw, to utilize the caching mechanisms.
  4552. the \a parentPlot does not take ownership of the label painter. Make sure
  4553. to delete it appropriately.
  4554. */
  4555. QCPLabelPainterPrivate::QCPLabelPainterPrivate(QCustomPlot *parentPlot) :
  4556. mAnchorMode(amRectangular),
  4557. mAnchorSide(asLeft),
  4558. mAnchorReferenceType(artNormal),
  4559. mColor(Qt::black),
  4560. mPadding(0),
  4561. mRotation(0),
  4562. mSubstituteExponent(true),
  4563. mMultiplicationSymbol(QChar(215)),
  4564. mAbbreviateDecimalPowers(false),
  4565. mParentPlot(parentPlot),
  4566. mLabelCache(16)
  4567. {
  4568. analyzeFontMetrics();
  4569. }
  4570. QCPLabelPainterPrivate::~QCPLabelPainterPrivate()
  4571. {
  4572. }
  4573. void QCPLabelPainterPrivate::setAnchorSide(AnchorSide side)
  4574. {
  4575. mAnchorSide = side;
  4576. }
  4577. void QCPLabelPainterPrivate::setAnchorMode(AnchorMode mode)
  4578. {
  4579. mAnchorMode = mode;
  4580. }
  4581. void QCPLabelPainterPrivate::setAnchorReference(const QPointF &pixelPoint)
  4582. {
  4583. mAnchorReference = pixelPoint;
  4584. }
  4585. void QCPLabelPainterPrivate::setAnchorReferenceType(AnchorReferenceType type)
  4586. {
  4587. mAnchorReferenceType = type;
  4588. }
  4589. void QCPLabelPainterPrivate::setFont(const QFont &font)
  4590. {
  4591. if (mFont != font)
  4592. {
  4593. mFont = font;
  4594. analyzeFontMetrics();
  4595. }
  4596. }
  4597. void QCPLabelPainterPrivate::setColor(const QColor &color)
  4598. {
  4599. mColor = color;
  4600. }
  4601. void QCPLabelPainterPrivate::setPadding(int padding)
  4602. {
  4603. mPadding = padding;
  4604. }
  4605. void QCPLabelPainterPrivate::setRotation(double rotation)
  4606. {
  4607. mRotation = qBound(-90.0, rotation, 90.0);
  4608. }
  4609. void QCPLabelPainterPrivate::setSubstituteExponent(bool enabled)
  4610. {
  4611. mSubstituteExponent = enabled;
  4612. }
  4613. void QCPLabelPainterPrivate::setMultiplicationSymbol(QChar symbol)
  4614. {
  4615. mMultiplicationSymbol = symbol;
  4616. }
  4617. void QCPLabelPainterPrivate::setAbbreviateDecimalPowers(bool enabled)
  4618. {
  4619. mAbbreviateDecimalPowers = enabled;
  4620. }
  4621. void QCPLabelPainterPrivate::setCacheSize(int labelCount)
  4622. {
  4623. mLabelCache.setMaxCost(labelCount);
  4624. }
  4625. int QCPLabelPainterPrivate::cacheSize() const
  4626. {
  4627. return mLabelCache.maxCost();
  4628. }
  4629. void QCPLabelPainterPrivate::drawTickLabel(QCPPainter *painter, const QPointF &tickPos, const QString &text)
  4630. {
  4631. double realRotation = mRotation;
  4632. AnchorSide realSide = mAnchorSide;
  4633. // for circular axes, the anchor side is determined depending on the quadrant of tickPos with respect to mCircularReference
  4634. if (mAnchorMode == amSkewedUpright)
  4635. {
  4636. realSide = skewedAnchorSide(tickPos, 0.2, 0.3);
  4637. } else if (mAnchorMode == amSkewedRotated) // in this mode every label is individually rotated to match circle tangent
  4638. {
  4639. realSide = skewedAnchorSide(tickPos, 0, 0);
  4640. realRotation += QCPVector2D(tickPos-mAnchorReference).angle()/M_PI*180.0;
  4641. if (realRotation > 90) realRotation -= 180;
  4642. else if (realRotation < -90) realRotation += 180;
  4643. }
  4644. realSide = rotationCorrectedSide(realSide, realRotation); // rotation angles may change the true anchor side of the label
  4645. drawLabelMaybeCached(painter, mFont, mColor, getAnchorPos(tickPos), realSide, realRotation, text);
  4646. }
  4647. /*! \internal
  4648. Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone
  4649. direction) needed to fit the axis.
  4650. */
  4651. /* TODO: needed?
  4652. int QCPLabelPainterPrivate::size() const
  4653. {
  4654. int result = 0;
  4655. // get length of tick marks pointing outwards:
  4656. if (!tickPositions.isEmpty())
  4657. result += qMax(0, qMax(tickLengthOut, subTickLengthOut));
  4658. // calculate size of tick labels:
  4659. if (tickLabelSide == QCPAxis::lsOutside)
  4660. {
  4661. QSize tickLabelsSize(0, 0);
  4662. if (!tickLabels.isEmpty())
  4663. {
  4664. for (int i=0; i<tickLabels.size(); ++i)
  4665. getMaxTickLabelSize(tickLabelFont, tickLabels.at(i), &tickLabelsSize);
  4666. result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width();
  4667. result += tickLabelPadding;
  4668. }
  4669. }
  4670. // calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees):
  4671. if (!label.isEmpty())
  4672. {
  4673. QFontMetrics fontMetrics(labelFont);
  4674. QRect bounds;
  4675. bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label);
  4676. result += bounds.height() + labelPadding;
  4677. }
  4678. return result;
  4679. }
  4680. */
  4681. /*! \internal
  4682. Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This
  4683. method is called automatically if any parameters have changed that invalidate the cached labels,
  4684. such as font, color, etc. Usually you won't need to call this method manually.
  4685. */
  4686. void QCPLabelPainterPrivate::clearCache()
  4687. {
  4688. mLabelCache.clear();
  4689. }
  4690. /*! \internal
  4691. Returns a hash that allows uniquely identifying whether the label parameters have changed such
  4692. that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the
  4693. return value of this method hasn't changed since the last redraw, the respective label parameters
  4694. haven't changed and cached labels may be used.
  4695. */
  4696. QByteArray QCPLabelPainterPrivate::generateLabelParameterHash() const
  4697. {
  4698. QByteArray result;
  4699. result.append(QByteArray::number(mParentPlot->bufferDevicePixelRatio()));
  4700. result.append(QByteArray::number(mRotation));
  4701. //result.append(QByteArray::number((int)tickLabelSide)); TODO: check whether this is really a cache-invalidating property
  4702. result.append(QByteArray::number(int(mSubstituteExponent)));
  4703. result.append(QString(mMultiplicationSymbol).toUtf8());
  4704. result.append(mColor.name().toLatin1()+QByteArray::number(mColor.alpha(), 16));
  4705. result.append(mFont.toString().toLatin1());
  4706. return result;
  4707. }
  4708. /*! \internal
  4709. Draws a single tick label with the provided \a painter, utilizing the internal label cache to
  4710. significantly speed up drawing of labels that were drawn in previous calls. The tick label is
  4711. always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in
  4712. pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence
  4713. for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate),
  4714. at which the label should be drawn.
  4715. In order to later draw the axis label in a place that doesn't overlap with the tick labels, the
  4716. largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref
  4717. drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a
  4718. tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently
  4719. holds.
  4720. The label is drawn with the font and pen that are currently set on the \a painter. To draw
  4721. superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref
  4722. getTickLabelData).
  4723. */
  4724. void QCPLabelPainterPrivate::drawLabelMaybeCached(QCPPainter *painter, const QFont &font, const QColor &color, const QPointF &pos, AnchorSide side, double rotation, const QString &text)
  4725. {
  4726. // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly!
  4727. if (text.isEmpty()) return;
  4728. QSize finalSize;
  4729. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled
  4730. {
  4731. QByteArray key = cacheKey(text, color, rotation, side);
  4732. 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)
  4733. if (!cachedLabel) // no cached label existed, create it
  4734. {
  4735. LabelData labelData = getTickLabelData(font, color, rotation, side, text);
  4736. cachedLabel = createCachedLabel(labelData);
  4737. }
  4738. // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
  4739. bool labelClippedByBorder = false;
  4740. /*
  4741. if (tickLabelSide == QCPAxis::lsOutside)
  4742. {
  4743. if (QCPAxis::orientation(type) == Qt::Horizontal)
  4744. labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width()/mParentPlot->bufferDevicePixelRatio() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left();
  4745. else
  4746. labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height()/mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top();
  4747. }
  4748. */
  4749. if (!labelClippedByBorder)
  4750. {
  4751. painter->drawPixmap(pos+cachedLabel->offset, cachedLabel->pixmap);
  4752. finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio(); // TODO: collect this in a member rect list?
  4753. }
  4754. mLabelCache.insert(QString::fromUtf8(key), cachedLabel);
  4755. } else // label caching disabled, draw text directly on surface:
  4756. {
  4757. LabelData labelData = getTickLabelData(font, color, rotation, side, text);
  4758. // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
  4759. bool labelClippedByBorder = false;
  4760. /*
  4761. if (tickLabelSide == QCPAxis::lsOutside)
  4762. {
  4763. if (QCPAxis::orientation(type) == Qt::Horizontal)
  4764. labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left();
  4765. else
  4766. labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top();
  4767. }
  4768. */
  4769. if (!labelClippedByBorder)
  4770. {
  4771. drawText(painter, pos, labelData);
  4772. finalSize = labelData.rotatedTotalBounds.size();
  4773. }
  4774. }
  4775. /*
  4776. // expand passed tickLabelsSize if current tick label is larger:
  4777. if (finalSize.width() > tickLabelsSize->width())
  4778. tickLabelsSize->setWidth(finalSize.width());
  4779. if (finalSize.height() > tickLabelsSize->height())
  4780. tickLabelsSize->setHeight(finalSize.height());
  4781. */
  4782. }
  4783. QPointF QCPLabelPainterPrivate::getAnchorPos(const QPointF &tickPos)
  4784. {
  4785. switch (mAnchorMode)
  4786. {
  4787. case amRectangular:
  4788. {
  4789. switch (mAnchorSide)
  4790. {
  4791. case asLeft: return tickPos+QPointF(mPadding, 0);
  4792. case asRight: return tickPos+QPointF(-mPadding, 0);
  4793. case asTop: return tickPos+QPointF(0, mPadding);
  4794. case asBottom: return tickPos+QPointF(0, -mPadding);
  4795. case asTopLeft: return tickPos+QPointF(mPadding*M_SQRT1_2, mPadding*M_SQRT1_2);
  4796. case asTopRight: return tickPos+QPointF(-mPadding*M_SQRT1_2, mPadding*M_SQRT1_2);
  4797. case asBottomRight: return tickPos+QPointF(-mPadding*M_SQRT1_2, -mPadding*M_SQRT1_2);
  4798. case asBottomLeft: return tickPos+QPointF(mPadding*M_SQRT1_2, -mPadding*M_SQRT1_2);
  4799. }
  4800. }
  4801. case amSkewedUpright:
  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. }
  4811. return tickPos;
  4812. }
  4813. /*! \internal
  4814. This is a \ref placeTickLabel helper function.
  4815. Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a
  4816. y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to
  4817. directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when
  4818. QCP::phCacheLabels plotting hint is not set.
  4819. */
  4820. void QCPLabelPainterPrivate::drawText(QCPPainter *painter, const QPointF &pos, const LabelData &labelData) const
  4821. {
  4822. // backup painter settings that we're about to change:
  4823. QTransform oldTransform = painter->transform();
  4824. QFont oldFont = painter->font();
  4825. QPen oldPen = painter->pen();
  4826. // transform painter to position/rotation:
  4827. painter->translate(pos);
  4828. painter->setTransform(labelData.transform, true);
  4829. // draw text:
  4830. painter->setFont(labelData.baseFont);
  4831. painter->setPen(QPen(labelData.color));
  4832. if (!labelData.expPart.isEmpty()) // use superscripted exponent typesetting
  4833. {
  4834. painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart);
  4835. if (!labelData.suffixPart.isEmpty())
  4836. painter->drawText(labelData.baseBounds.width()+1+labelData.expBounds.width(), 0, 0, 0, Qt::TextDontClip, labelData.suffixPart);
  4837. painter->setFont(labelData.expFont);
  4838. painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart);
  4839. } else
  4840. {
  4841. painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart);
  4842. }
  4843. /* Debug code to draw label bounding boxes, baseline, and capheight
  4844. painter->save();
  4845. painter->setPen(QPen(QColor(0, 0, 0, 150)));
  4846. painter->drawRect(labelData.totalBounds);
  4847. const int baseline = labelData.totalBounds.height()-mLetterDescent;
  4848. painter->setPen(QPen(QColor(255, 0, 0, 150)));
  4849. painter->drawLine(QLineF(0, baseline, labelData.totalBounds.width(), baseline));
  4850. painter->setPen(QPen(QColor(0, 0, 255, 150)));
  4851. painter->drawLine(QLineF(0, baseline-mLetterCapHeight, labelData.totalBounds.width(), baseline-mLetterCapHeight));
  4852. painter->restore();
  4853. */
  4854. // reset painter settings to what it was before:
  4855. painter->setTransform(oldTransform);
  4856. painter->setFont(oldFont);
  4857. painter->setPen(oldPen);
  4858. }
  4859. /*! \internal
  4860. This is a \ref placeTickLabel helper function.
  4861. Transforms the passed \a text and \a font to a tickLabelData structure that can then be further
  4862. processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and
  4863. exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes.
  4864. */
  4865. QCPLabelPainterPrivate::LabelData QCPLabelPainterPrivate::getTickLabelData(const QFont &font, const QColor &color, double rotation, AnchorSide side, const QString &text) const
  4866. {
  4867. LabelData result;
  4868. result.rotation = rotation;
  4869. result.side = side;
  4870. result.color = color;
  4871. // determine whether beautiful decimal powers should be used
  4872. bool useBeautifulPowers = false;
  4873. int ePos = -1; // first index of exponent part, text before that will be basePart, text until eLast will be expPart
  4874. int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart
  4875. if (mSubstituteExponent)
  4876. {
  4877. ePos = text.indexOf(QLatin1Char('e'));
  4878. if (ePos > 0 && text.at(ePos-1).isDigit())
  4879. {
  4880. eLast = ePos;
  4881. while (eLast+1 < text.size() && (text.at(eLast+1) == QLatin1Char('+') || text.at(eLast+1) == QLatin1Char('-') || text.at(eLast+1).isDigit()))
  4882. ++eLast;
  4883. if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as beautifiable power
  4884. useBeautifulPowers = true;
  4885. }
  4886. }
  4887. // calculate text bounding rects and do string preparation for beautiful decimal powers:
  4888. result.baseFont = font;
  4889. if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line
  4890. 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
  4891. QFontMetrics baseFontMetrics(result.baseFont);
  4892. if (useBeautifulPowers)
  4893. {
  4894. // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent:
  4895. result.basePart = text.left(ePos);
  4896. result.suffixPart = text.mid(eLast+1); // also drawn normally but after exponent
  4897. // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base:
  4898. if (mAbbreviateDecimalPowers && result.basePart == QLatin1String("1"))
  4899. result.basePart = QLatin1String("10");
  4900. else
  4901. result.basePart += QString(mMultiplicationSymbol) + QLatin1String("10");
  4902. result.expPart = text.mid(ePos+1, eLast-ePos);
  4903. // clip "+" and leading zeros off expPart:
  4904. while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e'
  4905. result.expPart.remove(1, 1);
  4906. if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+'))
  4907. result.expPart.remove(0, 1);
  4908. // prepare smaller font for exponent:
  4909. result.expFont = font;
  4910. if (result.expFont.pointSize() > 0)
  4911. result.expFont.setPointSizeF(result.expFont.pointSize()*0.75);
  4912. else
  4913. result.expFont.setPixelSize(int(result.expFont.pixelSize()*0.75));
  4914. // calculate bounding rects of base part(s), exponent part and total one:
  4915. result.baseBounds = baseFontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart);
  4916. result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart);
  4917. if (!result.suffixPart.isEmpty())
  4918. result.suffixBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.suffixPart);
  4919. 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
  4920. } else // useBeautifulPowers == false
  4921. {
  4922. result.basePart = text;
  4923. result.totalBounds = baseFontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart);
  4924. }
  4925. result.totalBounds.moveTopLeft(QPoint(0, 0));
  4926. applyAnchorTransform(result);
  4927. result.rotatedTotalBounds = result.transform.mapRect(result.totalBounds);
  4928. return result;
  4929. }
  4930. void QCPLabelPainterPrivate::applyAnchorTransform(LabelData &labelData) const
  4931. {
  4932. if (!qFuzzyIsNull(labelData.rotation))
  4933. labelData.transform.rotate(labelData.rotation); // rotates effectively clockwise (due to flipped y axis of painter vs widget coordinate system)
  4934. // from now on we translate in rotated label-local coordinate system.
  4935. // shift origin of coordinate system to appropriate point on label:
  4936. labelData.transform.translate(0, -labelData.totalBounds.height()+mLetterDescent+mLetterCapHeight); // shifts origin to true top of capital (or number) characters
  4937. if (labelData.side == asLeft || labelData.side == asRight) // anchor is centered vertically
  4938. labelData.transform.translate(0, -mLetterCapHeight/2.0);
  4939. else if (labelData.side == asTop || labelData.side == asBottom) // anchor is centered horizontally
  4940. labelData.transform.translate(-labelData.totalBounds.width()/2.0, 0);
  4941. if (labelData.side == asTopRight || labelData.side == asRight || labelData.side == asBottomRight) // anchor is at right
  4942. labelData.transform.translate(-labelData.totalBounds.width(), 0);
  4943. if (labelData.side == asBottomLeft || labelData.side == asBottom || labelData.side == asBottomRight) // anchor is at bottom (no elseif!)
  4944. labelData.transform.translate(0, -mLetterCapHeight);
  4945. }
  4946. /*! \internal
  4947. Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label
  4948. to be drawn, depending on number format etc. Since only the largest tick label is wanted for the
  4949. margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a
  4950. smaller width/height.
  4951. */
  4952. /*
  4953. void QCPLabelPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const
  4954. {
  4955. // note: this function must return the same tick label sizes as the placeTickLabel function.
  4956. QSize finalSize;
  4957. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label
  4958. {
  4959. const CachedLabel *cachedLabel = mLabelCache.object(text);
  4960. finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
  4961. } else // label caching disabled or no label with this text cached:
  4962. {
  4963. // TODO: LabelData labelData = getTickLabelData(font, text);
  4964. // TODO: finalSize = labelData.rotatedTotalBounds.size();
  4965. }
  4966. // expand passed tickLabelsSize if current tick label is larger:
  4967. if (finalSize.width() > tickLabelsSize->width())
  4968. tickLabelsSize->setWidth(finalSize.width());
  4969. if (finalSize.height() > tickLabelsSize->height())
  4970. tickLabelsSize->setHeight(finalSize.height());
  4971. }
  4972. */
  4973. QCPLabelPainterPrivate::CachedLabel *QCPLabelPainterPrivate::createCachedLabel(const LabelData &labelData) const
  4974. {
  4975. CachedLabel *result = new CachedLabel;
  4976. // allocate pixmap with the correct size and pixel ratio:
  4977. if (!qFuzzyCompare(1.0, mParentPlot->bufferDevicePixelRatio()))
  4978. {
  4979. result->pixmap = QPixmap(labelData.rotatedTotalBounds.size()*mParentPlot->bufferDevicePixelRatio());
  4980. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  4981. # ifdef QCP_DEVICEPIXELRATIO_FLOAT
  4982. result->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF());
  4983. # else
  4984. result->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio());
  4985. # endif
  4986. #endif
  4987. } else
  4988. result->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
  4989. result->pixmap.fill(Qt::transparent);
  4990. // draw the label into the pixmap
  4991. // 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.
  4992. // We use rotatedTotalBounds.topLeft() because rotatedTotalBounds is in a coordinate system where the label anchor is at (0, 0)
  4993. result->offset = labelData.rotatedTotalBounds.topLeft();
  4994. QCPPainter cachePainter(&result->pixmap);
  4995. drawText(&cachePainter, -result->offset, labelData);
  4996. return result;
  4997. }
  4998. QByteArray QCPLabelPainterPrivate::cacheKey(const QString &text, const QColor &color, double rotation, AnchorSide side) const
  4999. {
  5000. return text.toUtf8()+
  5001. QByteArray::number(color.red()+256*color.green()+65536*color.blue(), 36)+
  5002. QByteArray::number(color.alpha()+256*int(side), 36)+
  5003. QByteArray::number(int(rotation*100)%36000, 36);
  5004. }
  5005. QCPLabelPainterPrivate::AnchorSide QCPLabelPainterPrivate::skewedAnchorSide(const QPointF &tickPos, double sideExpandHorz, double sideExpandVert) const
  5006. {
  5007. QCPVector2D anchorNormal = QCPVector2D(tickPos-mAnchorReference);
  5008. if (mAnchorReferenceType == artTangent)
  5009. anchorNormal = anchorNormal.perpendicular();
  5010. const double radius = anchorNormal.length();
  5011. const double sideHorz = sideExpandHorz*radius;
  5012. const double sideVert = sideExpandVert*radius;
  5013. if (anchorNormal.x() > sideHorz)
  5014. {
  5015. if (anchorNormal.y() > sideVert) return asTopLeft;
  5016. else if (anchorNormal.y() < -sideVert) return asBottomLeft;
  5017. else return asLeft;
  5018. } else if (anchorNormal.x() < -sideHorz)
  5019. {
  5020. if (anchorNormal.y() > sideVert) return asTopRight;
  5021. else if (anchorNormal.y() < -sideVert) return asBottomRight;
  5022. else return asRight;
  5023. } else
  5024. {
  5025. if (anchorNormal.y() > 0) return asTop;
  5026. else return asBottom;
  5027. }
  5028. }
  5029. QCPLabelPainterPrivate::AnchorSide QCPLabelPainterPrivate::rotationCorrectedSide(AnchorSide side, double rotation) const
  5030. {
  5031. AnchorSide result = side;
  5032. const bool rotateClockwise = rotation > 0;
  5033. if (!qFuzzyIsNull(rotation))
  5034. {
  5035. if (!qFuzzyCompare(qAbs(rotation), 90)) // avoid graphical collision with anchor tangent (e.g. axis line) when rotating, so change anchor side appropriately:
  5036. {
  5037. if (side == asTop) result = rotateClockwise ? asLeft : asRight;
  5038. else if (side == asBottom) result = rotateClockwise ? asRight : asLeft;
  5039. else if (side == asTopLeft) result = rotateClockwise ? asLeft : asTop;
  5040. else if (side == asTopRight) result = rotateClockwise ? asTop : asRight;
  5041. else if (side == asBottomLeft) result = rotateClockwise ? asBottom : asLeft;
  5042. else if (side == asBottomRight) result = rotateClockwise ? asRight : asBottom;
  5043. } else // for full rotation by +/-90 degrees, other sides are more appropriate for centering on anchor:
  5044. {
  5045. if (side == asLeft) result = rotateClockwise ? asBottom : asTop;
  5046. else if (side == asRight) result = rotateClockwise ? asTop : asBottom;
  5047. else if (side == asTop) result = rotateClockwise ? asLeft : asRight;
  5048. else if (side == asBottom) result = rotateClockwise ? asRight : asLeft;
  5049. else if (side == asTopLeft) result = rotateClockwise ? asBottomLeft : asTopRight;
  5050. else if (side == asTopRight) result = rotateClockwise ? asTopLeft : asBottomRight;
  5051. else if (side == asBottomLeft) result = rotateClockwise ? asBottomRight : asTopLeft;
  5052. else if (side == asBottomRight) result = rotateClockwise ? asTopRight : asBottomLeft;
  5053. }
  5054. }
  5055. return result;
  5056. }
  5057. void QCPLabelPainterPrivate::analyzeFontMetrics()
  5058. {
  5059. const QFontMetrics fm(mFont);
  5060. mLetterCapHeight = fm.tightBoundingRect(QLatin1String("8")).height(); // this method is slow, that's why we query it only upon font change
  5061. mLetterDescent = fm.descent();
  5062. }
  5063. /* end of 'src/axis/labelpainter.cpp' */
  5064. /* including file 'src/axis/axisticker.cpp' */
  5065. /* modified 2021-03-29T02:30:44, size 18688 */
  5066. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5067. //////////////////// QCPAxisTicker
  5068. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5069. /*! \class QCPAxisTicker
  5070. \brief The base class tick generator used by QCPAxis to create tick positions and tick labels
  5071. Each QCPAxis has an internal QCPAxisTicker (or a subclass) in order to generate tick positions
  5072. and tick labels for the current axis range. The ticker of an axis can be set via \ref
  5073. QCPAxis::setTicker. Since that method takes a <tt>QSharedPointer<QCPAxisTicker></tt>, multiple
  5074. axes can share the same ticker instance.
  5075. This base class generates normal tick coordinates and numeric labels for linear axes. It picks a
  5076. reasonable tick step (the separation between ticks) which results in readable tick labels. The
  5077. number of ticks that should be approximately generated can be set via \ref setTickCount.
  5078. Depending on the current tick step strategy (\ref setTickStepStrategy), the algorithm either
  5079. sacrifices readability to better match the specified tick count (\ref
  5080. QCPAxisTicker::tssMeetTickCount) or relaxes the tick count in favor of better tick steps (\ref
  5081. QCPAxisTicker::tssReadability), which is the default.
  5082. The following more specialized axis ticker subclasses are available, see details in the
  5083. respective class documentation:
  5084. <center>
  5085. <table>
  5086. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerFixed</td><td>\image html axisticker-fixed.png</td></tr>
  5087. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerLog</td><td>\image html axisticker-log.png</td></tr>
  5088. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerPi</td><td>\image html axisticker-pi.png</td></tr>
  5089. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerText</td><td>\image html axisticker-text.png</td></tr>
  5090. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerDateTime</td><td>\image html axisticker-datetime.png</td></tr>
  5091. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerTime</td><td>\image html axisticker-time.png
  5092. \image html axisticker-time2.png</td></tr>
  5093. </table>
  5094. </center>
  5095. \section axisticker-subclassing Creating own axis tickers
  5096. Creating own axis tickers can be achieved very easily by sublassing QCPAxisTicker and
  5097. reimplementing some or all of the available virtual methods.
  5098. In the simplest case you might wish to just generate different tick steps than the other tickers,
  5099. so you only reimplement the method \ref getTickStep. If you additionally want control over the
  5100. string that will be shown as tick label, reimplement \ref getTickLabel.
  5101. If you wish to have complete control, you can generate the tick vectors and tick label vectors
  5102. yourself by reimplementing \ref createTickVector and \ref createLabelVector. The default
  5103. implementations use the previously mentioned virtual methods \ref getTickStep and \ref
  5104. getTickLabel, but your reimplementations don't necessarily need to do so. For example in the case
  5105. of unequal tick steps, the method \ref getTickStep loses its usefulness and can be ignored.
  5106. The sub tick count between major ticks can be controlled with \ref getSubTickCount. Full sub tick
  5107. placement control is obtained by reimplementing \ref createSubTickVector.
  5108. See the documentation of all these virtual methods in QCPAxisTicker for detailed information
  5109. about the parameters and expected return values.
  5110. */
  5111. /*!
  5112. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  5113. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  5114. */
  5115. QCPAxisTicker::QCPAxisTicker() :
  5116. mTickStepStrategy(tssReadability),
  5117. mTickCount(5),
  5118. mTickOrigin(0)
  5119. {
  5120. }
  5121. QCPAxisTicker::~QCPAxisTicker()
  5122. {
  5123. }
  5124. /*!
  5125. Sets which strategy the axis ticker follows when choosing the size of the tick step. For the
  5126. available strategies, see \ref TickStepStrategy.
  5127. */
  5128. void QCPAxisTicker::setTickStepStrategy(QCPAxisTicker::TickStepStrategy strategy)
  5129. {
  5130. mTickStepStrategy = strategy;
  5131. }
  5132. /*!
  5133. Sets how many ticks this ticker shall aim to generate across the axis range. Note that \a count
  5134. is not guaranteed to be matched exactly, as generating readable tick intervals may conflict with
  5135. the requested number of ticks.
  5136. Whether the readability has priority over meeting the requested \a count can be specified with
  5137. \ref setTickStepStrategy.
  5138. */
  5139. void QCPAxisTicker::setTickCount(int count)
  5140. {
  5141. if (count > 0)
  5142. mTickCount = count;
  5143. else
  5144. qDebug() << Q_FUNC_INFO << "tick count must be greater than zero:" << count;
  5145. }
  5146. /*!
  5147. Sets the mathematical coordinate (or "offset") of the zeroth tick. This tick coordinate is just a
  5148. concept and doesn't need to be inside the currently visible axis range.
  5149. By default \a origin is zero, which for example yields ticks {-5, 0, 5, 10, 15,...} when the tick
  5150. step is five. If \a origin is now set to 1 instead, the correspondingly generated ticks would be
  5151. {-4, 1, 6, 11, 16,...}.
  5152. */
  5153. void QCPAxisTicker::setTickOrigin(double origin)
  5154. {
  5155. mTickOrigin = origin;
  5156. }
  5157. /*!
  5158. This is the method called by QCPAxis in order to actually generate tick coordinates (\a ticks),
  5159. tick label strings (\a tickLabels) and sub tick coordinates (\a subTicks).
  5160. The ticks are generated for the specified \a range. The generated labels typically follow the
  5161. specified \a locale, \a formatChar and number \a precision, however this might be different (or
  5162. even irrelevant) for certain QCPAxisTicker subclasses.
  5163. The output parameter \a ticks is filled with the generated tick positions in axis coordinates.
  5164. The output parameters \a subTicks and \a tickLabels are optional (set them to \c nullptr if not
  5165. needed) and are respectively filled with sub tick coordinates, and tick label strings belonging
  5166. to \a ticks by index.
  5167. */
  5168. void QCPAxisTicker::generate(const QCPRange &range, const QLocale &locale, QChar formatChar, int precision, QVector<double> &ticks, QVector<double> *subTicks, QVector<QString> *tickLabels)
  5169. {
  5170. // generate (major) ticks:
  5171. double tickStep = getTickStep(range);
  5172. ticks = createTickVector(tickStep, range);
  5173. trimTicks(range, ticks, true); // trim ticks to visible range plus one outer tick on each side (incase a subclass createTickVector creates more)
  5174. // generate sub ticks between major ticks:
  5175. if (subTicks)
  5176. {
  5177. if (!ticks.isEmpty())
  5178. {
  5179. *subTicks = createSubTickVector(getSubTickCount(tickStep), ticks);
  5180. trimTicks(range, *subTicks, false);
  5181. } else
  5182. *subTicks = QVector<double>();
  5183. }
  5184. // finally trim also outliers (no further clipping happens in axis drawing):
  5185. trimTicks(range, ticks, false);
  5186. // generate labels for visible ticks if requested:
  5187. if (tickLabels)
  5188. *tickLabels = createLabelVector(ticks, locale, formatChar, precision);
  5189. }
  5190. /*! \internal
  5191. Takes the entire currently visible axis range and returns a sensible tick step in
  5192. order to provide readable tick labels as well as a reasonable number of tick counts (see \ref
  5193. setTickCount, \ref setTickStepStrategy).
  5194. If a QCPAxisTicker subclass only wants a different tick step behaviour than the default
  5195. implementation, it should reimplement this method. See \ref cleanMantissa for a possible helper
  5196. function.
  5197. */
  5198. double QCPAxisTicker::getTickStep(const QCPRange &range)
  5199. {
  5200. double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  5201. return cleanMantissa(exactStep);
  5202. }
  5203. /*! \internal
  5204. Takes the \a tickStep, i.e. the distance between two consecutive ticks, and returns
  5205. an appropriate number of sub ticks for that specific tick step.
  5206. Note that a returned sub tick count of e.g. 4 will split each tick interval into 5 sections.
  5207. */
  5208. int QCPAxisTicker::getSubTickCount(double tickStep)
  5209. {
  5210. int result = 1; // default to 1, if no proper value can be found
  5211. // separate integer and fractional part of mantissa:
  5212. double epsilon = 0.01;
  5213. double intPartf;
  5214. int intPart;
  5215. double fracPart = modf(getMantissa(tickStep), &intPartf);
  5216. intPart = int(intPartf);
  5217. // handle cases with (almost) integer mantissa:
  5218. if (fracPart < epsilon || 1.0-fracPart < epsilon)
  5219. {
  5220. if (1.0-fracPart < epsilon)
  5221. ++intPart;
  5222. switch (intPart)
  5223. {
  5224. case 1: result = 4; break; // 1.0 -> 0.2 substep
  5225. case 2: result = 3; break; // 2.0 -> 0.5 substep
  5226. case 3: result = 2; break; // 3.0 -> 1.0 substep
  5227. case 4: result = 3; break; // 4.0 -> 1.0 substep
  5228. case 5: result = 4; break; // 5.0 -> 1.0 substep
  5229. case 6: result = 2; break; // 6.0 -> 2.0 substep
  5230. case 7: result = 6; break; // 7.0 -> 1.0 substep
  5231. case 8: result = 3; break; // 8.0 -> 2.0 substep
  5232. case 9: result = 2; break; // 9.0 -> 3.0 substep
  5233. }
  5234. } else
  5235. {
  5236. // handle cases with significantly fractional mantissa:
  5237. if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa
  5238. {
  5239. switch (intPart)
  5240. {
  5241. case 1: result = 2; break; // 1.5 -> 0.5 substep
  5242. case 2: result = 4; break; // 2.5 -> 0.5 substep
  5243. case 3: result = 4; break; // 3.5 -> 0.7 substep
  5244. case 4: result = 2; break; // 4.5 -> 1.5 substep
  5245. case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with default getTickStep from here on)
  5246. case 6: result = 4; break; // 6.5 -> 1.3 substep
  5247. case 7: result = 2; break; // 7.5 -> 2.5 substep
  5248. case 8: result = 4; break; // 8.5 -> 1.7 substep
  5249. case 9: result = 4; break; // 9.5 -> 1.9 substep
  5250. }
  5251. }
  5252. // if mantissa fraction isn't 0.0 or 0.5, don't bother finding good sub tick marks, leave default
  5253. }
  5254. return result;
  5255. }
  5256. /*! \internal
  5257. This method returns the tick label string as it should be printed under the \a tick coordinate.
  5258. If a textual number is returned, it should respect the provided \a locale, \a formatChar and \a
  5259. precision.
  5260. If the returned value contains exponentials of the form "2e5" and beautifully typeset powers is
  5261. enabled in the QCPAxis number format (\ref QCPAxis::setNumberFormat), the exponential part will
  5262. be formatted accordingly using multiplication symbol and superscript during rendering of the
  5263. label automatically.
  5264. */
  5265. QString QCPAxisTicker::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  5266. {
  5267. return locale.toString(tick, formatChar.toLatin1(), precision);
  5268. }
  5269. /*! \internal
  5270. Returns a vector containing all coordinates of sub ticks that should be drawn. It generates \a
  5271. subTickCount sub ticks between each tick pair given in \a ticks.
  5272. If a QCPAxisTicker subclass needs maximal control over the generated sub ticks, it should
  5273. reimplement this method. Depending on the purpose of the subclass it doesn't necessarily need to
  5274. base its result on \a subTickCount or \a ticks.
  5275. */
  5276. QVector<double> QCPAxisTicker::createSubTickVector(int subTickCount, const QVector<double> &ticks)
  5277. {
  5278. QVector<double> result;
  5279. if (subTickCount <= 0 || ticks.size() < 2)
  5280. return result;
  5281. result.reserve((ticks.size()-1)*subTickCount);
  5282. for (int i=1; i<ticks.size(); ++i)
  5283. {
  5284. double subTickStep = (ticks.at(i)-ticks.at(i-1))/double(subTickCount+1);
  5285. for (int k=1; k<=subTickCount; ++k)
  5286. result.append(ticks.at(i-1) + k*subTickStep);
  5287. }
  5288. return result;
  5289. }
  5290. /*! \internal
  5291. Returns a vector containing all coordinates of ticks that should be drawn. The default
  5292. implementation generates ticks with a spacing of \a tickStep (mathematically starting at the tick
  5293. step origin, see \ref setTickOrigin) distributed over the passed \a range.
  5294. In order for the axis ticker to generate proper sub ticks, it is necessary that the first and
  5295. last tick coordinates returned by this method are just below/above the provided \a range.
  5296. Otherwise the outer intervals won't contain any sub ticks.
  5297. If a QCPAxisTicker subclass needs maximal control over the generated ticks, it should reimplement
  5298. this method. Depending on the purpose of the subclass it doesn't necessarily need to base its
  5299. result on \a tickStep, e.g. when the ticks are spaced unequally like in the case of
  5300. QCPAxisTickerLog.
  5301. */
  5302. QVector<double> QCPAxisTicker::createTickVector(double tickStep, const QCPRange &range)
  5303. {
  5304. QVector<double> result;
  5305. // Generate tick positions according to tickStep:
  5306. qint64 firstStep = qint64(floor((range.lower-mTickOrigin)/tickStep)); // do not use qFloor here, or we'll lose 64 bit precision
  5307. qint64 lastStep = qint64(ceil((range.upper-mTickOrigin)/tickStep)); // do not use qCeil here, or we'll lose 64 bit precision
  5308. int tickcount = int(lastStep-firstStep+1);
  5309. if (tickcount < 0) tickcount = 0;
  5310. result.resize(tickcount);
  5311. for (int i=0; i<tickcount; ++i)
  5312. result[i] = mTickOrigin + (firstStep+i)*tickStep;
  5313. return result;
  5314. }
  5315. /*! \internal
  5316. Returns a vector containing all tick label strings corresponding to the tick coordinates provided
  5317. in \a ticks. The default implementation calls \ref getTickLabel to generate the respective
  5318. strings.
  5319. It is possible but uncommon for QCPAxisTicker subclasses to reimplement this method, as
  5320. reimplementing \ref getTickLabel often achieves the intended result easier.
  5321. */
  5322. QVector<QString> QCPAxisTicker::createLabelVector(const QVector<double> &ticks, const QLocale &locale, QChar formatChar, int precision)
  5323. {
  5324. QVector<QString> result;
  5325. result.reserve(ticks.size());
  5326. foreach (double tickCoord, ticks)
  5327. result.append(getTickLabel(tickCoord, locale, formatChar, precision));
  5328. return result;
  5329. }
  5330. /*! \internal
  5331. Removes tick coordinates from \a ticks which lie outside the specified \a range. If \a
  5332. keepOneOutlier is true, it preserves one tick just outside the range on both sides, if present.
  5333. The passed \a ticks must be sorted in ascending order.
  5334. */
  5335. void QCPAxisTicker::trimTicks(const QCPRange &range, QVector<double> &ticks, bool keepOneOutlier) const
  5336. {
  5337. bool lowFound = false;
  5338. bool highFound = false;
  5339. int lowIndex = 0;
  5340. int highIndex = -1;
  5341. for (int i=0; i < ticks.size(); ++i)
  5342. {
  5343. if (ticks.at(i) >= range.lower)
  5344. {
  5345. lowFound = true;
  5346. lowIndex = i;
  5347. break;
  5348. }
  5349. }
  5350. for (int i=ticks.size()-1; i >= 0; --i)
  5351. {
  5352. if (ticks.at(i) <= range.upper)
  5353. {
  5354. highFound = true;
  5355. highIndex = i;
  5356. break;
  5357. }
  5358. }
  5359. if (highFound && lowFound)
  5360. {
  5361. int trimFront = qMax(0, lowIndex-(keepOneOutlier ? 1 : 0));
  5362. int trimBack = qMax(0, ticks.size()-(keepOneOutlier ? 2 : 1)-highIndex);
  5363. if (trimFront > 0 || trimBack > 0)
  5364. ticks = ticks.mid(trimFront, ticks.size()-trimFront-trimBack);
  5365. } else // all ticks are either all below or all above the range
  5366. ticks.clear();
  5367. }
  5368. /*! \internal
  5369. Returns the coordinate contained in \a candidates which is closest to the provided \a target.
  5370. This method assumes \a candidates is not empty and sorted in ascending order.
  5371. */
  5372. double QCPAxisTicker::pickClosest(double target, const QVector<double> &candidates) const
  5373. {
  5374. if (candidates.size() == 1)
  5375. return candidates.first();
  5376. QVector<double>::const_iterator it = std::lower_bound(candidates.constBegin(), candidates.constEnd(), target);
  5377. if (it == candidates.constEnd())
  5378. return *(it-1);
  5379. else if (it == candidates.constBegin())
  5380. return *it;
  5381. else
  5382. return target-*(it-1) < *it-target ? *(it-1) : *it;
  5383. }
  5384. /*! \internal
  5385. Returns the decimal mantissa of \a input. Optionally, if \a magnitude is not set to zero, it also
  5386. returns the magnitude of \a input as a power of 10.
  5387. For example, an input of 142.6 will return a mantissa of 1.426 and a magnitude of 100.
  5388. */
  5389. double QCPAxisTicker::getMantissa(double input, double *magnitude) const
  5390. {
  5391. const double mag = qPow(10.0, qFloor(qLn(input)/qLn(10.0)));
  5392. if (magnitude) *magnitude = mag;
  5393. return input/mag;
  5394. }
  5395. /*! \internal
  5396. Returns a number that is close to \a input but has a clean, easier human readable mantissa. How
  5397. strongly the mantissa is altered, and thus how strong the result deviates from the original \a
  5398. input, depends on the current tick step strategy (see \ref setTickStepStrategy).
  5399. */
  5400. double QCPAxisTicker::cleanMantissa(double input) const
  5401. {
  5402. double magnitude;
  5403. const double mantissa = getMantissa(input, &magnitude);
  5404. switch (mTickStepStrategy)
  5405. {
  5406. case tssReadability:
  5407. {
  5408. return pickClosest(mantissa, QVector<double>() << 1.0 << 2.0 << 2.5 << 5.0 << 10.0)*magnitude;
  5409. }
  5410. case tssMeetTickCount:
  5411. {
  5412. // 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
  5413. if (mantissa <= 5.0)
  5414. return int(mantissa*2)/2.0*magnitude; // round digit after decimal point to 0.5
  5415. else
  5416. return int(mantissa/2.0)*2.0*magnitude; // round to first digit in multiples of 2
  5417. }
  5418. }
  5419. return input;
  5420. }
  5421. /* end of 'src/axis/axisticker.cpp' */
  5422. /* including file 'src/axis/axistickerdatetime.cpp' */
  5423. /* modified 2021-03-29T02:30:44, size 18829 */
  5424. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5425. //////////////////// QCPAxisTickerDateTime
  5426. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5427. /*! \class QCPAxisTickerDateTime
  5428. \brief Specialized axis ticker for calendar dates and times as axis ticks
  5429. \image html axisticker-datetime.png
  5430. This QCPAxisTicker subclass generates ticks that correspond to real calendar dates and times. The
  5431. plot axis coordinate is interpreted as Unix Time, so seconds since Epoch (January 1, 1970, 00:00
  5432. UTC). This is also used for example by QDateTime in the <tt>toTime_t()/setTime_t()</tt> methods
  5433. with a precision of one second. Since Qt 4.7, millisecond accuracy can be obtained from QDateTime
  5434. by using <tt>QDateTime::fromMSecsSinceEpoch()/1000.0</tt>. The static methods \ref dateTimeToKey
  5435. and \ref keyToDateTime conveniently perform this conversion achieving a precision of one
  5436. millisecond on all Qt versions.
  5437. The format of the date/time display in the tick labels is controlled with \ref setDateTimeFormat.
  5438. If a different time spec or time zone shall be used for the tick label appearance, see \ref
  5439. setDateTimeSpec or \ref setTimeZone, respectively.
  5440. This ticker produces unequal tick spacing in order to provide intuitive date and time-of-day
  5441. ticks. For example, if the axis range spans a few years such that there is one tick per year,
  5442. ticks will be positioned on 1. January of every year. This is intuitive but, due to leap years,
  5443. will result in slightly unequal tick intervals (visually unnoticeable). The same can be seen in
  5444. the image above: even though the number of days varies month by month, this ticker generates
  5445. ticks on the same day of each month.
  5446. If you would like to change the date/time that is used as a (mathematical) starting date for the
  5447. ticks, use the \ref setTickOrigin(const QDateTime &origin) method overload, which takes a
  5448. QDateTime. If you pass 15. July, 9:45 to this method, the yearly ticks will end up on 15. July at
  5449. 9:45 of every year.
  5450. The ticker can be created and assigned to an axis like this:
  5451. \snippet documentation/doc-image-generator/mainwindow.cpp axistickerdatetime-creation
  5452. \note If you rather wish to display relative times in terms of days, hours, minutes, seconds and
  5453. milliseconds, and are not interested in the intricacies of real calendar dates with months and
  5454. (leap) years, have a look at QCPAxisTickerTime instead.
  5455. */
  5456. /*!
  5457. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  5458. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  5459. */
  5460. QCPAxisTickerDateTime::QCPAxisTickerDateTime() :
  5461. mDateTimeFormat(QLatin1String("hh:mm:ss\ndd.MM.yy")),
  5462. mDateTimeSpec(Qt::LocalTime),
  5463. mDateStrategy(dsNone)
  5464. {
  5465. setTickCount(4);
  5466. }
  5467. /*!
  5468. Sets the format in which dates and times are displayed as tick labels. For details about the \a
  5469. format string, see the documentation of QDateTime::toString().
  5470. Typical expressions are
  5471. <table>
  5472. <tr><td>\c d</td><td>The day as a number without a leading zero (1 to 31)</td></tr>
  5473. <tr><td>\c dd</td><td>The day as a number with a leading zero (01 to 31)</td></tr>
  5474. <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>
  5475. <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>
  5476. <tr><td>\c M</td><td>The month as a number without a leading zero (1 to 12)</td></tr>
  5477. <tr><td>\c MM</td><td>The month as a number with a leading zero (01 to 12)</td></tr>
  5478. <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>
  5479. <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>
  5480. <tr><td>\c yy</td><td>The year as a two digit number (00 to 99)</td></tr>
  5481. <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>
  5482. <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>
  5483. <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>
  5484. <tr><td>\c H</td><td>The hour without a leading zero (0 to 23, even with AM/PM display)</td></tr>
  5485. <tr><td>\c HH</td><td>The hour with a leading zero (00 to 23, even with AM/PM display)</td></tr>
  5486. <tr><td>\c m</td><td>The minute without a leading zero (0 to 59)</td></tr>
  5487. <tr><td>\c mm</td><td>The minute with a leading zero (00 to 59)</td></tr>
  5488. <tr><td>\c s</td><td>The whole second, without any leading zero (0 to 59)</td></tr>
  5489. <tr><td>\c ss</td><td>The whole second, with a leading zero where applicable (00 to 59)</td></tr>
  5490. <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>
  5491. <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>
  5492. <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>
  5493. <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>
  5494. <tr><td>\c t</td><td>The timezone (for example "CEST")</td></tr>
  5495. </table>
  5496. Newlines can be inserted with \c "\n", literal strings (even when containing above expressions)
  5497. by encapsulating them using single-quotes. A literal single quote can be generated by using two
  5498. consecutive single quotes in the format.
  5499. \see setDateTimeSpec, setTimeZone
  5500. */
  5501. void QCPAxisTickerDateTime::setDateTimeFormat(const QString &format)
  5502. {
  5503. mDateTimeFormat = format;
  5504. }
  5505. /*!
  5506. Sets the time spec that is used for creating the tick labels from corresponding dates/times.
  5507. The default value of QDateTime objects (and also QCPAxisTickerDateTime) is
  5508. <tt>Qt::LocalTime</tt>. However, if the displayed tick labels shall be given in UTC, set \a spec
  5509. to <tt>Qt::UTC</tt>.
  5510. Tick labels corresponding to other time zones can be achieved with \ref setTimeZone (which sets
  5511. \a spec to \c Qt::TimeZone internally). Note that if \a spec is afterwards set to not be \c
  5512. Qt::TimeZone again, the \ref setTimeZone setting will be ignored accordingly.
  5513. \see setDateTimeFormat, setTimeZone
  5514. */
  5515. void QCPAxisTickerDateTime::setDateTimeSpec(Qt::TimeSpec spec)
  5516. {
  5517. mDateTimeSpec = spec;
  5518. }
  5519. # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)
  5520. /*!
  5521. Sets the time zone that is used for creating the tick labels from corresponding dates/times. The
  5522. time spec (\ref setDateTimeSpec) is set to \c Qt::TimeZone.
  5523. \see setDateTimeFormat, setTimeZone
  5524. */
  5525. void QCPAxisTickerDateTime::setTimeZone(const QTimeZone &zone)
  5526. {
  5527. mTimeZone = zone;
  5528. mDateTimeSpec = Qt::TimeZone;
  5529. }
  5530. #endif
  5531. /*!
  5532. Sets the tick origin (see \ref QCPAxisTicker::setTickOrigin) in seconds since Epoch (1. Jan 1970,
  5533. 00:00 UTC). For the date time ticker it might be more intuitive to use the overload which
  5534. directly takes a QDateTime, see \ref setTickOrigin(const QDateTime &origin).
  5535. This is useful to define the month/day/time recurring at greater tick interval steps. For
  5536. example, If you pass 15. July, 9:45 to this method and the tick interval happens to be one tick
  5537. per year, the ticks will end up on 15. July at 9:45 of every year.
  5538. */
  5539. void QCPAxisTickerDateTime::setTickOrigin(double origin)
  5540. {
  5541. QCPAxisTicker::setTickOrigin(origin);
  5542. }
  5543. /*!
  5544. Sets the tick origin (see \ref QCPAxisTicker::setTickOrigin) as a QDateTime \a origin.
  5545. This is useful to define the month/day/time recurring at greater tick interval steps. For
  5546. example, If you pass 15. July, 9:45 to this method and the tick interval happens to be one tick
  5547. per year, the ticks will end up on 15. July at 9:45 of every year.
  5548. */
  5549. void QCPAxisTickerDateTime::setTickOrigin(const QDateTime &origin)
  5550. {
  5551. setTickOrigin(dateTimeToKey(origin));
  5552. }
  5553. /*! \internal
  5554. Returns a sensible tick step with intervals appropriate for a date-time-display, such as weekly,
  5555. monthly, bi-monthly, etc.
  5556. Note that this tick step isn't used exactly when generating the tick vector in \ref
  5557. createTickVector, but only as a guiding value requiring some correction for each individual tick
  5558. interval. Otherwise this would lead to unintuitive date displays, e.g. jumping between first day
  5559. in the month to the last day in the previous month from tick to tick, due to the non-uniform
  5560. length of months. The same problem arises with leap years.
  5561. \seebaseclassmethod
  5562. */
  5563. double QCPAxisTickerDateTime::getTickStep(const QCPRange &range)
  5564. {
  5565. double result = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  5566. mDateStrategy = dsNone; // leaving it at dsNone means tick coordinates will not be tuned in any special way in createTickVector
  5567. if (result < 1) // ideal tick step is below 1 second -> use normal clean mantissa algorithm in units of seconds
  5568. {
  5569. result = cleanMantissa(result);
  5570. } else if (result < 86400*30.4375*12) // below a year
  5571. {
  5572. result = pickClosest(result, QVector<double>()
  5573. << 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
  5574. << 3600*2 << 3600*3 << 3600*6 << 3600*12 << 3600*24 // hour to day range
  5575. << 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)
  5576. if (result > 86400*30.4375-1) // month tick intervals or larger
  5577. mDateStrategy = dsUniformDayInMonth;
  5578. else if (result > 3600*24-1) // day tick intervals or larger
  5579. mDateStrategy = dsUniformTimeInDay;
  5580. } else // more than a year, go back to normal clean mantissa algorithm but in units of years
  5581. {
  5582. const double secondsPerYear = 86400*30.4375*12; // average including leap years
  5583. result = cleanMantissa(result/secondsPerYear)*secondsPerYear;
  5584. mDateStrategy = dsUniformDayInMonth;
  5585. }
  5586. return result;
  5587. }
  5588. /*! \internal
  5589. Returns a sensible sub tick count with intervals appropriate for a date-time-display, such as weekly,
  5590. monthly, bi-monthly, etc.
  5591. \seebaseclassmethod
  5592. */
  5593. int QCPAxisTickerDateTime::getSubTickCount(double tickStep)
  5594. {
  5595. int result = QCPAxisTicker::getSubTickCount(tickStep);
  5596. switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day/week/month range (as specified in getTickStep)
  5597. {
  5598. case 5*60: result = 4; break;
  5599. case 10*60: result = 1; break;
  5600. case 15*60: result = 2; break;
  5601. case 30*60: result = 1; break;
  5602. case 60*60: result = 3; break;
  5603. case 3600*2: result = 3; break;
  5604. case 3600*3: result = 2; break;
  5605. case 3600*6: result = 1; break;
  5606. case 3600*12: result = 3; break;
  5607. case 3600*24: result = 3; break;
  5608. case 86400*2: result = 1; break;
  5609. case 86400*5: result = 4; break;
  5610. case 86400*7: result = 6; break;
  5611. case 86400*14: result = 1; break;
  5612. case int(86400*30.4375+0.5): result = 3; break;
  5613. case int(86400*30.4375*2+0.5): result = 1; break;
  5614. case int(86400*30.4375*3+0.5): result = 2; break;
  5615. case int(86400*30.4375*6+0.5): result = 5; break;
  5616. case int(86400*30.4375*12+0.5): result = 3; break;
  5617. }
  5618. return result;
  5619. }
  5620. /*! \internal
  5621. Generates a date/time tick label for tick coordinate \a tick, based on the currently set format
  5622. (\ref setDateTimeFormat), time spec (\ref setDateTimeSpec), and possibly time zone (\ref
  5623. setTimeZone).
  5624. \seebaseclassmethod
  5625. */
  5626. QString QCPAxisTickerDateTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  5627. {
  5628. Q_UNUSED(precision)
  5629. Q_UNUSED(formatChar)
  5630. # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)
  5631. if (mDateTimeSpec == Qt::TimeZone)
  5632. return locale.toString(keyToDateTime(tick).toTimeZone(mTimeZone), mDateTimeFormat);
  5633. else
  5634. return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
  5635. # else
  5636. return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
  5637. # endif
  5638. }
  5639. /*! \internal
  5640. Uses the passed \a tickStep as a guiding value and applies corrections in order to obtain
  5641. non-uniform tick intervals but intuitive tick labels, e.g. falling on the same day of each month.
  5642. \seebaseclassmethod
  5643. */
  5644. QVector<double> QCPAxisTickerDateTime::createTickVector(double tickStep, const QCPRange &range)
  5645. {
  5646. QVector<double> result = QCPAxisTicker::createTickVector(tickStep, range);
  5647. if (!result.isEmpty())
  5648. {
  5649. if (mDateStrategy == dsUniformTimeInDay)
  5650. {
  5651. QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // the time of this datetime will be set for all other ticks, if possible
  5652. QDateTime tickDateTime;
  5653. for (int i=0; i<result.size(); ++i)
  5654. {
  5655. tickDateTime = keyToDateTime(result.at(i));
  5656. tickDateTime.setTime(uniformDateTime.time());
  5657. result[i] = dateTimeToKey(tickDateTime);
  5658. }
  5659. } else if (mDateStrategy == dsUniformDayInMonth)
  5660. {
  5661. QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // this day (in month) and time will be set for all other ticks, if possible
  5662. QDateTime tickDateTime;
  5663. for (int i=0; i<result.size(); ++i)
  5664. {
  5665. tickDateTime = keyToDateTime(result.at(i));
  5666. tickDateTime.setTime(uniformDateTime.time());
  5667. int thisUniformDay = uniformDateTime.date().day() <= tickDateTime.date().daysInMonth() ? uniformDateTime.date().day() : tickDateTime.date().daysInMonth(); // don't exceed month (e.g. try to set day 31 in February)
  5668. if (thisUniformDay-tickDateTime.date().day() < -15) // with leap years involved, date month may jump backwards or forwards, and needs to be corrected before setting day
  5669. tickDateTime = tickDateTime.addMonths(1);
  5670. else if (thisUniformDay-tickDateTime.date().day() > 15) // with leap years involved, date month may jump backwards or forwards, and needs to be corrected before setting day
  5671. tickDateTime = tickDateTime.addMonths(-1);
  5672. tickDateTime.setDate(QDate(tickDateTime.date().year(), tickDateTime.date().month(), thisUniformDay));
  5673. result[i] = dateTimeToKey(tickDateTime);
  5674. }
  5675. }
  5676. }
  5677. return result;
  5678. }
  5679. /*!
  5680. A convenience method which turns \a key (in seconds since Epoch 1. Jan 1970, 00:00 UTC) into a
  5681. QDateTime object. This can be used to turn axis coordinates to actual QDateTimes.
  5682. The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it
  5683. works around the lack of a QDateTime::fromMSecsSinceEpoch in Qt 4.6)
  5684. \see dateTimeToKey
  5685. */
  5686. QDateTime QCPAxisTickerDateTime::keyToDateTime(double key)
  5687. {
  5688. # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
  5689. return QDateTime::fromTime_t(key).addMSecs((key-(qint64)key)*1000);
  5690. # else
  5691. return QDateTime::fromMSecsSinceEpoch(qint64(key*1000.0));
  5692. # endif
  5693. }
  5694. /*! \overload
  5695. A convenience method which turns a QDateTime object into a double value that corresponds to
  5696. seconds since Epoch (1. Jan 1970, 00:00 UTC). This is the format used as axis coordinates by
  5697. QCPAxisTickerDateTime.
  5698. The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it
  5699. works around the lack of a QDateTime::toMSecsSinceEpoch in Qt 4.6)
  5700. \see keyToDateTime
  5701. */
  5702. double QCPAxisTickerDateTime::dateTimeToKey(const QDateTime &dateTime)
  5703. {
  5704. # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
  5705. return dateTime.toTime_t()+dateTime.time().msec()/1000.0;
  5706. # else
  5707. return dateTime.toMSecsSinceEpoch()/1000.0;
  5708. # endif
  5709. }
  5710. /*! \overload
  5711. A convenience method which turns a QDate object into a double value that corresponds to seconds
  5712. since Epoch (1. Jan 1970, 00:00 UTC). This is the format used
  5713. as axis coordinates by QCPAxisTickerDateTime.
  5714. The returned value will be the start of the passed day of \a date, interpreted in the given \a
  5715. timeSpec.
  5716. \see keyToDateTime
  5717. */
  5718. double QCPAxisTickerDateTime::dateTimeToKey(const QDate &date, Qt::TimeSpec timeSpec)
  5719. {
  5720. # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
  5721. return QDateTime(date, QTime(0, 0), timeSpec).toTime_t();
  5722. # elif QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  5723. return QDateTime(date, QTime(0, 0), timeSpec).toMSecsSinceEpoch()/1000.0;
  5724. # else
  5725. return date.startOfDay(timeSpec).toMSecsSinceEpoch()/1000.0;
  5726. # endif
  5727. }
  5728. /* end of 'src/axis/axistickerdatetime.cpp' */
  5729. /* including file 'src/axis/axistickertime.cpp' */
  5730. /* modified 2021-03-29T02:30:44, size 11745 */
  5731. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5732. //////////////////// QCPAxisTickerTime
  5733. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5734. /*! \class QCPAxisTickerTime
  5735. \brief Specialized axis ticker for time spans in units of milliseconds to days
  5736. \image html axisticker-time.png
  5737. This QCPAxisTicker subclass generates ticks that corresponds to time intervals.
  5738. The format of the time display in the tick labels is controlled with \ref setTimeFormat and \ref
  5739. setFieldWidth. The time coordinate is in the unit of seconds with respect to the time coordinate
  5740. zero. Unlike with QCPAxisTickerDateTime, the ticks don't correspond to a specific calendar date
  5741. and time.
  5742. The time can be displayed in milliseconds, seconds, minutes, hours and days. Depending on the
  5743. largest available unit in the format specified with \ref setTimeFormat, any time spans above will
  5744. be carried in that largest unit. So for example if the format string is "%m:%s" and a tick at
  5745. coordinate value 7815 (being 2 hours, 10 minutes and 15 seconds) is created, the resulting tick
  5746. label will show "130:15" (130 minutes, 15 seconds). If the format string is "%h:%m:%s", the hour
  5747. unit will be used and the label will thus be "02:10:15". Negative times with respect to the axis
  5748. zero will carry a leading minus sign.
  5749. The ticker can be created and assigned to an axis like this:
  5750. \snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation
  5751. Here is an example of a time axis providing time information in days, hours and minutes. Due to
  5752. the axis range spanning a few days and the wanted tick count (\ref setTickCount), the ticker
  5753. decided to use tick steps of 12 hours:
  5754. \image html axisticker-time2.png
  5755. The format string for this example is
  5756. \snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation-2
  5757. \note If you rather wish to display calendar dates and times, have a look at QCPAxisTickerDateTime
  5758. instead.
  5759. */
  5760. /*!
  5761. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  5762. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  5763. */
  5764. QCPAxisTickerTime::QCPAxisTickerTime() :
  5765. mTimeFormat(QLatin1String("%h:%m:%s")),
  5766. mSmallestUnit(tuSeconds),
  5767. mBiggestUnit(tuHours)
  5768. {
  5769. setTickCount(4);
  5770. mFieldWidth[tuMilliseconds] = 3;
  5771. mFieldWidth[tuSeconds] = 2;
  5772. mFieldWidth[tuMinutes] = 2;
  5773. mFieldWidth[tuHours] = 2;
  5774. mFieldWidth[tuDays] = 1;
  5775. mFormatPattern[tuMilliseconds] = QLatin1String("%z");
  5776. mFormatPattern[tuSeconds] = QLatin1String("%s");
  5777. mFormatPattern[tuMinutes] = QLatin1String("%m");
  5778. mFormatPattern[tuHours] = QLatin1String("%h");
  5779. mFormatPattern[tuDays] = QLatin1String("%d");
  5780. }
  5781. /*!
  5782. Sets the format that will be used to display time in the tick labels.
  5783. The available patterns are:
  5784. - %%z for milliseconds
  5785. - %%s for seconds
  5786. - %%m for minutes
  5787. - %%h for hours
  5788. - %%d for days
  5789. The field width (zero padding) can be controlled for each unit with \ref setFieldWidth.
  5790. The largest unit that appears in \a format will carry all the remaining time of a certain tick
  5791. coordinate, even if it overflows the natural limit of the unit. For example, if %%m is the
  5792. largest unit it might become larger than 59 in order to consume larger time values. If on the
  5793. other hand %%h is available, the minutes will wrap around to zero after 59 and the time will
  5794. carry to the hour digit.
  5795. */
  5796. void QCPAxisTickerTime::setTimeFormat(const QString &format)
  5797. {
  5798. mTimeFormat = format;
  5799. // determine smallest and biggest unit in format, to optimize unit replacement and allow biggest
  5800. // unit to consume remaining time of a tick value and grow beyond its modulo (e.g. min > 59)
  5801. mSmallestUnit = tuMilliseconds;
  5802. mBiggestUnit = tuMilliseconds;
  5803. bool hasSmallest = false;
  5804. for (int i = tuMilliseconds; i <= tuDays; ++i)
  5805. {
  5806. TimeUnit unit = static_cast<TimeUnit>(i);
  5807. if (mTimeFormat.contains(mFormatPattern.value(unit)))
  5808. {
  5809. if (!hasSmallest)
  5810. {
  5811. mSmallestUnit = unit;
  5812. hasSmallest = true;
  5813. }
  5814. mBiggestUnit = unit;
  5815. }
  5816. }
  5817. }
  5818. /*!
  5819. Sets the field widh of the specified \a unit to be \a width digits, when displayed in the tick
  5820. label. If the number for the specific unit is shorter than \a width, it will be padded with an
  5821. according number of zeros to the left in order to reach the field width.
  5822. \see setTimeFormat
  5823. */
  5824. void QCPAxisTickerTime::setFieldWidth(QCPAxisTickerTime::TimeUnit unit, int width)
  5825. {
  5826. mFieldWidth[unit] = qMax(width, 1);
  5827. }
  5828. /*! \internal
  5829. Returns the tick step appropriate for time displays, depending on the provided \a range and the
  5830. smallest available time unit in the current format (\ref setTimeFormat). For example if the unit
  5831. of seconds isn't available in the format, this method will not generate steps (like 2.5 minutes)
  5832. that require sub-minute precision to be displayed correctly.
  5833. \seebaseclassmethod
  5834. */
  5835. double QCPAxisTickerTime::getTickStep(const QCPRange &range)
  5836. {
  5837. double result = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  5838. if (result < 1) // ideal tick step is below 1 second -> use normal clean mantissa algorithm in units of seconds
  5839. {
  5840. if (mSmallestUnit == tuMilliseconds)
  5841. result = qMax(cleanMantissa(result), 0.001); // smallest tick step is 1 millisecond
  5842. else // have no milliseconds available in format, so stick with 1 second tickstep
  5843. result = 1.0;
  5844. } else if (result < 3600*24) // below a day
  5845. {
  5846. // the filling of availableSteps seems a bit contorted but it fills in a sorted fashion and thus saves a post-fill sorting run
  5847. QVector<double> availableSteps;
  5848. // seconds range:
  5849. if (mSmallestUnit <= tuSeconds)
  5850. availableSteps << 1;
  5851. if (mSmallestUnit == tuMilliseconds)
  5852. availableSteps << 2.5; // only allow half second steps if milliseconds are there to display it
  5853. else if (mSmallestUnit == tuSeconds)
  5854. availableSteps << 2;
  5855. if (mSmallestUnit <= tuSeconds)
  5856. availableSteps << 5 << 10 << 15 << 30;
  5857. // minutes range:
  5858. if (mSmallestUnit <= tuMinutes)
  5859. availableSteps << 1*60;
  5860. if (mSmallestUnit <= tuSeconds)
  5861. availableSteps << 2.5*60; // only allow half minute steps if seconds are there to display it
  5862. else if (mSmallestUnit == tuMinutes)
  5863. availableSteps << 2*60;
  5864. if (mSmallestUnit <= tuMinutes)
  5865. availableSteps << 5*60 << 10*60 << 15*60 << 30*60;
  5866. // hours range:
  5867. if (mSmallestUnit <= tuHours)
  5868. availableSteps << 1*3600 << 2*3600 << 3*3600 << 6*3600 << 12*3600 << 24*3600;
  5869. // pick available step that is most appropriate to approximate ideal step:
  5870. result = pickClosest(result, availableSteps);
  5871. } else // more than a day, go back to normal clean mantissa algorithm but in units of days
  5872. {
  5873. const double secondsPerDay = 3600*24;
  5874. result = cleanMantissa(result/secondsPerDay)*secondsPerDay;
  5875. }
  5876. return result;
  5877. }
  5878. /*! \internal
  5879. Returns the sub tick count appropriate for the provided \a tickStep and time displays.
  5880. \seebaseclassmethod
  5881. */
  5882. int QCPAxisTickerTime::getSubTickCount(double tickStep)
  5883. {
  5884. int result = QCPAxisTicker::getSubTickCount(tickStep);
  5885. switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day range (as specified in getTickStep)
  5886. {
  5887. case 5*60: result = 4; break;
  5888. case 10*60: result = 1; break;
  5889. case 15*60: result = 2; break;
  5890. case 30*60: result = 1; break;
  5891. case 60*60: result = 3; break;
  5892. case 3600*2: result = 3; break;
  5893. case 3600*3: result = 2; break;
  5894. case 3600*6: result = 1; break;
  5895. case 3600*12: result = 3; break;
  5896. case 3600*24: result = 3; break;
  5897. }
  5898. return result;
  5899. }
  5900. /*! \internal
  5901. Returns the tick label corresponding to the provided \a tick and the configured format and field
  5902. widths (\ref setTimeFormat, \ref setFieldWidth).
  5903. \seebaseclassmethod
  5904. */
  5905. QString QCPAxisTickerTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  5906. {
  5907. Q_UNUSED(precision)
  5908. Q_UNUSED(formatChar)
  5909. Q_UNUSED(locale)
  5910. bool negative = tick < 0;
  5911. if (negative) tick *= -1;
  5912. double values[tuDays+1]; // contains the msec/sec/min/... value with its respective modulo (e.g. minute 0..59)
  5913. double restValues[tuDays+1]; // contains the msec/sec/min/... value as if it's the largest available unit and thus consumes the remaining time
  5914. restValues[tuMilliseconds] = tick*1000;
  5915. values[tuMilliseconds] = modf(restValues[tuMilliseconds]/1000, &restValues[tuSeconds])*1000;
  5916. values[tuSeconds] = modf(restValues[tuSeconds]/60, &restValues[tuMinutes])*60;
  5917. values[tuMinutes] = modf(restValues[tuMinutes]/60, &restValues[tuHours])*60;
  5918. values[tuHours] = modf(restValues[tuHours]/24, &restValues[tuDays])*24;
  5919. // no need to set values[tuDays] because days are always a rest value (there is no higher unit so it consumes all remaining time)
  5920. QString result = mTimeFormat;
  5921. for (int i = mSmallestUnit; i <= mBiggestUnit; ++i)
  5922. {
  5923. TimeUnit iUnit = static_cast<TimeUnit>(i);
  5924. replaceUnit(result, iUnit, qRound(iUnit == mBiggestUnit ? restValues[iUnit] : values[iUnit]));
  5925. }
  5926. if (negative)
  5927. result.prepend(QLatin1Char('-'));
  5928. return result;
  5929. }
  5930. /*! \internal
  5931. Replaces all occurrences of the format pattern belonging to \a unit in \a text with the specified
  5932. \a value, using the field width as specified with \ref setFieldWidth for the \a unit.
  5933. */
  5934. void QCPAxisTickerTime::replaceUnit(QString &text, QCPAxisTickerTime::TimeUnit unit, int value) const
  5935. {
  5936. QString valueStr = QString::number(value);
  5937. while (valueStr.size() < mFieldWidth.value(unit))
  5938. valueStr.prepend(QLatin1Char('0'));
  5939. text.replace(mFormatPattern.value(unit), valueStr);
  5940. }
  5941. /* end of 'src/axis/axistickertime.cpp' */
  5942. /* including file 'src/axis/axistickerfixed.cpp' */
  5943. /* modified 2021-03-29T02:30:44, size 5575 */
  5944. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5945. //////////////////// QCPAxisTickerFixed
  5946. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5947. /*! \class QCPAxisTickerFixed
  5948. \brief Specialized axis ticker with a fixed tick step
  5949. \image html axisticker-fixed.png
  5950. This QCPAxisTicker subclass generates ticks with a fixed tick step set with \ref setTickStep. It
  5951. is also possible to allow integer multiples and integer powers of the specified tick step with
  5952. \ref setScaleStrategy.
  5953. A typical application of this ticker is to make an axis only display integers, by setting the
  5954. tick step of the ticker to 1.0 and the scale strategy to \ref ssMultiples.
  5955. Another case is when a certain number has a special meaning and axis ticks should only appear at
  5956. multiples of that value. In this case you might also want to consider \ref QCPAxisTickerPi
  5957. because despite the name it is not limited to only pi symbols/values.
  5958. The ticker can be created and assigned to an axis like this:
  5959. \snippet documentation/doc-image-generator/mainwindow.cpp axistickerfixed-creation
  5960. */
  5961. /*!
  5962. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  5963. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  5964. */
  5965. QCPAxisTickerFixed::QCPAxisTickerFixed() :
  5966. mTickStep(1.0),
  5967. mScaleStrategy(ssNone)
  5968. {
  5969. }
  5970. /*!
  5971. Sets the fixed tick interval to \a step.
  5972. The axis ticker will only use this tick step when generating axis ticks. This might cause a very
  5973. high tick density and overlapping labels if the axis range is zoomed out. Using \ref
  5974. setScaleStrategy it is possible to relax the fixed step and also allow multiples or powers of \a
  5975. step. This will enable the ticker to reduce the number of ticks to a reasonable amount (see \ref
  5976. setTickCount).
  5977. */
  5978. void QCPAxisTickerFixed::setTickStep(double step)
  5979. {
  5980. if (step > 0)
  5981. mTickStep = step;
  5982. else
  5983. qDebug() << Q_FUNC_INFO << "tick step must be greater than zero:" << step;
  5984. }
  5985. /*!
  5986. Sets whether the specified tick step (\ref setTickStep) is absolutely fixed or whether
  5987. modifications may be applied to it before calculating the finally used tick step, such as
  5988. permitting multiples or powers. See \ref ScaleStrategy for details.
  5989. The default strategy is \ref ssNone, which means the tick step is absolutely fixed.
  5990. */
  5991. void QCPAxisTickerFixed::setScaleStrategy(QCPAxisTickerFixed::ScaleStrategy strategy)
  5992. {
  5993. mScaleStrategy = strategy;
  5994. }
  5995. /*! \internal
  5996. Determines the actually used tick step from the specified tick step and scale strategy (\ref
  5997. setTickStep, \ref setScaleStrategy).
  5998. This method either returns the specified tick step exactly, or, if the scale strategy is not \ref
  5999. ssNone, a modification of it to allow varying the number of ticks in the current axis range.
  6000. \seebaseclassmethod
  6001. */
  6002. double QCPAxisTickerFixed::getTickStep(const QCPRange &range)
  6003. {
  6004. switch (mScaleStrategy)
  6005. {
  6006. case ssNone:
  6007. {
  6008. return mTickStep;
  6009. }
  6010. case ssMultiples:
  6011. {
  6012. double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  6013. if (exactStep < mTickStep)
  6014. return mTickStep;
  6015. else
  6016. return qint64(cleanMantissa(exactStep/mTickStep)+0.5)*mTickStep;
  6017. }
  6018. case ssPowers:
  6019. {
  6020. double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  6021. return qPow(mTickStep, int(qLn(exactStep)/qLn(mTickStep)+0.5));
  6022. }
  6023. }
  6024. return mTickStep;
  6025. }
  6026. /* end of 'src/axis/axistickerfixed.cpp' */
  6027. /* including file 'src/axis/axistickertext.cpp' */
  6028. /* modified 2021-03-29T02:30:44, size 8742 */
  6029. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6030. //////////////////// QCPAxisTickerText
  6031. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6032. /*! \class QCPAxisTickerText
  6033. \brief Specialized axis ticker which allows arbitrary labels at specified coordinates
  6034. \image html axisticker-text.png
  6035. This QCPAxisTicker subclass generates ticks which can be directly specified by the user as
  6036. coordinates and associated strings. They can be passed as a whole with \ref setTicks or one at a
  6037. time with \ref addTick. Alternatively you can directly access the internal storage via \ref ticks
  6038. and modify the tick/label data there.
  6039. This is useful for cases where the axis represents categories rather than numerical values.
  6040. If you are updating the ticks of this ticker regularly and in a dynamic fasion (e.g. dependent on
  6041. the axis range), it is a sign that you should probably create an own ticker by subclassing
  6042. QCPAxisTicker, instead of using this one.
  6043. The ticker can be created and assigned to an axis like this:
  6044. \snippet documentation/doc-image-generator/mainwindow.cpp axistickertext-creation
  6045. */
  6046. /* start of documentation of inline functions */
  6047. /*! \fn QMap<double, QString> &QCPAxisTickerText::ticks()
  6048. Returns a non-const reference to the internal map which stores the tick coordinates and their
  6049. labels.
  6050. You can access the map directly in order to add, remove or manipulate ticks, as an alternative to
  6051. using the methods provided by QCPAxisTickerText, such as \ref setTicks and \ref addTick.
  6052. */
  6053. /* end of documentation of inline functions */
  6054. /*!
  6055. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  6056. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  6057. */
  6058. QCPAxisTickerText::QCPAxisTickerText() :
  6059. mSubTickCount(0)
  6060. {
  6061. }
  6062. /*! \overload
  6063. Sets the ticks that shall appear on the axis. The map key of \a ticks corresponds to the axis
  6064. coordinate, and the map value is the string that will appear as tick label.
  6065. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  6066. getter.
  6067. \see addTicks, addTick, clear
  6068. */
  6069. void QCPAxisTickerText::setTicks(const QMap<double, QString> &ticks)
  6070. {
  6071. mTicks = ticks;
  6072. }
  6073. /*! \overload
  6074. Sets the ticks that shall appear on the axis. The entries of \a positions correspond to the axis
  6075. coordinates, and the entries of \a labels are the respective strings that will appear as tick
  6076. labels.
  6077. \see addTicks, addTick, clear
  6078. */
  6079. void QCPAxisTickerText::setTicks(const QVector<double> &positions, const QVector<QString> &labels)
  6080. {
  6081. clear();
  6082. addTicks(positions, labels);
  6083. }
  6084. /*!
  6085. Sets the number of sub ticks that shall appear between ticks. For QCPAxisTickerText, there is no
  6086. automatic sub tick count calculation. So if sub ticks are needed, they must be configured with this
  6087. method.
  6088. */
  6089. void QCPAxisTickerText::setSubTickCount(int subTicks)
  6090. {
  6091. if (subTicks >= 0)
  6092. mSubTickCount = subTicks;
  6093. else
  6094. qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks;
  6095. }
  6096. /*!
  6097. Clears all ticks.
  6098. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  6099. getter.
  6100. \see setTicks, addTicks, addTick
  6101. */
  6102. void QCPAxisTickerText::clear()
  6103. {
  6104. mTicks.clear();
  6105. }
  6106. /*!
  6107. Adds a single tick to the axis at the given axis coordinate \a position, with the provided tick \a
  6108. label.
  6109. \see addTicks, setTicks, clear
  6110. */
  6111. void QCPAxisTickerText::addTick(double position, const QString &label)
  6112. {
  6113. mTicks.insert(position, label);
  6114. }
  6115. /*! \overload
  6116. Adds the provided \a ticks to the ones already existing. The map key of \a ticks corresponds to
  6117. the axis coordinate, and the map value is the string that will appear as tick label.
  6118. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  6119. getter.
  6120. \see addTick, setTicks, clear
  6121. */
  6122. void QCPAxisTickerText::addTicks(const QMap<double, QString> &ticks)
  6123. {
  6124. #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
  6125. mTicks.unite(ticks);
  6126. #else
  6127. mTicks.insert(ticks);
  6128. #endif
  6129. }
  6130. /*! \overload
  6131. Adds the provided ticks to the ones already existing. The entries of \a positions correspond to
  6132. the axis coordinates, and the entries of \a labels are the respective strings that will appear as
  6133. tick labels.
  6134. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  6135. getter.
  6136. \see addTick, setTicks, clear
  6137. */
  6138. void QCPAxisTickerText::addTicks(const QVector<double> &positions, const QVector<QString> &labels)
  6139. {
  6140. if (positions.size() != labels.size())
  6141. qDebug() << Q_FUNC_INFO << "passed unequal length vectors for positions and labels:" << positions.size() << labels.size();
  6142. int n = qMin(positions.size(), labels.size());
  6143. for (int i=0; i<n; ++i)
  6144. mTicks.insert(positions.at(i), labels.at(i));
  6145. }
  6146. /*!
  6147. Since the tick coordinates are provided externally, this method implementation does nothing.
  6148. \seebaseclassmethod
  6149. */
  6150. double QCPAxisTickerText::getTickStep(const QCPRange &range)
  6151. {
  6152. // text axis ticker has manual tick positions, so doesn't need this method
  6153. Q_UNUSED(range)
  6154. return 1.0;
  6155. }
  6156. /*!
  6157. Returns the sub tick count that was configured with \ref setSubTickCount.
  6158. \seebaseclassmethod
  6159. */
  6160. int QCPAxisTickerText::getSubTickCount(double tickStep)
  6161. {
  6162. Q_UNUSED(tickStep)
  6163. return mSubTickCount;
  6164. }
  6165. /*!
  6166. Returns the tick label which corresponds to the key \a tick in the internal tick storage. Since
  6167. the labels are provided externally, \a locale, \a formatChar, and \a precision are ignored.
  6168. \seebaseclassmethod
  6169. */
  6170. QString QCPAxisTickerText::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  6171. {
  6172. Q_UNUSED(locale)
  6173. Q_UNUSED(formatChar)
  6174. Q_UNUSED(precision)
  6175. return mTicks.value(tick);
  6176. }
  6177. /*!
  6178. Returns the externally provided tick coordinates which are in the specified \a range. If
  6179. available, one tick above and below the range is provided in addition, to allow possible sub tick
  6180. calculation. The parameter \a tickStep is ignored.
  6181. \seebaseclassmethod
  6182. */
  6183. QVector<double> QCPAxisTickerText::createTickVector(double tickStep, const QCPRange &range)
  6184. {
  6185. Q_UNUSED(tickStep)
  6186. QVector<double> result;
  6187. if (mTicks.isEmpty())
  6188. return result;
  6189. QMap<double, QString>::const_iterator start = mTicks.lowerBound(range.lower);
  6190. QMap<double, QString>::const_iterator end = mTicks.upperBound(range.upper);
  6191. // this method should try to give one tick outside of range so proper subticks can be generated:
  6192. if (start != mTicks.constBegin()) --start;
  6193. if (end != mTicks.constEnd()) ++end;
  6194. for (QMap<double, QString>::const_iterator it = start; it != end; ++it)
  6195. result.append(it.key());
  6196. return result;
  6197. }
  6198. /* end of 'src/axis/axistickertext.cpp' */
  6199. /* including file 'src/axis/axistickerpi.cpp' */
  6200. /* modified 2021-03-29T02:30:44, size 11177 */
  6201. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6202. //////////////////// QCPAxisTickerPi
  6203. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6204. /*! \class QCPAxisTickerPi
  6205. \brief Specialized axis ticker to display ticks in units of an arbitrary constant, for example pi
  6206. \image html axisticker-pi.png
  6207. This QCPAxisTicker subclass generates ticks that are expressed with respect to a given symbolic
  6208. constant with a numerical value specified with \ref setPiValue and an appearance in the tick
  6209. labels specified with \ref setPiSymbol.
  6210. Ticks may be generated at fractions of the symbolic constant. How these fractions appear in the
  6211. tick label can be configured with \ref setFractionStyle.
  6212. The ticker can be created and assigned to an axis like this:
  6213. \snippet documentation/doc-image-generator/mainwindow.cpp axistickerpi-creation
  6214. */
  6215. /*!
  6216. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  6217. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  6218. */
  6219. QCPAxisTickerPi::QCPAxisTickerPi() :
  6220. mPiSymbol(QLatin1String(" ")+QChar(0x03C0)),
  6221. mPiValue(M_PI),
  6222. mPeriodicity(0),
  6223. mFractionStyle(fsUnicodeFractions),
  6224. mPiTickStep(0)
  6225. {
  6226. setTickCount(4);
  6227. }
  6228. /*!
  6229. Sets how the symbol part (which is always a suffix to the number) shall appear in the axis tick
  6230. label.
  6231. If a space shall appear between the number and the symbol, make sure the space is contained in \a
  6232. symbol.
  6233. */
  6234. void QCPAxisTickerPi::setPiSymbol(QString symbol)
  6235. {
  6236. mPiSymbol = symbol;
  6237. }
  6238. /*!
  6239. Sets the numerical value that the symbolic constant has.
  6240. This will be used to place the appropriate fractions of the symbol at the respective axis
  6241. coordinates.
  6242. */
  6243. void QCPAxisTickerPi::setPiValue(double pi)
  6244. {
  6245. mPiValue = pi;
  6246. }
  6247. /*!
  6248. Sets whether the axis labels shall appear periodicly and if so, at which multiplicity of the
  6249. symbolic constant.
  6250. To disable periodicity, set \a multiplesOfPi to zero.
  6251. For example, an axis that identifies 0 with 2pi would set \a multiplesOfPi to two.
  6252. */
  6253. void QCPAxisTickerPi::setPeriodicity(int multiplesOfPi)
  6254. {
  6255. mPeriodicity = qAbs(multiplesOfPi);
  6256. }
  6257. /*!
  6258. Sets how the numerical/fractional part preceding the symbolic constant is displayed in tick
  6259. labels. See \ref FractionStyle for the various options.
  6260. */
  6261. void QCPAxisTickerPi::setFractionStyle(QCPAxisTickerPi::FractionStyle style)
  6262. {
  6263. mFractionStyle = style;
  6264. }
  6265. /*! \internal
  6266. Returns the tick step, using the constant's value (\ref setPiValue) as base unit. In consequence
  6267. the numerical/fractional part preceding the symbolic constant is made to have a readable
  6268. mantissa.
  6269. \seebaseclassmethod
  6270. */
  6271. double QCPAxisTickerPi::getTickStep(const QCPRange &range)
  6272. {
  6273. mPiTickStep = range.size()/mPiValue/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  6274. mPiTickStep = cleanMantissa(mPiTickStep);
  6275. return mPiTickStep*mPiValue;
  6276. }
  6277. /*! \internal
  6278. Returns the sub tick count, using the constant's value (\ref setPiValue) as base unit. In
  6279. consequence the sub ticks divide the numerical/fractional part preceding the symbolic constant
  6280. reasonably, and not the total tick coordinate.
  6281. \seebaseclassmethod
  6282. */
  6283. int QCPAxisTickerPi::getSubTickCount(double tickStep)
  6284. {
  6285. return QCPAxisTicker::getSubTickCount(tickStep/mPiValue);
  6286. }
  6287. /*! \internal
  6288. Returns the tick label as a fractional/numerical part and a symbolic string as suffix. The
  6289. formatting of the fraction is done according to the specified \ref setFractionStyle. The appended
  6290. symbol is specified with \ref setPiSymbol.
  6291. \seebaseclassmethod
  6292. */
  6293. QString QCPAxisTickerPi::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  6294. {
  6295. double tickInPis = tick/mPiValue;
  6296. if (mPeriodicity > 0)
  6297. tickInPis = fmod(tickInPis, mPeriodicity);
  6298. if (mFractionStyle != fsFloatingPoint && mPiTickStep > 0.09 && mPiTickStep < 50)
  6299. {
  6300. // simply construct fraction from decimal like 1.234 -> 1234/1000 and then simplify fraction, smaller digits are irrelevant due to mPiTickStep conditional above
  6301. int denominator = 1000;
  6302. int numerator = qRound(tickInPis*denominator);
  6303. simplifyFraction(numerator, denominator);
  6304. if (qAbs(numerator) == 1 && denominator == 1)
  6305. return (numerator < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed();
  6306. else if (numerator == 0)
  6307. return QLatin1String("0");
  6308. else
  6309. return fractionToString(numerator, denominator) + mPiSymbol;
  6310. } else
  6311. {
  6312. if (qFuzzyIsNull(tickInPis))
  6313. return QLatin1String("0");
  6314. else if (qFuzzyCompare(qAbs(tickInPis), 1.0))
  6315. return (tickInPis < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed();
  6316. else
  6317. return QCPAxisTicker::getTickLabel(tickInPis, locale, formatChar, precision) + mPiSymbol;
  6318. }
  6319. }
  6320. /*! \internal
  6321. Takes the fraction given by \a numerator and \a denominator and modifies the values to make sure
  6322. the fraction is in irreducible form, i.e. numerator and denominator don't share any common
  6323. factors which could be cancelled.
  6324. */
  6325. void QCPAxisTickerPi::simplifyFraction(int &numerator, int &denominator) const
  6326. {
  6327. if (numerator == 0 || denominator == 0)
  6328. return;
  6329. int num = numerator;
  6330. int denom = denominator;
  6331. while (denom != 0) // euclidean gcd algorithm
  6332. {
  6333. int oldDenom = denom;
  6334. denom = num % denom;
  6335. num = oldDenom;
  6336. }
  6337. // num is now gcd of numerator and denominator
  6338. numerator /= num;
  6339. denominator /= num;
  6340. }
  6341. /*! \internal
  6342. Takes the fraction given by \a numerator and \a denominator and returns a string representation.
  6343. The result depends on the configured fraction style (\ref setFractionStyle).
  6344. This method is used to format the numerical/fractional part when generating tick labels. It
  6345. simplifies the passed fraction to an irreducible form using \ref simplifyFraction and factors out
  6346. any integer parts of the fraction (e.g. "10/4" becomes "2 1/2").
  6347. */
  6348. QString QCPAxisTickerPi::fractionToString(int numerator, int denominator) const
  6349. {
  6350. if (denominator == 0)
  6351. {
  6352. qDebug() << Q_FUNC_INFO << "called with zero denominator";
  6353. return QString();
  6354. }
  6355. if (mFractionStyle == fsFloatingPoint) // should never be the case when calling this function
  6356. {
  6357. qDebug() << Q_FUNC_INFO << "shouldn't be called with fraction style fsDecimal";
  6358. return QString::number(numerator/double(denominator)); // failsafe
  6359. }
  6360. int sign = numerator*denominator < 0 ? -1 : 1;
  6361. numerator = qAbs(numerator);
  6362. denominator = qAbs(denominator);
  6363. if (denominator == 1)
  6364. {
  6365. return QString::number(sign*numerator);
  6366. } else
  6367. {
  6368. int integerPart = numerator/denominator;
  6369. int remainder = numerator%denominator;
  6370. if (remainder == 0)
  6371. {
  6372. return QString::number(sign*integerPart);
  6373. } else
  6374. {
  6375. if (mFractionStyle == fsAsciiFractions)
  6376. {
  6377. return QString(QLatin1String("%1%2%3/%4"))
  6378. .arg(sign == -1 ? QLatin1String("-") : QLatin1String(""))
  6379. .arg(integerPart > 0 ? QString::number(integerPart)+QLatin1String(" ") : QString(QLatin1String("")))
  6380. .arg(remainder)
  6381. .arg(denominator);
  6382. } else if (mFractionStyle == fsUnicodeFractions)
  6383. {
  6384. return QString(QLatin1String("%1%2%3"))
  6385. .arg(sign == -1 ? QLatin1String("-") : QLatin1String(""))
  6386. .arg(integerPart > 0 ? QString::number(integerPart) : QLatin1String(""))
  6387. .arg(unicodeFraction(remainder, denominator));
  6388. }
  6389. }
  6390. }
  6391. return QString();
  6392. }
  6393. /*! \internal
  6394. Returns the unicode string representation of the fraction given by \a numerator and \a
  6395. denominator. This is the representation used in \ref fractionToString when the fraction style
  6396. (\ref setFractionStyle) is \ref fsUnicodeFractions.
  6397. This method doesn't use the single-character common fractions but builds each fraction from a
  6398. superscript unicode number, the unicode fraction character, and a subscript unicode number.
  6399. */
  6400. QString QCPAxisTickerPi::unicodeFraction(int numerator, int denominator) const
  6401. {
  6402. return unicodeSuperscript(numerator)+QChar(0x2044)+unicodeSubscript(denominator);
  6403. }
  6404. /*! \internal
  6405. Returns the unicode string representing \a number as superscript. This is used to build
  6406. unicode fractions in \ref unicodeFraction.
  6407. */
  6408. QString QCPAxisTickerPi::unicodeSuperscript(int number) const
  6409. {
  6410. if (number == 0)
  6411. return QString(QChar(0x2070));
  6412. QString result;
  6413. while (number > 0)
  6414. {
  6415. const int digit = number%10;
  6416. switch (digit)
  6417. {
  6418. case 1: { result.prepend(QChar(0x00B9)); break; }
  6419. case 2: { result.prepend(QChar(0x00B2)); break; }
  6420. case 3: { result.prepend(QChar(0x00B3)); break; }
  6421. default: { result.prepend(QChar(0x2070+digit)); break; }
  6422. }
  6423. number /= 10;
  6424. }
  6425. return result;
  6426. }
  6427. /*! \internal
  6428. Returns the unicode string representing \a number as subscript. This is used to build unicode
  6429. fractions in \ref unicodeFraction.
  6430. */
  6431. QString QCPAxisTickerPi::unicodeSubscript(int number) const
  6432. {
  6433. if (number == 0)
  6434. return QString(QChar(0x2080));
  6435. QString result;
  6436. while (number > 0)
  6437. {
  6438. result.prepend(QChar(0x2080+number%10));
  6439. number /= 10;
  6440. }
  6441. return result;
  6442. }
  6443. /* end of 'src/axis/axistickerpi.cpp' */
  6444. /* including file 'src/axis/axistickerlog.cpp' */
  6445. /* modified 2021-03-29T02:30:44, size 7890 */
  6446. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6447. //////////////////// QCPAxisTickerLog
  6448. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6449. /*! \class QCPAxisTickerLog
  6450. \brief Specialized axis ticker suited for logarithmic axes
  6451. \image html axisticker-log.png
  6452. This QCPAxisTicker subclass generates ticks with unequal tick intervals suited for logarithmic
  6453. axis scales. The ticks are placed at powers of the specified log base (\ref setLogBase).
  6454. Especially in the case of a log base equal to 10 (the default), it might be desirable to have
  6455. tick labels in the form of powers of ten without mantissa display. To achieve this, set the
  6456. number precision (\ref QCPAxis::setNumberPrecision) to zero and the number format (\ref
  6457. QCPAxis::setNumberFormat) to scientific (exponential) display with beautifully typeset decimal
  6458. powers, so a format string of <tt>"eb"</tt>. This will result in the following axis tick labels:
  6459. \image html axisticker-log-powers.png
  6460. The ticker can be created and assigned to an axis like this:
  6461. \snippet documentation/doc-image-generator/mainwindow.cpp axistickerlog-creation
  6462. Note that the nature of logarithmic ticks imply that there exists a smallest possible tick step,
  6463. corresponding to one multiplication by the log base. If the user zooms in further than that, no
  6464. new ticks would appear, leading to very sparse or even no axis ticks on the axis. To prevent this
  6465. situation, this ticker falls back to regular tick generation if the axis range would be covered
  6466. by too few logarithmically placed ticks.
  6467. */
  6468. /*!
  6469. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  6470. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  6471. */
  6472. QCPAxisTickerLog::QCPAxisTickerLog() :
  6473. mLogBase(10.0),
  6474. mSubTickCount(8), // generates 10 intervals
  6475. mLogBaseLnInv(1.0/qLn(mLogBase))
  6476. {
  6477. }
  6478. /*!
  6479. Sets the logarithm base used for tick coordinate generation. The ticks will be placed at integer
  6480. powers of \a base.
  6481. */
  6482. void QCPAxisTickerLog::setLogBase(double base)
  6483. {
  6484. if (base > 0)
  6485. {
  6486. mLogBase = base;
  6487. mLogBaseLnInv = 1.0/qLn(mLogBase);
  6488. } else
  6489. qDebug() << Q_FUNC_INFO << "log base has to be greater than zero:" << base;
  6490. }
  6491. /*!
  6492. Sets the number of sub ticks in a tick interval. Within each interval, the sub ticks are spaced
  6493. linearly to provide a better visual guide, so the sub tick density increases toward the higher
  6494. tick.
  6495. Note that \a subTicks is the number of sub ticks (not sub intervals) in one tick interval. So in
  6496. the case of logarithm base 10 an intuitive sub tick spacing would be achieved with eight sub
  6497. ticks (the default). This means e.g. between the ticks 10 and 100 there will be eight ticks,
  6498. namely at 20, 30, 40, 50, 60, 70, 80 and 90.
  6499. */
  6500. void QCPAxisTickerLog::setSubTickCount(int subTicks)
  6501. {
  6502. if (subTicks >= 0)
  6503. mSubTickCount = subTicks;
  6504. else
  6505. qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks;
  6506. }
  6507. /*! \internal
  6508. Returns the sub tick count specified in \ref setSubTickCount. For QCPAxisTickerLog, there is no
  6509. automatic sub tick count calculation necessary.
  6510. \seebaseclassmethod
  6511. */
  6512. int QCPAxisTickerLog::getSubTickCount(double tickStep)
  6513. {
  6514. Q_UNUSED(tickStep)
  6515. return mSubTickCount;
  6516. }
  6517. /*! \internal
  6518. Creates ticks with a spacing given by the logarithm base and an increasing integer power in the
  6519. provided \a range. The step in which the power increases tick by tick is chosen in order to keep
  6520. the total number of ticks as close as possible to the tick count (\ref setTickCount).
  6521. The parameter \a tickStep is ignored for the normal logarithmic ticker generation. Only when
  6522. zoomed in very far such that not enough logarithmically placed ticks would be visible, this
  6523. function falls back to the regular QCPAxisTicker::createTickVector, which then uses \a tickStep.
  6524. \seebaseclassmethod
  6525. */
  6526. QVector<double> QCPAxisTickerLog::createTickVector(double tickStep, const QCPRange &range)
  6527. {
  6528. QVector<double> result;
  6529. if (range.lower > 0 && range.upper > 0) // positive range
  6530. {
  6531. const double baseTickCount = qLn(range.upper/range.lower)*mLogBaseLnInv;
  6532. if (baseTickCount < 1.6) // if too few log ticks would be visible in axis range, fall back to regular tick vector generation
  6533. return QCPAxisTicker::createTickVector(tickStep, range);
  6534. const double exactPowerStep = baseTickCount/double(mTickCount+1e-10);
  6535. const double newLogBase = qPow(mLogBase, qMax(int(cleanMantissa(exactPowerStep)), 1));
  6536. double currentTick = qPow(newLogBase, qFloor(qLn(range.lower)/qLn(newLogBase)));
  6537. result.append(currentTick);
  6538. while (currentTick < range.upper && currentTick > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
  6539. {
  6540. currentTick *= newLogBase;
  6541. result.append(currentTick);
  6542. }
  6543. } else if (range.lower < 0 && range.upper < 0) // negative range
  6544. {
  6545. const double baseTickCount = qLn(range.lower/range.upper)*mLogBaseLnInv;
  6546. if (baseTickCount < 1.6) // if too few log ticks would be visible in axis range, fall back to regular tick vector generation
  6547. return QCPAxisTicker::createTickVector(tickStep, range);
  6548. const double exactPowerStep = baseTickCount/double(mTickCount+1e-10);
  6549. const double newLogBase = qPow(mLogBase, qMax(int(cleanMantissa(exactPowerStep)), 1));
  6550. double currentTick = -qPow(newLogBase, qCeil(qLn(-range.lower)/qLn(newLogBase)));
  6551. result.append(currentTick);
  6552. while (currentTick < range.upper && currentTick < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
  6553. {
  6554. currentTick /= newLogBase;
  6555. result.append(currentTick);
  6556. }
  6557. } else // invalid range for logarithmic scale, because lower and upper have different sign
  6558. {
  6559. qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << range.lower << ".." << range.upper;
  6560. }
  6561. return result;
  6562. }
  6563. /* end of 'src/axis/axistickerlog.cpp' */
  6564. /* including file 'src/axis/axis.cpp' */
  6565. /* modified 2021-03-29T02:30:44, size 99883 */
  6566. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6567. //////////////////// QCPGrid
  6568. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6569. /*! \class QCPGrid
  6570. \brief Responsible for drawing the grid of a QCPAxis.
  6571. This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the
  6572. grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref
  6573. QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself.
  6574. The axis and grid drawing was split into two classes to allow them to be placed on different
  6575. layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid
  6576. in the background and the axes in the foreground, and any plottables/items in between. This
  6577. described situation is the default setup, see the QCPLayer documentation.
  6578. */
  6579. /*!
  6580. Creates a QCPGrid instance and sets default values.
  6581. You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid.
  6582. */
  6583. QCPGrid::QCPGrid(QCPAxis *parentAxis) :
  6584. QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis),
  6585. mSubGridVisible{},
  6586. mAntialiasedSubGrid{},
  6587. mAntialiasedZeroLine{},
  6588. mParentAxis(parentAxis)
  6589. {
  6590. // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called
  6591. setParent(parentAxis);
  6592. setPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
  6593. setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
  6594. setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine));
  6595. setSubGridVisible(false);
  6596. setAntialiased(false);
  6597. setAntialiasedSubGrid(false);
  6598. setAntialiasedZeroLine(false);
  6599. }
  6600. /*!
  6601. Sets whether grid lines at sub tick marks are drawn.
  6602. \see setSubGridPen
  6603. */
  6604. void QCPGrid::setSubGridVisible(bool visible)
  6605. {
  6606. mSubGridVisible = visible;
  6607. }
  6608. /*!
  6609. Sets whether sub grid lines are drawn antialiased.
  6610. */
  6611. void QCPGrid::setAntialiasedSubGrid(bool enabled)
  6612. {
  6613. mAntialiasedSubGrid = enabled;
  6614. }
  6615. /*!
  6616. Sets whether zero lines are drawn antialiased.
  6617. */
  6618. void QCPGrid::setAntialiasedZeroLine(bool enabled)
  6619. {
  6620. mAntialiasedZeroLine = enabled;
  6621. }
  6622. /*!
  6623. Sets the pen with which (major) grid lines are drawn.
  6624. */
  6625. void QCPGrid::setPen(const QPen &pen)
  6626. {
  6627. mPen = pen;
  6628. }
  6629. /*!
  6630. Sets the pen with which sub grid lines are drawn.
  6631. */
  6632. void QCPGrid::setSubGridPen(const QPen &pen)
  6633. {
  6634. mSubGridPen = pen;
  6635. }
  6636. /*!
  6637. Sets the pen with which zero lines are drawn.
  6638. Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid
  6639. lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen.
  6640. */
  6641. void QCPGrid::setZeroLinePen(const QPen &pen)
  6642. {
  6643. mZeroLinePen = pen;
  6644. }
  6645. /*! \internal
  6646. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  6647. before drawing the major grid lines.
  6648. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  6649. This function takes into account the local setting of the antialiasing flag as well as the
  6650. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  6651. QCustomPlot::setNotAntialiasedElements.
  6652. \see setAntialiased
  6653. */
  6654. void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const
  6655. {
  6656. applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid);
  6657. }
  6658. /*! \internal
  6659. Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning
  6660. over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen).
  6661. */
  6662. void QCPGrid::draw(QCPPainter *painter)
  6663. {
  6664. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  6665. if (mParentAxis->subTicks() && mSubGridVisible)
  6666. drawSubGridLines(painter);
  6667. drawGridLines(painter);
  6668. }
  6669. /*! \internal
  6670. Draws the main grid lines and possibly a zero line with the specified painter.
  6671. This is a helper function called by \ref draw.
  6672. */
  6673. void QCPGrid::drawGridLines(QCPPainter *painter) const
  6674. {
  6675. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  6676. const int tickCount = mParentAxis->mTickVector.size();
  6677. double t; // helper variable, result of coordinate-to-pixel transforms
  6678. if (mParentAxis->orientation() == Qt::Horizontal)
  6679. {
  6680. // draw zeroline:
  6681. int zeroLineIndex = -1;
  6682. if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
  6683. {
  6684. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  6685. painter->setPen(mZeroLinePen);
  6686. double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero
  6687. for (int i=0; i<tickCount; ++i)
  6688. {
  6689. if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
  6690. {
  6691. zeroLineIndex = i;
  6692. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
  6693. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  6694. break;
  6695. }
  6696. }
  6697. }
  6698. // draw grid lines:
  6699. applyDefaultAntialiasingHint(painter);
  6700. painter->setPen(mPen);
  6701. for (int i=0; i<tickCount; ++i)
  6702. {
  6703. if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
  6704. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
  6705. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  6706. }
  6707. } else
  6708. {
  6709. // draw zeroline:
  6710. int zeroLineIndex = -1;
  6711. if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
  6712. {
  6713. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  6714. painter->setPen(mZeroLinePen);
  6715. double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero
  6716. for (int i=0; i<tickCount; ++i)
  6717. {
  6718. if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
  6719. {
  6720. zeroLineIndex = i;
  6721. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
  6722. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  6723. break;
  6724. }
  6725. }
  6726. }
  6727. // draw grid lines:
  6728. applyDefaultAntialiasingHint(painter);
  6729. painter->setPen(mPen);
  6730. for (int i=0; i<tickCount; ++i)
  6731. {
  6732. if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
  6733. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
  6734. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  6735. }
  6736. }
  6737. }
  6738. /*! \internal
  6739. Draws the sub grid lines with the specified painter.
  6740. This is a helper function called by \ref draw.
  6741. */
  6742. void QCPGrid::drawSubGridLines(QCPPainter *painter) const
  6743. {
  6744. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  6745. applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid);
  6746. double t; // helper variable, result of coordinate-to-pixel transforms
  6747. painter->setPen(mSubGridPen);
  6748. if (mParentAxis->orientation() == Qt::Horizontal)
  6749. {
  6750. foreach (double tickCoord, mParentAxis->mSubTickVector)
  6751. {
  6752. t = mParentAxis->coordToPixel(tickCoord); // x
  6753. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  6754. }
  6755. } else
  6756. {
  6757. foreach (double tickCoord, mParentAxis->mSubTickVector)
  6758. {
  6759. t = mParentAxis->coordToPixel(tickCoord); // y
  6760. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  6761. }
  6762. }
  6763. }
  6764. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6765. //////////////////// QCPAxis
  6766. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6767. /*! \class QCPAxis
  6768. \brief Manages a single axis inside a QCustomPlot.
  6769. Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via
  6770. QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and
  6771. QCustomPlot::yAxis2 (right).
  6772. Axes are always part of an axis rect, see QCPAxisRect.
  6773. \image html AxisNamesOverview.png
  6774. <center>Naming convention of axis parts</center>
  6775. \n
  6776. \image html AxisRectSpacingOverview.png
  6777. <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line
  6778. on the left represents the QCustomPlot widget border.</center>
  6779. Each axis holds an instance of QCPAxisTicker which is used to generate the tick coordinates and
  6780. tick labels. You can access the currently installed \ref ticker or set a new one (possibly one of
  6781. the specialized subclasses, or your own subclass) via \ref setTicker. For details, see the
  6782. documentation of QCPAxisTicker.
  6783. */
  6784. /* start of documentation of inline functions */
  6785. /*! \fn Qt::Orientation QCPAxis::orientation() const
  6786. Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced
  6787. from the axis type (left, top, right or bottom).
  6788. \see orientation(AxisType type), pixelOrientation
  6789. */
  6790. /*! \fn QCPGrid *QCPAxis::grid() const
  6791. Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the
  6792. grid is displayed.
  6793. */
  6794. /*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type)
  6795. Returns the orientation of the specified axis type
  6796. \see orientation(), pixelOrientation
  6797. */
  6798. /*! \fn int QCPAxis::pixelOrientation() const
  6799. Returns which direction points towards higher coordinate values/keys, in pixel space.
  6800. This method returns either 1 or -1. If it returns 1, then going in the positive direction along
  6801. the orientation of the axis in pixels corresponds to going from lower to higher axis coordinates.
  6802. On the other hand, if this method returns -1, going to smaller pixel values corresponds to going
  6803. from lower to higher axis coordinates.
  6804. For example, this is useful to easily shift axis coordinates by a certain amount given in pixels,
  6805. without having to care about reversed or vertically aligned axes:
  6806. \code
  6807. double newKey = keyAxis->pixelToCoord(keyAxis->coordToPixel(oldKey)+10*keyAxis->pixelOrientation());
  6808. \endcode
  6809. \a newKey will then contain a key that is ten pixels towards higher keys, starting from \a oldKey.
  6810. */
  6811. /*! \fn QSharedPointer<QCPAxisTicker> QCPAxis::ticker() const
  6812. Returns a modifiable shared pointer to the currently installed axis ticker. The axis ticker is
  6813. responsible for generating the tick positions and tick labels of this axis. You can access the
  6814. \ref QCPAxisTicker with this method and modify basic properties such as the approximate tick count
  6815. (\ref QCPAxisTicker::setTickCount).
  6816. You can gain more control over the axis ticks by setting a different \ref QCPAxisTicker subclass, see
  6817. the documentation there. A new axis ticker can be set with \ref setTicker.
  6818. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  6819. ticker simply by passing the same shared pointer to multiple axes.
  6820. \see setTicker
  6821. */
  6822. /* end of documentation of inline functions */
  6823. /* start of documentation of signals */
  6824. /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange)
  6825. This signal is emitted when the range of this axis has changed. You can connect it to the \ref
  6826. setRange slot of another axis to communicate the new range to the other axis, in order for it to
  6827. be synchronized.
  6828. You may also manipulate/correct the range with \ref setRange in a slot connected to this signal.
  6829. This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper
  6830. range shouldn't go beyond certain values (see \ref QCPRange::bounded). For example, the following
  6831. slot would limit the x axis to ranges between 0 and 10:
  6832. \code
  6833. customPlot->xAxis->setRange(newRange.bounded(0, 10))
  6834. \endcode
  6835. */
  6836. /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange)
  6837. \overload
  6838. Additionally to the new range, this signal also provides the previous range held by the axis as
  6839. \a oldRange.
  6840. */
  6841. /*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType);
  6842. This signal is emitted when the scale type changes, by calls to \ref setScaleType
  6843. */
  6844. /*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection)
  6845. This signal is emitted when the selection state of this axis has changed, either by user interaction
  6846. or by a direct call to \ref setSelectedParts.
  6847. */
  6848. /*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts);
  6849. This signal is emitted when the selectability changes, by calls to \ref setSelectableParts
  6850. */
  6851. /* end of documentation of signals */
  6852. /*!
  6853. Constructs an Axis instance of Type \a type for the axis rect \a parent.
  6854. Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create
  6855. them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however,
  6856. create them manually and then inject them also via \ref QCPAxisRect::addAxis.
  6857. */
  6858. QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) :
  6859. QCPLayerable(parent->parentPlot(), QString(), parent),
  6860. // axis base:
  6861. mAxisType(type),
  6862. mAxisRect(parent),
  6863. mPadding(5),
  6864. mOrientation(orientation(type)),
  6865. mSelectableParts(spAxis | spTickLabels | spAxisLabel),
  6866. mSelectedParts(spNone),
  6867. mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  6868. mSelectedBasePen(QPen(Qt::blue, 2)),
  6869. // axis label:
  6870. mLabel(),
  6871. mLabelFont(mParentPlot->font()),
  6872. mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
  6873. mLabelColor(Qt::black),
  6874. mSelectedLabelColor(Qt::blue),
  6875. // tick labels:
  6876. mTickLabels(true),
  6877. mTickLabelFont(mParentPlot->font()),
  6878. mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
  6879. mTickLabelColor(Qt::black),
  6880. mSelectedTickLabelColor(Qt::blue),
  6881. mNumberPrecision(6),
  6882. mNumberFormatChar('g'),
  6883. mNumberBeautifulPowers(true),
  6884. // ticks and subticks:
  6885. mTicks(true),
  6886. mSubTicks(true),
  6887. mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  6888. mSelectedTickPen(QPen(Qt::blue, 2)),
  6889. mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  6890. mSelectedSubTickPen(QPen(Qt::blue, 2)),
  6891. // scale and range:
  6892. mRange(0, 5),
  6893. mRangeReversed(false),
  6894. mScaleType(stLinear),
  6895. // internal members:
  6896. mGrid(new QCPGrid(this)),
  6897. mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())),
  6898. mTicker(new QCPAxisTicker),
  6899. mCachedMarginValid(false),
  6900. mCachedMargin(0),
  6901. mDragging(false)
  6902. {
  6903. setParent(parent);
  6904. mGrid->setVisible(false);
  6905. setAntialiased(false);
  6906. setLayer(mParentPlot->currentLayer()); // it's actually on that layer already, but we want it in front of the grid, so we place it on there again
  6907. if (type == atTop)
  6908. {
  6909. setTickLabelPadding(3);
  6910. setLabelPadding(6);
  6911. } else if (type == atRight)
  6912. {
  6913. setTickLabelPadding(7);
  6914. setLabelPadding(12);
  6915. } else if (type == atBottom)
  6916. {
  6917. setTickLabelPadding(3);
  6918. setLabelPadding(3);
  6919. } else if (type == atLeft)
  6920. {
  6921. setTickLabelPadding(5);
  6922. setLabelPadding(10);
  6923. }
  6924. }
  6925. QCPAxis::~QCPAxis()
  6926. {
  6927. delete mAxisPainter;
  6928. delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order
  6929. }
  6930. /* No documentation as it is a property getter */
  6931. int QCPAxis::tickLabelPadding() const
  6932. {
  6933. return mAxisPainter->tickLabelPadding;
  6934. }
  6935. /* No documentation as it is a property getter */
  6936. double QCPAxis::tickLabelRotation() const
  6937. {
  6938. return mAxisPainter->tickLabelRotation;
  6939. }
  6940. /* No documentation as it is a property getter */
  6941. QCPAxis::LabelSide QCPAxis::tickLabelSide() const
  6942. {
  6943. return mAxisPainter->tickLabelSide;
  6944. }
  6945. /* No documentation as it is a property getter */
  6946. QString QCPAxis::numberFormat() const
  6947. {
  6948. QString result;
  6949. result.append(mNumberFormatChar);
  6950. if (mNumberBeautifulPowers)
  6951. {
  6952. result.append(QLatin1Char('b'));
  6953. if (mAxisPainter->numberMultiplyCross)
  6954. result.append(QLatin1Char('c'));
  6955. }
  6956. return result;
  6957. }
  6958. /* No documentation as it is a property getter */
  6959. int QCPAxis::tickLengthIn() const
  6960. {
  6961. return mAxisPainter->tickLengthIn;
  6962. }
  6963. /* No documentation as it is a property getter */
  6964. int QCPAxis::tickLengthOut() const
  6965. {
  6966. return mAxisPainter->tickLengthOut;
  6967. }
  6968. /* No documentation as it is a property getter */
  6969. int QCPAxis::subTickLengthIn() const
  6970. {
  6971. return mAxisPainter->subTickLengthIn;
  6972. }
  6973. /* No documentation as it is a property getter */
  6974. int QCPAxis::subTickLengthOut() const
  6975. {
  6976. return mAxisPainter->subTickLengthOut;
  6977. }
  6978. /* No documentation as it is a property getter */
  6979. int QCPAxis::labelPadding() const
  6980. {
  6981. return mAxisPainter->labelPadding;
  6982. }
  6983. /* No documentation as it is a property getter */
  6984. int QCPAxis::offset() const
  6985. {
  6986. return int(mAxisPainter->offset);
  6987. }
  6988. /* No documentation as it is a property getter */
  6989. QCPLineEnding QCPAxis::lowerEnding() const
  6990. {
  6991. return mAxisPainter->lowerEnding;
  6992. }
  6993. /* No documentation as it is a property getter */
  6994. QCPLineEnding QCPAxis::upperEnding() const
  6995. {
  6996. return mAxisPainter->upperEnding;
  6997. }
  6998. /*!
  6999. Sets whether the axis uses a linear scale or a logarithmic scale.
  7000. Note that this method controls the coordinate transformation. For logarithmic scales, you will
  7001. likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting
  7002. the axis ticker to an instance of \ref QCPAxisTickerLog :
  7003. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-creation
  7004. See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick
  7005. creation.
  7006. \ref setNumberPrecision
  7007. */
  7008. void QCPAxis::setScaleType(QCPAxis::ScaleType type)
  7009. {
  7010. if (mScaleType != type)
  7011. {
  7012. mScaleType = type;
  7013. if (mScaleType == stLogarithmic)
  7014. setRange(mRange.sanitizedForLogScale());
  7015. mCachedMarginValid = false;
  7016. emit scaleTypeChanged(mScaleType);
  7017. }
  7018. }
  7019. /*!
  7020. Sets the range of the axis.
  7021. This slot may be connected with the \ref rangeChanged signal of another axis so this axis
  7022. is always synchronized with the other axis range, when it changes.
  7023. To invert the direction of an axis, use \ref setRangeReversed.
  7024. */
  7025. void QCPAxis::setRange(const QCPRange &range)
  7026. {
  7027. if (qFuzzyCompare(range.lower, mRange.lower) && qFuzzyCompare(range.upper, mRange.upper))
  7028. return;
  7029. if (!QCPRange::validRange(range)) return;
  7030. QCPRange oldRange = mRange;
  7031. if (mScaleType == stLogarithmic)
  7032. {
  7033. mRange = range.sanitizedForLogScale();
  7034. } else
  7035. {
  7036. mRange = range.sanitizedForLinScale();
  7037. }
  7038. emit rangeChanged(mRange);
  7039. emit rangeChanged(mRange, oldRange);
  7040. }
  7041. /*!
  7042. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  7043. (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
  7044. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  7045. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  7046. directly.
  7047. \see SelectablePart, setSelectedParts
  7048. */
  7049. void QCPAxis::setSelectableParts(const SelectableParts &selectable)
  7050. {
  7051. if (mSelectableParts != selectable)
  7052. {
  7053. mSelectableParts = selectable;
  7054. emit selectableChanged(mSelectableParts);
  7055. }
  7056. }
  7057. /*!
  7058. Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
  7059. is selected, it uses a different pen/font.
  7060. The entire selection mechanism for axes is handled automatically when \ref
  7061. QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
  7062. wish to change the selection state manually.
  7063. This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
  7064. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  7065. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
  7066. setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
  7067. */
  7068. void QCPAxis::setSelectedParts(const SelectableParts &selected)
  7069. {
  7070. if (mSelectedParts != selected)
  7071. {
  7072. mSelectedParts = selected;
  7073. emit selectionChanged(mSelectedParts);
  7074. }
  7075. }
  7076. /*!
  7077. \overload
  7078. Sets the lower and upper bound of the axis range.
  7079. To invert the direction of an axis, use \ref setRangeReversed.
  7080. There is also a slot to set a range, see \ref setRange(const QCPRange &range).
  7081. */
  7082. void QCPAxis::setRange(double lower, double upper)
  7083. {
  7084. if (qFuzzyCompare(lower, mRange.lower) && qFuzzyCompare(upper, mRange.upper))
  7085. return;
  7086. if (!QCPRange::validRange(lower, upper)) return;
  7087. QCPRange oldRange = mRange;
  7088. mRange.lower = lower;
  7089. mRange.upper = upper;
  7090. if (mScaleType == stLogarithmic)
  7091. {
  7092. mRange = mRange.sanitizedForLogScale();
  7093. } else
  7094. {
  7095. mRange = mRange.sanitizedForLinScale();
  7096. }
  7097. emit rangeChanged(mRange);
  7098. emit rangeChanged(mRange, oldRange);
  7099. }
  7100. /*!
  7101. \overload
  7102. Sets the range of the axis.
  7103. The \a position coordinate indicates together with the \a alignment parameter, where the new
  7104. range will be positioned. \a size defines the size of the new axis range. \a alignment may be
  7105. Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
  7106. or center of the range to be aligned with \a position. Any other values of \a alignment will
  7107. default to Qt::AlignCenter.
  7108. */
  7109. void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment)
  7110. {
  7111. if (alignment == Qt::AlignLeft)
  7112. setRange(position, position+size);
  7113. else if (alignment == Qt::AlignRight)
  7114. setRange(position-size, position);
  7115. else // alignment == Qt::AlignCenter
  7116. setRange(position-size/2.0, position+size/2.0);
  7117. }
  7118. /*!
  7119. Sets the lower bound of the axis range. The upper bound is not changed.
  7120. \see setRange
  7121. */
  7122. void QCPAxis::setRangeLower(double lower)
  7123. {
  7124. if (qFuzzyCompare(mRange.lower, lower))
  7125. return;
  7126. QCPRange oldRange = mRange;
  7127. mRange.lower = lower;
  7128. if (mScaleType == stLogarithmic)
  7129. {
  7130. mRange = mRange.sanitizedForLogScale();
  7131. } else
  7132. {
  7133. mRange = mRange.sanitizedForLinScale();
  7134. }
  7135. emit rangeChanged(mRange);
  7136. emit rangeChanged(mRange, oldRange);
  7137. }
  7138. /*!
  7139. Sets the upper bound of the axis range. The lower bound is not changed.
  7140. \see setRange
  7141. */
  7142. void QCPAxis::setRangeUpper(double upper)
  7143. {
  7144. if (qFuzzyCompare(mRange.upper, upper))
  7145. return;
  7146. QCPRange oldRange = mRange;
  7147. mRange.upper = upper;
  7148. if (mScaleType == stLogarithmic)
  7149. {
  7150. mRange = mRange.sanitizedForLogScale();
  7151. } else
  7152. {
  7153. mRange = mRange.sanitizedForLinScale();
  7154. }
  7155. emit rangeChanged(mRange);
  7156. emit rangeChanged(mRange, oldRange);
  7157. }
  7158. /*!
  7159. Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
  7160. axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
  7161. direction of increasing values is inverted.
  7162. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
  7163. of the \ref setRange interface will still reference the mathematically smaller number than the \a
  7164. upper part.
  7165. */
  7166. void QCPAxis::setRangeReversed(bool reversed)
  7167. {
  7168. mRangeReversed = reversed;
  7169. }
  7170. /*!
  7171. The axis ticker is responsible for generating the tick positions and tick labels. See the
  7172. documentation of QCPAxisTicker for details on how to work with axis tickers.
  7173. You can change the tick positioning/labeling behaviour of this axis by setting a different
  7174. QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
  7175. ticker, access it via \ref ticker.
  7176. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  7177. ticker simply by passing the same shared pointer to multiple axes.
  7178. \see ticker
  7179. */
  7180. void QCPAxis::setTicker(QSharedPointer<QCPAxisTicker> ticker)
  7181. {
  7182. if (ticker)
  7183. mTicker = ticker;
  7184. else
  7185. qDebug() << Q_FUNC_INFO << "can not set nullptr as axis ticker";
  7186. // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
  7187. }
  7188. /*!
  7189. Sets whether tick marks are displayed.
  7190. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
  7191. that, see \ref setTickLabels.
  7192. \see setSubTicks
  7193. */
  7194. void QCPAxis::setTicks(bool show)
  7195. {
  7196. if (mTicks != show)
  7197. {
  7198. mTicks = show;
  7199. mCachedMarginValid = false;
  7200. }
  7201. }
  7202. /*!
  7203. Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
  7204. */
  7205. void QCPAxis::setTickLabels(bool show)
  7206. {
  7207. if (mTickLabels != show)
  7208. {
  7209. mTickLabels = show;
  7210. mCachedMarginValid = false;
  7211. if (!mTickLabels)
  7212. mTickVectorLabels.clear();
  7213. }
  7214. }
  7215. /*!
  7216. Sets the distance between the axis base line (including any outward ticks) and the tick labels.
  7217. \see setLabelPadding, setPadding
  7218. */
  7219. void QCPAxis::setTickLabelPadding(int padding)
  7220. {
  7221. if (mAxisPainter->tickLabelPadding != padding)
  7222. {
  7223. mAxisPainter->tickLabelPadding = padding;
  7224. mCachedMarginValid = false;
  7225. }
  7226. }
  7227. /*!
  7228. Sets the font of the tick labels.
  7229. \see setTickLabels, setTickLabelColor
  7230. */
  7231. void QCPAxis::setTickLabelFont(const QFont &font)
  7232. {
  7233. if (font != mTickLabelFont)
  7234. {
  7235. mTickLabelFont = font;
  7236. mCachedMarginValid = false;
  7237. }
  7238. }
  7239. /*!
  7240. Sets the color of the tick labels.
  7241. \see setTickLabels, setTickLabelFont
  7242. */
  7243. void QCPAxis::setTickLabelColor(const QColor &color)
  7244. {
  7245. mTickLabelColor = color;
  7246. }
  7247. /*!
  7248. Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
  7249. the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
  7250. from -90 to 90 degrees.
  7251. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
  7252. other angles, the label is drawn with an offset such that it seems to point toward or away from
  7253. the tick mark.
  7254. */
  7255. void QCPAxis::setTickLabelRotation(double degrees)
  7256. {
  7257. if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation))
  7258. {
  7259. mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0);
  7260. mCachedMarginValid = false;
  7261. }
  7262. }
  7263. /*!
  7264. Sets whether the tick labels (numbers) shall appear inside or outside the axis rect.
  7265. The usual and default setting is \ref lsOutside. Very compact plots sometimes require tick labels
  7266. to be inside the axis rect, to save space. If \a side is set to \ref lsInside, the tick labels
  7267. appear on the inside are additionally clipped to the axis rect.
  7268. */
  7269. void QCPAxis::setTickLabelSide(LabelSide side)
  7270. {
  7271. mAxisPainter->tickLabelSide = side;
  7272. mCachedMarginValid = false;
  7273. }
  7274. /*!
  7275. Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
  7276. of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
  7277. that, see the "Argument Formats" section in the detailed description of the QString class.
  7278. \a formatCode is a string of one, two or three characters.
  7279. <b>The first character</b> is identical to
  7280. the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
  7281. format, 'g'/'G' scientific or fixed, whichever is shorter. For the 'e', 'E', and 'f' formats,
  7282. the precision set by \ref setNumberPrecision represents the number of digits after the decimal
  7283. point. For the 'g' and 'G' formats, the precision represents the maximum number of significant
  7284. digits, trailing zeroes are omitted.
  7285. <b>The second and third characters</b> are optional and specific to QCustomPlot:\n
  7286. If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
  7287. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for
  7288. "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
  7289. [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
  7290. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
  7291. be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
  7292. cross and 183 (0xB7) for the dot.
  7293. Examples for \a formatCode:
  7294. \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
  7295. normal scientific format is used
  7296. \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
  7297. beautifully typeset decimal powers and a dot as multiplication sign
  7298. \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
  7299. multiplication sign
  7300. \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
  7301. powers. Format code will be reduced to 'f'.
  7302. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
  7303. code will not be changed.
  7304. */
  7305. void QCPAxis::setNumberFormat(const QString &formatCode)
  7306. {
  7307. if (formatCode.isEmpty())
  7308. {
  7309. qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
  7310. return;
  7311. }
  7312. mCachedMarginValid = false;
  7313. // interpret first char as number format char:
  7314. QString allowedFormatChars(QLatin1String("eEfgG"));
  7315. if (allowedFormatChars.contains(formatCode.at(0)))
  7316. {
  7317. mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
  7318. } else
  7319. {
  7320. qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
  7321. return;
  7322. }
  7323. if (formatCode.length() < 2)
  7324. {
  7325. mNumberBeautifulPowers = false;
  7326. mAxisPainter->numberMultiplyCross = false;
  7327. return;
  7328. }
  7329. // interpret second char as indicator for beautiful decimal powers:
  7330. if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
  7331. {
  7332. mNumberBeautifulPowers = true;
  7333. } else
  7334. {
  7335. qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
  7336. return;
  7337. }
  7338. if (formatCode.length() < 3)
  7339. {
  7340. mAxisPainter->numberMultiplyCross = false;
  7341. return;
  7342. }
  7343. // interpret third char as indicator for dot or cross multiplication symbol:
  7344. if (formatCode.at(2) == QLatin1Char('c'))
  7345. {
  7346. mAxisPainter->numberMultiplyCross = true;
  7347. } else if (formatCode.at(2) == QLatin1Char('d'))
  7348. {
  7349. mAxisPainter->numberMultiplyCross = false;
  7350. } else
  7351. {
  7352. qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
  7353. return;
  7354. }
  7355. }
  7356. /*!
  7357. Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
  7358. for details. The effect of precisions are most notably for number Formats starting with 'e', see
  7359. \ref setNumberFormat
  7360. */
  7361. void QCPAxis::setNumberPrecision(int precision)
  7362. {
  7363. if (mNumberPrecision != precision)
  7364. {
  7365. mNumberPrecision = precision;
  7366. mCachedMarginValid = false;
  7367. }
  7368. }
  7369. /*!
  7370. Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
  7371. plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
  7372. zero, the tick labels and axis label will increase their distance to the axis accordingly, so
  7373. they won't collide with the ticks.
  7374. \see setSubTickLength, setTickLengthIn, setTickLengthOut
  7375. */
  7376. void QCPAxis::setTickLength(int inside, int outside)
  7377. {
  7378. setTickLengthIn(inside);
  7379. setTickLengthOut(outside);
  7380. }
  7381. /*!
  7382. Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
  7383. inside the plot.
  7384. \see setTickLengthOut, setTickLength, setSubTickLength
  7385. */
  7386. void QCPAxis::setTickLengthIn(int inside)
  7387. {
  7388. if (mAxisPainter->tickLengthIn != inside)
  7389. {
  7390. mAxisPainter->tickLengthIn = inside;
  7391. }
  7392. }
  7393. /*!
  7394. Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
  7395. outside the plot. If \a outside is greater than zero, the tick labels and axis label will
  7396. increase their distance to the axis accordingly, so they won't collide with the ticks.
  7397. \see setTickLengthIn, setTickLength, setSubTickLength
  7398. */
  7399. void QCPAxis::setTickLengthOut(int outside)
  7400. {
  7401. if (mAxisPainter->tickLengthOut != outside)
  7402. {
  7403. mAxisPainter->tickLengthOut = outside;
  7404. mCachedMarginValid = false; // only outside tick length can change margin
  7405. }
  7406. }
  7407. /*!
  7408. Sets whether sub tick marks are displayed.
  7409. Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
  7410. \see setTicks
  7411. */
  7412. void QCPAxis::setSubTicks(bool show)
  7413. {
  7414. if (mSubTicks != show)
  7415. {
  7416. mSubTicks = show;
  7417. mCachedMarginValid = false;
  7418. }
  7419. }
  7420. /*!
  7421. Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
  7422. the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
  7423. than zero, the tick labels and axis label will increase their distance to the axis accordingly,
  7424. so they won't collide with the ticks.
  7425. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
  7426. */
  7427. void QCPAxis::setSubTickLength(int inside, int outside)
  7428. {
  7429. setSubTickLengthIn(inside);
  7430. setSubTickLengthOut(outside);
  7431. }
  7432. /*!
  7433. Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
  7434. the plot.
  7435. \see setSubTickLengthOut, setSubTickLength, setTickLength
  7436. */
  7437. void QCPAxis::setSubTickLengthIn(int inside)
  7438. {
  7439. if (mAxisPainter->subTickLengthIn != inside)
  7440. {
  7441. mAxisPainter->subTickLengthIn = inside;
  7442. }
  7443. }
  7444. /*!
  7445. Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
  7446. outside the plot. If \a outside is greater than zero, the tick labels will increase their
  7447. distance to the axis accordingly, so they won't collide with the ticks.
  7448. \see setSubTickLengthIn, setSubTickLength, setTickLength
  7449. */
  7450. void QCPAxis::setSubTickLengthOut(int outside)
  7451. {
  7452. if (mAxisPainter->subTickLengthOut != outside)
  7453. {
  7454. mAxisPainter->subTickLengthOut = outside;
  7455. mCachedMarginValid = false; // only outside tick length can change margin
  7456. }
  7457. }
  7458. /*!
  7459. Sets the pen, the axis base line is drawn with.
  7460. \see setTickPen, setSubTickPen
  7461. */
  7462. void QCPAxis::setBasePen(const QPen &pen)
  7463. {
  7464. mBasePen = pen;
  7465. }
  7466. /*!
  7467. Sets the pen, tick marks will be drawn with.
  7468. \see setTickLength, setBasePen
  7469. */
  7470. void QCPAxis::setTickPen(const QPen &pen)
  7471. {
  7472. mTickPen = pen;
  7473. }
  7474. /*!
  7475. Sets the pen, subtick marks will be drawn with.
  7476. \see setSubTickCount, setSubTickLength, setBasePen
  7477. */
  7478. void QCPAxis::setSubTickPen(const QPen &pen)
  7479. {
  7480. mSubTickPen = pen;
  7481. }
  7482. /*!
  7483. Sets the font of the axis label.
  7484. \see setLabelColor
  7485. */
  7486. void QCPAxis::setLabelFont(const QFont &font)
  7487. {
  7488. if (mLabelFont != font)
  7489. {
  7490. mLabelFont = font;
  7491. mCachedMarginValid = false;
  7492. }
  7493. }
  7494. /*!
  7495. Sets the color of the axis label.
  7496. \see setLabelFont
  7497. */
  7498. void QCPAxis::setLabelColor(const QColor &color)
  7499. {
  7500. mLabelColor = color;
  7501. }
  7502. /*!
  7503. Sets the text of the axis label that will be shown below/above or next to the axis, depending on
  7504. its orientation. To disable axis labels, pass an empty string as \a str.
  7505. */
  7506. void QCPAxis::setLabel(const QString &str)
  7507. {
  7508. if (mLabel != str)
  7509. {
  7510. mLabel = str;
  7511. mCachedMarginValid = false;
  7512. }
  7513. }
  7514. /*!
  7515. Sets the distance between the tick labels and the axis label.
  7516. \see setTickLabelPadding, setPadding
  7517. */
  7518. void QCPAxis::setLabelPadding(int padding)
  7519. {
  7520. if (mAxisPainter->labelPadding != padding)
  7521. {
  7522. mAxisPainter->labelPadding = padding;
  7523. mCachedMarginValid = false;
  7524. }
  7525. }
  7526. /*!
  7527. Sets the padding of the axis.
  7528. When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space,
  7529. that is left blank.
  7530. The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled.
  7531. \see setLabelPadding, setTickLabelPadding
  7532. */
  7533. void QCPAxis::setPadding(int padding)
  7534. {
  7535. if (mPadding != padding)
  7536. {
  7537. mPadding = padding;
  7538. mCachedMarginValid = false;
  7539. }
  7540. }
  7541. /*!
  7542. Sets the offset the axis has to its axis rect side.
  7543. If an axis rect side has multiple axes and automatic margin calculation is enabled for that side,
  7544. only the offset of the inner most axis has meaning (even if it is set to be invisible). The
  7545. offset of the other, outer axes is controlled automatically, to place them at appropriate
  7546. positions.
  7547. */
  7548. void QCPAxis::setOffset(int offset)
  7549. {
  7550. mAxisPainter->offset = offset;
  7551. }
  7552. /*!
  7553. Sets the font that is used for tick labels when they are selected.
  7554. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7555. */
  7556. void QCPAxis::setSelectedTickLabelFont(const QFont &font)
  7557. {
  7558. if (font != mSelectedTickLabelFont)
  7559. {
  7560. mSelectedTickLabelFont = font;
  7561. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  7562. }
  7563. }
  7564. /*!
  7565. Sets the font that is used for the axis label when it is selected.
  7566. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7567. */
  7568. void QCPAxis::setSelectedLabelFont(const QFont &font)
  7569. {
  7570. mSelectedLabelFont = font;
  7571. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  7572. }
  7573. /*!
  7574. Sets the color that is used for tick labels when they are selected.
  7575. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7576. */
  7577. void QCPAxis::setSelectedTickLabelColor(const QColor &color)
  7578. {
  7579. if (color != mSelectedTickLabelColor)
  7580. {
  7581. mSelectedTickLabelColor = color;
  7582. }
  7583. }
  7584. /*!
  7585. Sets the color that is used for the axis label when it is selected.
  7586. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7587. */
  7588. void QCPAxis::setSelectedLabelColor(const QColor &color)
  7589. {
  7590. mSelectedLabelColor = color;
  7591. }
  7592. /*!
  7593. Sets the pen that is used to draw the axis base line when selected.
  7594. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7595. */
  7596. void QCPAxis::setSelectedBasePen(const QPen &pen)
  7597. {
  7598. mSelectedBasePen = pen;
  7599. }
  7600. /*!
  7601. Sets the pen that is used to draw the (major) ticks when selected.
  7602. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7603. */
  7604. void QCPAxis::setSelectedTickPen(const QPen &pen)
  7605. {
  7606. mSelectedTickPen = pen;
  7607. }
  7608. /*!
  7609. Sets the pen that is used to draw the subticks when selected.
  7610. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7611. */
  7612. void QCPAxis::setSelectedSubTickPen(const QPen &pen)
  7613. {
  7614. mSelectedSubTickPen = pen;
  7615. }
  7616. /*!
  7617. Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available
  7618. styles.
  7619. For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending.
  7620. Note that this meaning does not change when the axis range is reversed with \ref
  7621. setRangeReversed.
  7622. \see setUpperEnding
  7623. */
  7624. void QCPAxis::setLowerEnding(const QCPLineEnding &ending)
  7625. {
  7626. mAxisPainter->lowerEnding = ending;
  7627. }
  7628. /*!
  7629. Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available
  7630. styles.
  7631. For horizontal axes, this method refers to the right ending, for vertical axes the top ending.
  7632. Note that this meaning does not change when the axis range is reversed with \ref
  7633. setRangeReversed.
  7634. \see setLowerEnding
  7635. */
  7636. void QCPAxis::setUpperEnding(const QCPLineEnding &ending)
  7637. {
  7638. mAxisPainter->upperEnding = ending;
  7639. }
  7640. /*!
  7641. If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
  7642. bounds of the range. The range is simply moved by \a diff.
  7643. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
  7644. corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
  7645. */
  7646. void QCPAxis::moveRange(double diff)
  7647. {
  7648. QCPRange oldRange = mRange;
  7649. if (mScaleType == stLinear)
  7650. {
  7651. mRange.lower += diff;
  7652. mRange.upper += diff;
  7653. } else // mScaleType == stLogarithmic
  7654. {
  7655. mRange.lower *= diff;
  7656. mRange.upper *= diff;
  7657. }
  7658. emit rangeChanged(mRange);
  7659. emit rangeChanged(mRange, oldRange);
  7660. }
  7661. /*!
  7662. Scales the range of this axis by \a factor around the center of the current axis range. For
  7663. example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
  7664. range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
  7665. the center will have moved symmetrically closer).
  7666. If you wish to scale around a different coordinate than the current axis range center, use the
  7667. overload \ref scaleRange(double factor, double center).
  7668. */
  7669. void QCPAxis::scaleRange(double factor)
  7670. {
  7671. scaleRange(factor, range().center());
  7672. }
  7673. /*! \overload
  7674. Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
  7675. factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
  7676. coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
  7677. around 1.0 will have moved symmetrically closer to 1.0).
  7678. \see scaleRange(double factor)
  7679. */
  7680. void QCPAxis::scaleRange(double factor, double center)
  7681. {
  7682. QCPRange oldRange = mRange;
  7683. if (mScaleType == stLinear)
  7684. {
  7685. QCPRange newRange;
  7686. newRange.lower = (mRange.lower-center)*factor + center;
  7687. newRange.upper = (mRange.upper-center)*factor + center;
  7688. if (QCPRange::validRange(newRange))
  7689. mRange = newRange.sanitizedForLinScale();
  7690. } else // mScaleType == stLogarithmic
  7691. {
  7692. if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range
  7693. {
  7694. QCPRange newRange;
  7695. newRange.lower = qPow(mRange.lower/center, factor)*center;
  7696. newRange.upper = qPow(mRange.upper/center, factor)*center;
  7697. if (QCPRange::validRange(newRange))
  7698. mRange = newRange.sanitizedForLogScale();
  7699. } else
  7700. qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center;
  7701. }
  7702. emit rangeChanged(mRange);
  7703. emit rangeChanged(mRange, oldRange);
  7704. }
  7705. /*!
  7706. Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will
  7707. be done around the center of the current axis range.
  7708. For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs
  7709. plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the
  7710. axis rect has.
  7711. This is an operation that changes the range of this axis once, it doesn't fix the scale ratio
  7712. indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent
  7713. won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent
  7714. will follow.
  7715. */
  7716. void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio)
  7717. {
  7718. double otherPixelSize, ownPixelSize;
  7719. if (otherAxis->orientation() == Qt::Horizontal)
  7720. otherPixelSize = otherAxis->axisRect()->width();
  7721. else
  7722. otherPixelSize = otherAxis->axisRect()->height();
  7723. if (orientation() == Qt::Horizontal)
  7724. ownPixelSize = axisRect()->width();
  7725. else
  7726. ownPixelSize = axisRect()->height();
  7727. double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/double(otherPixelSize);
  7728. setRange(range().center(), newRangeSize, Qt::AlignCenter);
  7729. }
  7730. /*!
  7731. Changes the axis range such that all plottables associated with this axis are fully visible in
  7732. that dimension.
  7733. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
  7734. */
  7735. void QCPAxis::rescale(bool onlyVisiblePlottables)
  7736. {
  7737. QCPRange newRange;
  7738. bool haveRange = false;
  7739. foreach (QCPAbstractPlottable *plottable, plottables())
  7740. {
  7741. if (!plottable->realVisibility() && onlyVisiblePlottables)
  7742. continue;
  7743. QCPRange plottableRange;
  7744. bool currentFoundRange;
  7745. QCP::SignDomain signDomain = QCP::sdBoth;
  7746. if (mScaleType == stLogarithmic)
  7747. signDomain = (mRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  7748. if (plottable->keyAxis() == this)
  7749. plottableRange = plottable->getKeyRange(currentFoundRange, signDomain);
  7750. else
  7751. plottableRange = plottable->getValueRange(currentFoundRange, signDomain);
  7752. if (currentFoundRange)
  7753. {
  7754. if (!haveRange)
  7755. newRange = plottableRange;
  7756. else
  7757. newRange.expand(plottableRange);
  7758. haveRange = true;
  7759. }
  7760. }
  7761. if (haveRange)
  7762. {
  7763. if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
  7764. {
  7765. double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
  7766. if (mScaleType == stLinear)
  7767. {
  7768. newRange.lower = center-mRange.size()/2.0;
  7769. newRange.upper = center+mRange.size()/2.0;
  7770. } else // mScaleType == stLogarithmic
  7771. {
  7772. newRange.lower = center/qSqrt(mRange.upper/mRange.lower);
  7773. newRange.upper = center*qSqrt(mRange.upper/mRange.lower);
  7774. }
  7775. }
  7776. setRange(newRange);
  7777. }
  7778. }
  7779. /*!
  7780. Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
  7781. */
  7782. double QCPAxis::pixelToCoord(double value) const
  7783. {
  7784. if (orientation() == Qt::Horizontal)
  7785. {
  7786. auto width = mAxisRect->right() - mAxisRect->left();
  7787. // auto width = mAxisRect->width();
  7788. if (mScaleType == stLinear)
  7789. {
  7790. if (!mRangeReversed)
  7791. return (value-mAxisRect->left())/width*mRange.size()+mRange.lower;
  7792. else
  7793. return -(value-mAxisRect->left())/width*mRange.size()+mRange.upper;
  7794. } else // mScaleType == stLogarithmic
  7795. {
  7796. if (!mRangeReversed)
  7797. return qPow(mRange.upper/mRange.lower, (value-mAxisRect->left())/width)*mRange.lower;
  7798. else
  7799. return qPow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/width)*mRange.upper;
  7800. }
  7801. } else // orientation() == Qt::Vertical
  7802. {
  7803. auto height = mAxisRect->bottom() - mAxisRect->top();
  7804. // auto height = mAxisRect->height();
  7805. if (mScaleType == stLinear)
  7806. {
  7807. if (!mRangeReversed)
  7808. return (mAxisRect->bottom()-value)/height*mRange.size()+mRange.lower;
  7809. else
  7810. return -(mAxisRect->bottom()-value)/height*mRange.size()+mRange.upper;
  7811. } else // mScaleType == stLogarithmic
  7812. {
  7813. if (!mRangeReversed)
  7814. return qPow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/height)*mRange.lower;
  7815. else
  7816. return qPow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/height)*mRange.upper;
  7817. }
  7818. }
  7819. }
  7820. /*!
  7821. Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
  7822. */
  7823. double QCPAxis::coordToPixel(double value) const
  7824. {
  7825. if (orientation() == Qt::Horizontal)
  7826. {
  7827. auto width = mAxisRect->right() - mAxisRect->left();
  7828. // auto width = mAxisRect->width();
  7829. if (mScaleType == stLinear)
  7830. {
  7831. if (!mRangeReversed)
  7832. return (value-mRange.lower)/mRange.size()*width+mAxisRect->left();
  7833. else
  7834. return (mRange.upper-value)/mRange.size()*width+mAxisRect->left();
  7835. } else // mScaleType == stLogarithmic
  7836. {
  7837. if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7838. return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200;
  7839. else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7840. return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200;
  7841. else
  7842. {
  7843. if (!mRangeReversed)
  7844. return qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*width+mAxisRect->left();
  7845. else
  7846. return qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*width+mAxisRect->left();
  7847. }
  7848. }
  7849. } else // orientation() == Qt::Vertical
  7850. {
  7851. auto height = mAxisRect->bottom() - mAxisRect->top();
  7852. // auto height = mAxisRect->height();
  7853. if (mScaleType == stLinear)
  7854. {
  7855. if (!mRangeReversed)
  7856. return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*height;
  7857. else
  7858. return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*height;
  7859. } else // mScaleType == stLogarithmic
  7860. {
  7861. if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7862. return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200;
  7863. else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7864. return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200;
  7865. else
  7866. {
  7867. if (!mRangeReversed)
  7868. return mAxisRect->bottom()-qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*height;
  7869. else
  7870. return mAxisRect->bottom()-qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*height;
  7871. }
  7872. }
  7873. }
  7874. }
  7875. /*!
  7876. Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
  7877. is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
  7878. function does not change the current selection state of the axis.
  7879. If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
  7880. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
  7881. */
  7882. QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const
  7883. {
  7884. if (!mVisible)
  7885. return spNone;
  7886. if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
  7887. return spAxis;
  7888. else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
  7889. return spTickLabels;
  7890. else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
  7891. return spAxisLabel;
  7892. else
  7893. return spNone;
  7894. }
  7895. /* inherits documentation from base class */
  7896. double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  7897. {
  7898. if (!mParentPlot) return -1;
  7899. SelectablePart part = getPartAt(pos);
  7900. if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
  7901. return -1;
  7902. if (details)
  7903. details->setValue(part);
  7904. return mParentPlot->selectionTolerance()*0.99;
  7905. }
  7906. /*!
  7907. Returns a list of all the plottables that have this axis as key or value axis.
  7908. If you are only interested in plottables of type QCPGraph, see \ref graphs.
  7909. \see graphs, items
  7910. */
  7911. QList<QCPAbstractPlottable*> QCPAxis::plottables() const
  7912. {
  7913. QList<QCPAbstractPlottable*> result;
  7914. if (!mParentPlot) return result;
  7915. foreach (QCPAbstractPlottable *plottable, mParentPlot->mPlottables)
  7916. {
  7917. if (plottable->keyAxis() == this || plottable->valueAxis() == this)
  7918. result.append(plottable);
  7919. }
  7920. return result;
  7921. }
  7922. /*!
  7923. Returns a list of all the graphs that have this axis as key or value axis.
  7924. \see plottables, items
  7925. */
  7926. QList<QCPGraph*> QCPAxis::graphs() const
  7927. {
  7928. QList<QCPGraph*> result;
  7929. if (!mParentPlot) return result;
  7930. foreach (QCPGraph *graph, mParentPlot->mGraphs)
  7931. {
  7932. if (graph->keyAxis() == this || graph->valueAxis() == this)
  7933. result.append(graph);
  7934. }
  7935. return result;
  7936. }
  7937. /*!
  7938. Returns a list of all the items that are associated with this axis. An item is considered
  7939. associated with an axis if at least one of its positions uses the axis as key or value axis.
  7940. \see plottables, graphs
  7941. */
  7942. QList<QCPAbstractItem*> QCPAxis::items() const
  7943. {
  7944. QList<QCPAbstractItem*> result;
  7945. if (!mParentPlot) return result;
  7946. foreach (QCPAbstractItem *item, mParentPlot->mItems)
  7947. {
  7948. foreach (QCPItemPosition *position, item->positions())
  7949. {
  7950. if (position->keyAxis() == this || position->valueAxis() == this)
  7951. {
  7952. result.append(item);
  7953. break;
  7954. }
  7955. }
  7956. }
  7957. return result;
  7958. }
  7959. /*!
  7960. Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to
  7961. QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.)
  7962. */
  7963. QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side)
  7964. {
  7965. switch (side)
  7966. {
  7967. case QCP::msLeft: return atLeft;
  7968. case QCP::msRight: return atRight;
  7969. case QCP::msTop: return atTop;
  7970. case QCP::msBottom: return atBottom;
  7971. default: break;
  7972. }
  7973. qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << static_cast<int>(side);
  7974. return atLeft;
  7975. }
  7976. /*!
  7977. Returns the axis type that describes the opposite axis of an axis with the specified \a type.
  7978. */
  7979. QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type)
  7980. {
  7981. switch (type)
  7982. {
  7983. case atLeft: return atRight;
  7984. case atRight: return atLeft;
  7985. case atBottom: return atTop;
  7986. case atTop: return atBottom;
  7987. }
  7988. qDebug() << Q_FUNC_INFO << "invalid axis type";
  7989. return atLeft;
  7990. }
  7991. /* inherits documentation from base class */
  7992. void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  7993. {
  7994. Q_UNUSED(event)
  7995. SelectablePart part = details.value<SelectablePart>();
  7996. if (mSelectableParts.testFlag(part))
  7997. {
  7998. SelectableParts selBefore = mSelectedParts;
  7999. setSelectedParts(additive ? mSelectedParts^part : part);
  8000. if (selectionStateChanged)
  8001. *selectionStateChanged = mSelectedParts != selBefore;
  8002. }
  8003. }
  8004. /* inherits documentation from base class */
  8005. void QCPAxis::deselectEvent(bool *selectionStateChanged)
  8006. {
  8007. SelectableParts selBefore = mSelectedParts;
  8008. setSelectedParts(mSelectedParts & ~mSelectableParts);
  8009. if (selectionStateChanged)
  8010. *selectionStateChanged = mSelectedParts != selBefore;
  8011. }
  8012. /*! \internal
  8013. This mouse event reimplementation provides the functionality to let the user drag individual axes
  8014. exclusively, by startig the drag on top of the axis.
  8015. For the axis to accept this event and perform the single axis drag, the parent \ref QCPAxisRect
  8016. must be configured accordingly, i.e. it must allow range dragging in the orientation of this axis
  8017. (\ref QCPAxisRect::setRangeDrag) and this axis must be a draggable axis (\ref
  8018. QCPAxisRect::setRangeDragAxes)
  8019. \seebaseclassmethod
  8020. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  8021. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  8022. */
  8023. void QCPAxis::mousePressEvent(QMouseEvent *event, const QVariant &details)
  8024. {
  8025. Q_UNUSED(details)
  8026. if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag) ||
  8027. !mAxisRect->rangeDrag().testFlag(orientation()) ||
  8028. !mAxisRect->rangeDragAxes(orientation()).contains(this))
  8029. {
  8030. event->ignore();
  8031. return;
  8032. }
  8033. if (event->buttons() & Qt::LeftButton)
  8034. {
  8035. mDragging = true;
  8036. // initialize antialiasing backup in case we start dragging:
  8037. if (mParentPlot->noAntialiasingOnDrag())
  8038. {
  8039. mAADragBackup = mParentPlot->antialiasedElements();
  8040. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  8041. }
  8042. // Mouse range dragging interaction:
  8043. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  8044. mDragStartRange = mRange;
  8045. }
  8046. }
  8047. /*! \internal
  8048. This mouse event reimplementation provides the functionality to let the user drag individual axes
  8049. exclusively, by startig the drag on top of the axis.
  8050. \seebaseclassmethod
  8051. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  8052. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  8053. \see QCPAxis::mousePressEvent
  8054. */
  8055. void QCPAxis::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  8056. {
  8057. if (mDragging)
  8058. {
  8059. const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y();
  8060. const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y();
  8061. if (mScaleType == QCPAxis::stLinear)
  8062. {
  8063. const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel);
  8064. setRange(mDragStartRange.lower+diff, mDragStartRange.upper+diff);
  8065. } else if (mScaleType == QCPAxis::stLogarithmic)
  8066. {
  8067. const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel);
  8068. setRange(mDragStartRange.lower*diff, mDragStartRange.upper*diff);
  8069. }
  8070. if (mParentPlot->noAntialiasingOnDrag())
  8071. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  8072. mParentPlot->replot(QCustomPlot::rpQueuedReplot);
  8073. }
  8074. }
  8075. /*! \internal
  8076. This mouse event reimplementation provides the functionality to let the user drag individual axes
  8077. exclusively, by startig the drag on top of the axis.
  8078. \seebaseclassmethod
  8079. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  8080. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  8081. \see QCPAxis::mousePressEvent
  8082. */
  8083. void QCPAxis::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  8084. {
  8085. Q_UNUSED(event)
  8086. Q_UNUSED(startPos)
  8087. mDragging = false;
  8088. if (mParentPlot->noAntialiasingOnDrag())
  8089. {
  8090. mParentPlot->setAntialiasedElements(mAADragBackup);
  8091. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  8092. }
  8093. }
  8094. /*! \internal
  8095. This mouse event reimplementation provides the functionality to let the user zoom individual axes
  8096. exclusively, by performing the wheel event on top of the axis.
  8097. For the axis to accept this event and perform the single axis zoom, the parent \ref QCPAxisRect
  8098. must be configured accordingly, i.e. it must allow range zooming in the orientation of this axis
  8099. (\ref QCPAxisRect::setRangeZoom) and this axis must be a zoomable axis (\ref
  8100. QCPAxisRect::setRangeZoomAxes)
  8101. \seebaseclassmethod
  8102. \note The zooming of possibly multiple axes at once by performing the wheel event anywhere in the
  8103. axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::wheelEvent.
  8104. */
  8105. void QCPAxis::wheelEvent(QWheelEvent *event)
  8106. {
  8107. // Mouse range zooming interaction:
  8108. if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom) ||
  8109. !mAxisRect->rangeZoom().testFlag(orientation()) ||
  8110. !mAxisRect->rangeZoomAxes(orientation()).contains(this))
  8111. {
  8112. event->ignore();
  8113. return;
  8114. }
  8115. #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  8116. const double delta = event->delta();
  8117. #else
  8118. const double delta = event->angleDelta().y();
  8119. #endif
  8120. #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  8121. const QPointF pos = event->pos();
  8122. #else
  8123. const QPointF pos = event->position();
  8124. #endif
  8125. const double wheelSteps = delta/120.0; // a single step delta is +/-120 usually
  8126. const double factor = qPow(mAxisRect->rangeZoomFactor(orientation()), wheelSteps);
  8127. scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? pos.x() : pos.y()));
  8128. mParentPlot->replot();
  8129. }
  8130. /*! \internal
  8131. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  8132. before drawing axis lines.
  8133. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  8134. This function takes into account the local setting of the antialiasing flag as well as the
  8135. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  8136. QCustomPlot::setNotAntialiasedElements.
  8137. \seebaseclassmethod
  8138. \see setAntialiased
  8139. */
  8140. void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const
  8141. {
  8142. applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
  8143. }
  8144. /*! \internal
  8145. Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance.
  8146. \seebaseclassmethod
  8147. */
  8148. void QCPAxis::draw(QCPPainter *painter)
  8149. {
  8150. QVector<double> subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  8151. QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  8152. QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
  8153. tickPositions.reserve(mTickVector.size());
  8154. tickLabels.reserve(mTickVector.size());
  8155. subTickPositions.reserve(mSubTickVector.size());
  8156. if (mTicks)
  8157. {
  8158. for (int i=0; i<mTickVector.size(); ++i)
  8159. {
  8160. tickPositions.append(coordToPixel(mTickVector.at(i)));
  8161. if (mTickLabels)
  8162. tickLabels.append(mTickVectorLabels.at(i));
  8163. }
  8164. if (mSubTicks)
  8165. {
  8166. const int subTickCount = mSubTickVector.size();
  8167. for (int i=0; i<subTickCount; ++i)
  8168. subTickPositions.append(coordToPixel(mSubTickVector.at(i)));
  8169. }
  8170. }
  8171. // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to draw the axis.
  8172. // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
  8173. mAxisPainter->type = mAxisType;
  8174. mAxisPainter->basePen = getBasePen();
  8175. mAxisPainter->labelFont = getLabelFont();
  8176. mAxisPainter->labelColor = getLabelColor();
  8177. mAxisPainter->label = mLabel;
  8178. mAxisPainter->substituteExponent = mNumberBeautifulPowers;
  8179. mAxisPainter->tickPen = getTickPen();
  8180. mAxisPainter->subTickPen = getSubTickPen();
  8181. mAxisPainter->tickLabelFont = getTickLabelFont();
  8182. mAxisPainter->tickLabelColor = getTickLabelColor();
  8183. mAxisPainter->axisRect = mAxisRect->rect();
  8184. mAxisPainter->viewportRect = mParentPlot->viewport();
  8185. mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic;
  8186. mAxisPainter->reversedEndings = mRangeReversed;
  8187. mAxisPainter->tickPositions = tickPositions;
  8188. mAxisPainter->tickLabels = tickLabels;
  8189. mAxisPainter->subTickPositions = subTickPositions;
  8190. mAxisPainter->draw(painter);
  8191. }
  8192. /*! \internal
  8193. Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
  8194. QCPAxisTicker::generate on the currently installed ticker.
  8195. If a change in the label text/count is detected, the cached axis margin is invalidated to make
  8196. sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
  8197. */
  8198. void QCPAxis::setupTickVectors()
  8199. {
  8200. if (!mParentPlot) return;
  8201. if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
  8202. QVector<QString> oldLabels = mTickVectorLabels;
  8203. mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : nullptr, mTickLabels ? &mTickVectorLabels : nullptr);
  8204. mCachedMarginValid &= mTickVectorLabels == oldLabels; // if labels have changed, margin might have changed, too
  8205. }
  8206. /*! \internal
  8207. Returns the pen that is used to draw the axis base line. Depending on the selection state, this
  8208. is either mSelectedBasePen or mBasePen.
  8209. */
  8210. QPen QCPAxis::getBasePen() const
  8211. {
  8212. return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
  8213. }
  8214. /*! \internal
  8215. Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
  8216. is either mSelectedTickPen or mTickPen.
  8217. */
  8218. QPen QCPAxis::getTickPen() const
  8219. {
  8220. return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
  8221. }
  8222. /*! \internal
  8223. Returns the pen that is used to draw the subticks. Depending on the selection state, this
  8224. is either mSelectedSubTickPen or mSubTickPen.
  8225. */
  8226. QPen QCPAxis::getSubTickPen() const
  8227. {
  8228. return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
  8229. }
  8230. /*! \internal
  8231. Returns the font that is used to draw the tick labels. Depending on the selection state, this
  8232. is either mSelectedTickLabelFont or mTickLabelFont.
  8233. */
  8234. QFont QCPAxis::getTickLabelFont() const
  8235. {
  8236. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
  8237. }
  8238. /*! \internal
  8239. Returns the font that is used to draw the axis label. Depending on the selection state, this
  8240. is either mSelectedLabelFont or mLabelFont.
  8241. */
  8242. QFont QCPAxis::getLabelFont() const
  8243. {
  8244. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
  8245. }
  8246. /*! \internal
  8247. Returns the color that is used to draw the tick labels. Depending on the selection state, this
  8248. is either mSelectedTickLabelColor or mTickLabelColor.
  8249. */
  8250. QColor QCPAxis::getTickLabelColor() const
  8251. {
  8252. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
  8253. }
  8254. /*! \internal
  8255. Returns the color that is used to draw the axis label. Depending on the selection state, this
  8256. is either mSelectedLabelColor or mLabelColor.
  8257. */
  8258. QColor QCPAxis::getLabelColor() const
  8259. {
  8260. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
  8261. }
  8262. /*! \internal
  8263. Returns the appropriate outward margin for this axis. It is needed if \ref
  8264. QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref
  8265. atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom
  8266. margin and so forth. For the calculation, this function goes through similar steps as \ref draw,
  8267. so changing one function likely requires the modification of the other one as well.
  8268. The margin consists of the outward tick length, tick label padding, tick label size, label
  8269. padding, label size, and padding.
  8270. The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc.
  8271. unchanged are very fast.
  8272. */
  8273. int QCPAxis::calculateMargin()
  8274. {
  8275. if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis
  8276. return 0;
  8277. if (mCachedMarginValid)
  8278. return mCachedMargin;
  8279. // run through similar steps as QCPAxis::draw, and calculate margin needed to fit axis and its labels
  8280. int margin = 0;
  8281. QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  8282. QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
  8283. tickPositions.reserve(mTickVector.size());
  8284. tickLabels.reserve(mTickVector.size());
  8285. if (mTicks)
  8286. {
  8287. for (int i=0; i<mTickVector.size(); ++i)
  8288. {
  8289. tickPositions.append(coordToPixel(mTickVector.at(i)));
  8290. if (mTickLabels)
  8291. tickLabels.append(mTickVectorLabels.at(i));
  8292. }
  8293. }
  8294. // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size.
  8295. // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
  8296. mAxisPainter->type = mAxisType;
  8297. mAxisPainter->labelFont = getLabelFont();
  8298. mAxisPainter->label = mLabel;
  8299. mAxisPainter->tickLabelFont = mTickLabelFont;
  8300. mAxisPainter->axisRect = mAxisRect->rect();
  8301. mAxisPainter->viewportRect = mParentPlot->viewport();
  8302. mAxisPainter->tickPositions = tickPositions;
  8303. mAxisPainter->tickLabels = tickLabels;
  8304. margin += mAxisPainter->size();
  8305. margin += mPadding;
  8306. mCachedMargin = margin;
  8307. mCachedMarginValid = true;
  8308. return margin;
  8309. }
  8310. /* inherits documentation from base class */
  8311. QCP::Interaction QCPAxis::selectionCategory() const
  8312. {
  8313. return QCP::iSelectAxes;
  8314. }
  8315. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8316. //////////////////// QCPAxisPainterPrivate
  8317. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8318. /*! \class QCPAxisPainterPrivate
  8319. \internal
  8320. \brief (Private)
  8321. This is a private class and not part of the public QCustomPlot interface.
  8322. It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and
  8323. axis label. It also buffers the labels to reduce replot times. The parameters are configured by
  8324. directly accessing the public member variables.
  8325. */
  8326. /*!
  8327. Constructs a QCPAxisPainterPrivate instance. Make sure to not create a new instance on every
  8328. redraw, to utilize the caching mechanisms.
  8329. */
  8330. QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) :
  8331. type(QCPAxis::atLeft),
  8332. basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  8333. lowerEnding(QCPLineEnding::esNone),
  8334. upperEnding(QCPLineEnding::esNone),
  8335. labelPadding(0),
  8336. tickLabelPadding(0),
  8337. tickLabelRotation(0),
  8338. tickLabelSide(QCPAxis::lsOutside),
  8339. substituteExponent(true),
  8340. numberMultiplyCross(false),
  8341. tickLengthIn(5),
  8342. tickLengthOut(0),
  8343. subTickLengthIn(2),
  8344. subTickLengthOut(0),
  8345. tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  8346. subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  8347. offset(0),
  8348. abbreviateDecimalPowers(false),
  8349. reversedEndings(false),
  8350. mParentPlot(parentPlot),
  8351. mLabelCache(16) // cache at most 16 (tick) labels
  8352. {
  8353. }
  8354. QCPAxisPainterPrivate::~QCPAxisPainterPrivate()
  8355. {
  8356. }
  8357. /*! \internal
  8358. Draws the axis with the specified \a painter.
  8359. The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set
  8360. here, too.
  8361. */
  8362. void QCPAxisPainterPrivate::draw(QCPPainter *painter)
  8363. {
  8364. QByteArray newHash = generateLabelParameterHash();
  8365. if (newHash != mLabelParameterHash)
  8366. {
  8367. mLabelCache.clear();
  8368. mLabelParameterHash = newHash;
  8369. }
  8370. QPointF origin;
  8371. switch (type)
  8372. {
  8373. case QCPAxis::atLeft: origin = axisRect.bottomLeft() +QPointF(-offset, 0); break;
  8374. case QCPAxis::atRight: origin = axisRect.bottomRight()+QPointF(+offset, 0); break;
  8375. case QCPAxis::atTop: origin = axisRect.topLeft() +QPointF(0, -offset); break;
  8376. case QCPAxis::atBottom: origin = axisRect.bottomLeft() +QPointF(0, +offset); break;
  8377. }
  8378. double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes)
  8379. switch (type)
  8380. {
  8381. case QCPAxis::atTop: yCor = -1; break;
  8382. case QCPAxis::atRight: xCor = 1; break;
  8383. default: break;
  8384. }
  8385. int margin = 0;
  8386. // draw baseline:
  8387. QLineF baseLine;
  8388. painter->setPen(basePen);
  8389. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8390. baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(axisRect.width()+xCor, yCor));
  8391. else
  8392. baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -axisRect.height()+yCor));
  8393. if (reversedEndings)
  8394. baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later
  8395. painter->drawLine(baseLine);
  8396. // draw ticks:
  8397. if (!tickPositions.isEmpty())
  8398. {
  8399. painter->setPen(tickPen);
  8400. int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis)
  8401. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8402. {
  8403. foreach (double tickPos, tickPositions)
  8404. painter->drawLine(QLineF(tickPos+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPos+xCor, origin.y()+tickLengthIn*tickDir+yCor));
  8405. } else
  8406. {
  8407. foreach (double tickPos, tickPositions)
  8408. painter->drawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPos+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPos+yCor));
  8409. }
  8410. }
  8411. // draw subticks:
  8412. if (!subTickPositions.isEmpty())
  8413. {
  8414. painter->setPen(subTickPen);
  8415. // direction of ticks ("inward" is right for left axis and left for right axis)
  8416. int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1;
  8417. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8418. {
  8419. foreach (double subTickPos, subTickPositions)
  8420. painter->drawLine(QLineF(subTickPos+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPos+xCor, origin.y()+subTickLengthIn*tickDir+yCor));
  8421. } else
  8422. {
  8423. foreach (double subTickPos, subTickPositions)
  8424. painter->drawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPos+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPos+yCor));
  8425. }
  8426. }
  8427. margin += qMax(0, qMax(tickLengthOut, subTickLengthOut));
  8428. // draw axis base endings:
  8429. bool antialiasingBackup = painter->antialiasing();
  8430. painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't
  8431. painter->setBrush(QBrush(basePen.color()));
  8432. QCPVector2D baseLineVector(baseLine.dx(), baseLine.dy());
  8433. if (lowerEnding.style() != QCPLineEnding::esNone)
  8434. lowerEnding.draw(painter, QCPVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector);
  8435. if (upperEnding.style() != QCPLineEnding::esNone)
  8436. upperEnding.draw(painter, QCPVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector);
  8437. painter->setAntialiasing(antialiasingBackup);
  8438. // tick labels:
  8439. QRect oldClipRect;
  8440. if (tickLabelSide == QCPAxis::lsInside) // if using inside labels, clip them to the axis rect
  8441. {
  8442. oldClipRect = painter->clipRegion().boundingRect();
  8443. painter->setClipRect(axisRect);
  8444. }
  8445. QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label
  8446. if (!tickLabels.isEmpty())
  8447. {
  8448. if (tickLabelSide == QCPAxis::lsOutside)
  8449. margin += tickLabelPadding;
  8450. painter->setFont(tickLabelFont);
  8451. painter->setPen(QPen(tickLabelColor));
  8452. const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size());
  8453. int distanceToAxis = margin;
  8454. if (tickLabelSide == QCPAxis::lsInside)
  8455. distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding);
  8456. for (int i=0; i<maxLabelIndex; ++i)
  8457. placeTickLabel(painter, tickPositions.at(i), distanceToAxis, tickLabels.at(i), &tickLabelsSize);
  8458. if (tickLabelSide == QCPAxis::lsOutside)
  8459. margin += (QCPAxis::orientation(type) == Qt::Horizontal) ? tickLabelsSize.height() : tickLabelsSize.width();
  8460. }
  8461. if (tickLabelSide == QCPAxis::lsInside)
  8462. painter->setClipRect(oldClipRect);
  8463. // axis label:
  8464. QRect labelBounds;
  8465. if (!label.isEmpty())
  8466. {
  8467. margin += labelPadding;
  8468. painter->setFont(labelFont);
  8469. painter->setPen(QPen(labelColor));
  8470. labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label);
  8471. if (type == QCPAxis::atLeft)
  8472. {
  8473. QTransform oldTransform = painter->transform();
  8474. painter->translate((origin.x()-margin-labelBounds.height()), origin.y());
  8475. painter->rotate(-90);
  8476. painter->drawText(0, 0, int(axisRect.height()), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  8477. painter->setTransform(oldTransform);
  8478. }
  8479. else if (type == QCPAxis::atRight)
  8480. {
  8481. QTransform oldTransform = painter->transform();
  8482. painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-axisRect.height());
  8483. painter->rotate(90);
  8484. painter->drawText(0, 0, int(axisRect.height()), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  8485. painter->setTransform(oldTransform);
  8486. }
  8487. else if (type == QCPAxis::atTop)
  8488. painter->drawText(int(origin.x()), int(origin.y())-margin-labelBounds.height(), int(axisRect.width()), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  8489. else if (type == QCPAxis::atBottom)
  8490. painter->drawText(int(origin.x()), int(origin.y())+margin, int(axisRect.width()), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  8491. }
  8492. // set selection boxes:
  8493. int selectionTolerance = 0;
  8494. if (mParentPlot)
  8495. selectionTolerance = mParentPlot->selectionTolerance();
  8496. else
  8497. qDebug() << Q_FUNC_INFO << "mParentPlot is null";
  8498. int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance);
  8499. int selAxisInSize = selectionTolerance;
  8500. int selTickLabelSize;
  8501. int selTickLabelOffset;
  8502. if (tickLabelSide == QCPAxis::lsOutside)
  8503. {
  8504. selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
  8505. selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding;
  8506. } else
  8507. {
  8508. selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
  8509. selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding);
  8510. }
  8511. int selLabelSize = labelBounds.height();
  8512. int selLabelOffset = qMax(tickLengthOut, subTickLengthOut)+(!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside ? tickLabelPadding+selTickLabelSize : 0)+labelPadding;
  8513. if (type == QCPAxis::atLeft)
  8514. {
  8515. mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, axisRect.top(), origin.x()+selAxisInSize, axisRect.bottom());
  8516. mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, axisRect.top(), origin.x()-selTickLabelOffset, axisRect.bottom());
  8517. mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, axisRect.top(), origin.x()-selLabelOffset, axisRect.bottom());
  8518. } else if (type == QCPAxis::atRight)
  8519. {
  8520. mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, axisRect.top(), origin.x()+selAxisOutSize, axisRect.bottom());
  8521. mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, axisRect.top(), origin.x()+selTickLabelOffset, axisRect.bottom());
  8522. mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, axisRect.top(), origin.x()+selLabelOffset, axisRect.bottom());
  8523. } else if (type == QCPAxis::atTop)
  8524. {
  8525. mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisOutSize, axisRect.right(), origin.y()+selAxisInSize);
  8526. mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, axisRect.right(), origin.y()-selTickLabelOffset);
  8527. mLabelSelectionBox.setCoords(axisRect.left(), origin.y()-selLabelOffset-selLabelSize, axisRect.right(), origin.y()-selLabelOffset);
  8528. } else if (type == QCPAxis::atBottom)
  8529. {
  8530. mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisInSize, axisRect.right(), origin.y()+selAxisOutSize);
  8531. mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, axisRect.right(), origin.y()+selTickLabelOffset);
  8532. mLabelSelectionBox.setCoords(axisRect.left(), origin.y()+selLabelOffset+selLabelSize, axisRect.right(), origin.y()+selLabelOffset);
  8533. }
  8534. mAxisSelectionBox = mAxisSelectionBox.normalized();
  8535. mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized();
  8536. mLabelSelectionBox = mLabelSelectionBox.normalized();
  8537. // draw hitboxes for debug purposes:
  8538. //painter->setBrush(Qt::NoBrush);
  8539. //painter->drawRects(QVector<QRect>() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox);
  8540. }
  8541. /*! \internal
  8542. Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone
  8543. direction) needed to fit the axis.
  8544. */
  8545. int QCPAxisPainterPrivate::size()
  8546. {
  8547. int result = 0;
  8548. QByteArray newHash = generateLabelParameterHash();
  8549. if (newHash != mLabelParameterHash)
  8550. {
  8551. mLabelCache.clear();
  8552. mLabelParameterHash = newHash;
  8553. }
  8554. // get length of tick marks pointing outwards:
  8555. if (!tickPositions.isEmpty())
  8556. result += qMax(0, qMax(tickLengthOut, subTickLengthOut));
  8557. // calculate size of tick labels:
  8558. if (tickLabelSide == QCPAxis::lsOutside)
  8559. {
  8560. QSize tickLabelsSize(0, 0);
  8561. if (!tickLabels.isEmpty())
  8562. {
  8563. foreach (const QString &tickLabel, tickLabels)
  8564. getMaxTickLabelSize(tickLabelFont, tickLabel, &tickLabelsSize);
  8565. result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width();
  8566. result += tickLabelPadding;
  8567. }
  8568. }
  8569. // calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees):
  8570. if (!label.isEmpty())
  8571. {
  8572. QFontMetrics fontMetrics(labelFont);
  8573. QRect bounds;
  8574. bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label);
  8575. result += bounds.height() + labelPadding;
  8576. }
  8577. return result;
  8578. }
  8579. /*! \internal
  8580. Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This
  8581. method is called automatically in \ref draw, if any parameters have changed that invalidate the
  8582. cached labels, such as font, color, etc.
  8583. */
  8584. void QCPAxisPainterPrivate::clearCache()
  8585. {
  8586. mLabelCache.clear();
  8587. }
  8588. /*! \internal
  8589. Returns a hash that allows uniquely identifying whether the label parameters have changed such
  8590. that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the
  8591. return value of this method hasn't changed since the last redraw, the respective label parameters
  8592. haven't changed and cached labels may be used.
  8593. */
  8594. QByteArray QCPAxisPainterPrivate::generateLabelParameterHash() const
  8595. {
  8596. QByteArray result;
  8597. result.append(QByteArray::number(mParentPlot->bufferDevicePixelRatio()));
  8598. result.append(QByteArray::number(tickLabelRotation));
  8599. result.append(QByteArray::number(int(tickLabelSide)));
  8600. result.append(QByteArray::number(int(substituteExponent)));
  8601. result.append(QByteArray::number(int(numberMultiplyCross)));
  8602. result.append(tickLabelColor.name().toLatin1()+QByteArray::number(tickLabelColor.alpha(), 16));
  8603. result.append(tickLabelFont.toString().toLatin1());
  8604. return result;
  8605. }
  8606. /*! \internal
  8607. Draws a single tick label with the provided \a painter, utilizing the internal label cache to
  8608. significantly speed up drawing of labels that were drawn in previous calls. The tick label is
  8609. always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in
  8610. pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence
  8611. for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate),
  8612. at which the label should be drawn.
  8613. In order to later draw the axis label in a place that doesn't overlap with the tick labels, the
  8614. largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref
  8615. drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a
  8616. tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently
  8617. holds.
  8618. The label is drawn with the font and pen that are currently set on the \a painter. To draw
  8619. superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref
  8620. getTickLabelData).
  8621. */
  8622. void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize)
  8623. {
  8624. // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly!
  8625. if (text.isEmpty()) return;
  8626. QSize finalSize;
  8627. QPointF labelAnchor;
  8628. switch (type)
  8629. {
  8630. case QCPAxis::atLeft: labelAnchor = QPointF(axisRect.left()-distanceToAxis-offset, position); break;
  8631. case QCPAxis::atRight: labelAnchor = QPointF(axisRect.right()+distanceToAxis+offset, position); break;
  8632. case QCPAxis::atTop: labelAnchor = QPointF(position, axisRect.top()-distanceToAxis-offset); break;
  8633. case QCPAxis::atBottom: labelAnchor = QPointF(position, axisRect.bottom()+distanceToAxis+offset); break;
  8634. }
  8635. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled
  8636. {
  8637. CachedLabel *cachedLabel = mLabelCache.take(text); // attempt to get label from cache
  8638. if (!cachedLabel) // no cached label existed, create it
  8639. {
  8640. cachedLabel = new CachedLabel;
  8641. TickLabelData labelData = getTickLabelData(painter->font(), text);
  8642. cachedLabel->offset = getTickLabelDrawOffset(labelData)+labelData.rotatedTotalBounds.topLeft();
  8643. if (!qFuzzyCompare(1.0, mParentPlot->bufferDevicePixelRatio()))
  8644. {
  8645. cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()*mParentPlot->bufferDevicePixelRatio());
  8646. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  8647. # ifdef QCP_DEVICEPIXELRATIO_FLOAT
  8648. cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF());
  8649. # else
  8650. cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio());
  8651. # endif
  8652. #endif
  8653. } else
  8654. cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
  8655. cachedLabel->pixmap.fill(Qt::transparent);
  8656. QCPPainter cachePainter(&cachedLabel->pixmap);
  8657. cachePainter.setPen(painter->pen());
  8658. drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData);
  8659. }
  8660. // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
  8661. bool labelClippedByBorder = false;
  8662. if (tickLabelSide == QCPAxis::lsOutside)
  8663. {
  8664. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8665. labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width()/mParentPlot->bufferDevicePixelRatio() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left();
  8666. else
  8667. labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height()/mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top();
  8668. }
  8669. if (!labelClippedByBorder)
  8670. {
  8671. painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap);
  8672. finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
  8673. }
  8674. mLabelCache.insert(text, cachedLabel); // return label to cache or insert for the first time if newly created
  8675. } else // label caching disabled, draw text directly on surface:
  8676. {
  8677. TickLabelData labelData = getTickLabelData(painter->font(), text);
  8678. QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData);
  8679. // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
  8680. bool labelClippedByBorder = false;
  8681. if (tickLabelSide == QCPAxis::lsOutside)
  8682. {
  8683. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8684. labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left();
  8685. else
  8686. labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top();
  8687. }
  8688. if (!labelClippedByBorder)
  8689. {
  8690. drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData);
  8691. finalSize = labelData.rotatedTotalBounds.size();
  8692. }
  8693. }
  8694. // expand passed tickLabelsSize if current tick label is larger:
  8695. if (finalSize.width() > tickLabelsSize->width())
  8696. tickLabelsSize->setWidth(finalSize.width());
  8697. if (finalSize.height() > tickLabelsSize->height())
  8698. tickLabelsSize->setHeight(finalSize.height());
  8699. }
  8700. /*! \internal
  8701. This is a \ref placeTickLabel helper function.
  8702. Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a
  8703. y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to
  8704. directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when
  8705. QCP::phCacheLabels plotting hint is not set.
  8706. */
  8707. void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const
  8708. {
  8709. // backup painter settings that we're about to change:
  8710. QTransform oldTransform = painter->transform();
  8711. QFont oldFont = painter->font();
  8712. // transform painter to position/rotation:
  8713. painter->translate(x, y);
  8714. if (!qFuzzyIsNull(tickLabelRotation))
  8715. painter->rotate(tickLabelRotation);
  8716. // draw text:
  8717. if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used
  8718. {
  8719. painter->setFont(labelData.baseFont);
  8720. painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart);
  8721. if (!labelData.suffixPart.isEmpty())
  8722. painter->drawText(labelData.baseBounds.width()+1+labelData.expBounds.width(), 0, 0, 0, Qt::TextDontClip, labelData.suffixPart);
  8723. painter->setFont(labelData.expFont);
  8724. painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart);
  8725. } else
  8726. {
  8727. painter->setFont(labelData.baseFont);
  8728. painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart);
  8729. }
  8730. // reset painter settings to what it was before:
  8731. painter->setTransform(oldTransform);
  8732. painter->setFont(oldFont);
  8733. }
  8734. /*! \internal
  8735. This is a \ref placeTickLabel helper function.
  8736. Transforms the passed \a text and \a font to a tickLabelData structure that can then be further
  8737. processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and
  8738. exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes.
  8739. */
  8740. QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const
  8741. {
  8742. TickLabelData result;
  8743. // determine whether beautiful decimal powers should be used
  8744. bool useBeautifulPowers = false;
  8745. int ePos = -1; // first index of exponent part, text before that will be basePart, text until eLast will be expPart
  8746. int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart
  8747. if (substituteExponent)
  8748. {
  8749. ePos = text.indexOf(QLatin1Char('e'));
  8750. if (ePos > 0 && text.at(ePos-1).isDigit())
  8751. {
  8752. eLast = ePos;
  8753. while (eLast+1 < text.size() && (text.at(eLast+1) == QLatin1Char('+') || text.at(eLast+1) == QLatin1Char('-') || text.at(eLast+1).isDigit()))
  8754. ++eLast;
  8755. if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as beautifiable power
  8756. useBeautifulPowers = true;
  8757. }
  8758. }
  8759. // calculate text bounding rects and do string preparation for beautiful decimal powers:
  8760. result.baseFont = font;
  8761. if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line
  8762. 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
  8763. if (useBeautifulPowers)
  8764. {
  8765. // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent:
  8766. result.basePart = text.left(ePos);
  8767. result.suffixPart = text.mid(eLast+1); // also drawn normally but after exponent
  8768. // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base:
  8769. if (abbreviateDecimalPowers && result.basePart == QLatin1String("1"))
  8770. result.basePart = QLatin1String("10");
  8771. else
  8772. result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + QLatin1String("10");
  8773. result.expPart = text.mid(ePos+1, eLast-ePos);
  8774. // clip "+" and leading zeros off expPart:
  8775. while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e'
  8776. result.expPart.remove(1, 1);
  8777. if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+'))
  8778. result.expPart.remove(0, 1);
  8779. // prepare smaller font for exponent:
  8780. result.expFont = font;
  8781. if (result.expFont.pointSize() > 0)
  8782. result.expFont.setPointSize(int(result.expFont.pointSize()*0.75));
  8783. else
  8784. result.expFont.setPixelSize(int(result.expFont.pixelSize()*0.75));
  8785. // calculate bounding rects of base part(s), exponent part and total one:
  8786. result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart);
  8787. result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart);
  8788. if (!result.suffixPart.isEmpty())
  8789. result.suffixBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.suffixPart);
  8790. 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
  8791. } else // useBeautifulPowers == false
  8792. {
  8793. result.basePart = text;
  8794. result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart);
  8795. }
  8796. 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
  8797. // calculate possibly different bounding rect after rotation:
  8798. result.rotatedTotalBounds = result.totalBounds;
  8799. if (!qFuzzyIsNull(tickLabelRotation))
  8800. {
  8801. QTransform transform;
  8802. transform.rotate(tickLabelRotation);
  8803. result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds);
  8804. }
  8805. return result;
  8806. }
  8807. /*! \internal
  8808. This is a \ref placeTickLabel helper function.
  8809. Calculates the offset at which the top left corner of the specified tick label shall be drawn.
  8810. The offset is relative to a point right next to the tick the label belongs to.
  8811. This function is thus responsible for e.g. centering tick labels under ticks and positioning them
  8812. appropriately when they are rotated.
  8813. */
  8814. QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const
  8815. {
  8816. /*
  8817. calculate label offset from base point at tick (non-trivial, for best visual appearance): short
  8818. explanation for bottom axis: The anchor, i.e. the point in the label that is placed
  8819. horizontally under the corresponding tick is always on the label side that is closer to the
  8820. axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height
  8821. is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text
  8822. will be centered under the tick (i.e. displaced horizontally by half its height). At the same
  8823. time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick
  8824. labels.
  8825. */
  8826. bool doRotation = !qFuzzyIsNull(tickLabelRotation);
  8827. bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes.
  8828. double radians = tickLabelRotation/180.0*M_PI;
  8829. double x = 0;
  8830. double y = 0;
  8831. if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsInside)) // Anchor at right side of tick label
  8832. {
  8833. if (doRotation)
  8834. {
  8835. if (tickLabelRotation > 0)
  8836. {
  8837. x = -qCos(radians)*labelData.totalBounds.width();
  8838. y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0;
  8839. } else
  8840. {
  8841. x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height();
  8842. y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0;
  8843. }
  8844. } else
  8845. {
  8846. x = -labelData.totalBounds.width();
  8847. y = -labelData.totalBounds.height()/2.0;
  8848. }
  8849. } else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsInside)) // Anchor at left side of tick label
  8850. {
  8851. if (doRotation)
  8852. {
  8853. if (tickLabelRotation > 0)
  8854. {
  8855. x = +qSin(radians)*labelData.totalBounds.height();
  8856. y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0;
  8857. } else
  8858. {
  8859. x = 0;
  8860. y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0;
  8861. }
  8862. } else
  8863. {
  8864. x = 0;
  8865. y = -labelData.totalBounds.height()/2.0;
  8866. }
  8867. } else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsInside)) // Anchor at bottom side of tick label
  8868. {
  8869. if (doRotation)
  8870. {
  8871. if (tickLabelRotation > 0)
  8872. {
  8873. x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0;
  8874. y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height();
  8875. } else
  8876. {
  8877. x = -qSin(-radians)*labelData.totalBounds.height()/2.0;
  8878. y = -qCos(-radians)*labelData.totalBounds.height();
  8879. }
  8880. } else
  8881. {
  8882. x = -labelData.totalBounds.width()/2.0;
  8883. y = -labelData.totalBounds.height();
  8884. }
  8885. } else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsInside)) // Anchor at top side of tick label
  8886. {
  8887. if (doRotation)
  8888. {
  8889. if (tickLabelRotation > 0)
  8890. {
  8891. x = +qSin(radians)*labelData.totalBounds.height()/2.0;
  8892. y = 0;
  8893. } else
  8894. {
  8895. x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0;
  8896. y = +qSin(-radians)*labelData.totalBounds.width();
  8897. }
  8898. } else
  8899. {
  8900. x = -labelData.totalBounds.width()/2.0;
  8901. y = 0;
  8902. }
  8903. }
  8904. return {x, y};
  8905. }
  8906. /*! \internal
  8907. Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label
  8908. to be drawn, depending on number format etc. Since only the largest tick label is wanted for the
  8909. margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a
  8910. smaller width/height.
  8911. */
  8912. void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const
  8913. {
  8914. // note: this function must return the same tick label sizes as the placeTickLabel function.
  8915. QSize finalSize;
  8916. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label
  8917. {
  8918. const CachedLabel *cachedLabel = mLabelCache.object(text);
  8919. finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
  8920. } else // label caching disabled or no label with this text cached:
  8921. {
  8922. TickLabelData labelData = getTickLabelData(font, text);
  8923. finalSize = labelData.rotatedTotalBounds.size();
  8924. }
  8925. // expand passed tickLabelsSize if current tick label is larger:
  8926. if (finalSize.width() > tickLabelsSize->width())
  8927. tickLabelsSize->setWidth(finalSize.width());
  8928. if (finalSize.height() > tickLabelsSize->height())
  8929. tickLabelsSize->setHeight(finalSize.height());
  8930. }
  8931. /* end of 'src/axis/axis.cpp' */
  8932. /* including file 'src/scatterstyle.cpp' */
  8933. /* modified 2021-03-29T02:30:44, size 17466 */
  8934. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8935. //////////////////// QCPScatterStyle
  8936. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8937. /*! \class QCPScatterStyle
  8938. \brief Represents the visual appearance of scatter points
  8939. This class holds information about shape, color and size of scatter points. In plottables like
  8940. QCPGraph it is used to store how scatter points shall be drawn. For example, \ref
  8941. QCPGraph::setScatterStyle takes a QCPScatterStyle instance.
  8942. A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a
  8943. fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can
  8944. be controlled with \ref setSize.
  8945. \section QCPScatterStyle-defining Specifying a scatter style
  8946. You can set all these configurations either by calling the respective functions on an instance:
  8947. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-1
  8948. Or you can use one of the various constructors that take different parameter combinations, making
  8949. it easy to specify a scatter style in a single call, like so:
  8950. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-2
  8951. \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable
  8952. There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref
  8953. QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref
  8954. isPenDefined will return false. It leads to scatter points that inherit the pen from the
  8955. plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line
  8956. color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes
  8957. it very convenient to set up typical scatter settings:
  8958. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-shortcreation
  8959. Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works
  8960. because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly
  8961. into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size)
  8962. constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref
  8963. ScatterShape, where actually a QCPScatterStyle is expected.
  8964. \section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps
  8965. QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points.
  8966. For custom shapes, you can provide a QPainterPath with the desired shape to the \ref
  8967. setCustomPath function or call the constructor that takes a painter path. The scatter shape will
  8968. automatically be set to \ref ssCustom.
  8969. For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the
  8970. constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap.
  8971. Note that \ref setSize does not influence the appearance of the pixmap.
  8972. */
  8973. /* start documentation of inline functions */
  8974. /*! \fn bool QCPScatterStyle::isNone() const
  8975. Returns whether the scatter shape is \ref ssNone.
  8976. \see setShape
  8977. */
  8978. /*! \fn bool QCPScatterStyle::isPenDefined() const
  8979. Returns whether a pen has been defined for this scatter style.
  8980. The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those
  8981. are \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen
  8982. is undefined, the pen of the respective plottable will be used for drawing scatters.
  8983. If a pen was defined for this scatter style instance, and you now wish to undefine the pen, call
  8984. \ref undefinePen.
  8985. \see setPen
  8986. */
  8987. /* end documentation of inline functions */
  8988. /*!
  8989. Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined.
  8990. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
  8991. from the plottable that uses this scatter style.
  8992. */
  8993. QCPScatterStyle::QCPScatterStyle() :
  8994. mSize(6),
  8995. mShape(ssNone),
  8996. mPen(Qt::NoPen),
  8997. mBrush(Qt::NoBrush),
  8998. mPenDefined(false)
  8999. {
  9000. }
  9001. /*!
  9002. Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or
  9003. brush is defined.
  9004. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
  9005. from the plottable that uses this scatter style.
  9006. */
  9007. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) :
  9008. mSize(size),
  9009. mShape(shape),
  9010. mPen(Qt::NoPen),
  9011. mBrush(Qt::NoBrush),
  9012. mPenDefined(false)
  9013. {
  9014. }
  9015. /*!
  9016. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
  9017. and size to \a size. No brush is defined, i.e. the scatter point will not be filled.
  9018. */
  9019. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) :
  9020. mSize(size),
  9021. mShape(shape),
  9022. mPen(QPen(color)),
  9023. mBrush(Qt::NoBrush),
  9024. mPenDefined(true)
  9025. {
  9026. }
  9027. /*!
  9028. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
  9029. the brush color to \a fill (with a solid pattern), and size to \a size.
  9030. */
  9031. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) :
  9032. mSize(size),
  9033. mShape(shape),
  9034. mPen(QPen(color)),
  9035. mBrush(QBrush(fill)),
  9036. mPenDefined(true)
  9037. {
  9038. }
  9039. /*!
  9040. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the
  9041. brush to \a brush, and size to \a size.
  9042. \warning In some cases it might be tempting to directly use a pen style like <tt>Qt::NoPen</tt> as \a pen
  9043. and a color like <tt>Qt::blue</tt> as \a brush. Notice however, that the corresponding call\n
  9044. <tt>QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)</tt>\n
  9045. doesn't necessarily lead C++ to use this constructor in some cases, but might mistake
  9046. <tt>Qt::NoPen</tt> for a QColor and use the
  9047. \ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size)
  9048. constructor instead (which will lead to an unexpected look of the scatter points). To prevent
  9049. this, be more explicit with the parameter types. For example, use <tt>QBrush(Qt::blue)</tt>
  9050. instead of just <tt>Qt::blue</tt>, to clearly point out to the compiler that this constructor is
  9051. wanted.
  9052. */
  9053. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) :
  9054. mSize(size),
  9055. mShape(shape),
  9056. mPen(pen),
  9057. mBrush(brush),
  9058. mPenDefined(pen.style() != Qt::NoPen)
  9059. {
  9060. }
  9061. /*!
  9062. Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape
  9063. is set to \ref ssPixmap.
  9064. */
  9065. QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) :
  9066. mSize(5),
  9067. mShape(ssPixmap),
  9068. mPen(Qt::NoPen),
  9069. mBrush(Qt::NoBrush),
  9070. mPixmap(pixmap),
  9071. mPenDefined(false)
  9072. {
  9073. }
  9074. /*!
  9075. Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The
  9076. scatter shape is set to \ref ssCustom.
  9077. The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly
  9078. different meaning than for built-in scatter points: The custom path will be drawn scaled by a
  9079. factor of \a size/6.0. Since the default \a size is 6, the custom path will appear in its
  9080. original size by default. To for example double the size of the path, set \a size to 12.
  9081. */
  9082. QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) :
  9083. mSize(size),
  9084. mShape(ssCustom),
  9085. mPen(pen),
  9086. mBrush(brush),
  9087. mCustomPath(customPath),
  9088. mPenDefined(pen.style() != Qt::NoPen)
  9089. {
  9090. }
  9091. /*!
  9092. Copies the specified \a properties from the \a other scatter style to this scatter style.
  9093. */
  9094. void QCPScatterStyle::setFromOther(const QCPScatterStyle &other, ScatterProperties properties)
  9095. {
  9096. if (properties.testFlag(spPen))
  9097. {
  9098. setPen(other.pen());
  9099. if (!other.isPenDefined())
  9100. undefinePen();
  9101. }
  9102. if (properties.testFlag(spBrush))
  9103. setBrush(other.brush());
  9104. if (properties.testFlag(spSize))
  9105. setSize(other.size());
  9106. if (properties.testFlag(spShape))
  9107. {
  9108. setShape(other.shape());
  9109. if (other.shape() == ssPixmap)
  9110. setPixmap(other.pixmap());
  9111. else if (other.shape() == ssCustom)
  9112. setCustomPath(other.customPath());
  9113. }
  9114. }
  9115. /*!
  9116. Sets the size (pixel diameter) of the drawn scatter points to \a size.
  9117. \see setShape
  9118. */
  9119. void QCPScatterStyle::setSize(double size)
  9120. {
  9121. mSize = size;
  9122. }
  9123. /*!
  9124. Sets the shape to \a shape.
  9125. Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref
  9126. ssPixmap and \ref ssCustom, respectively.
  9127. \see setSize
  9128. */
  9129. void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape)
  9130. {
  9131. mShape = shape;
  9132. }
  9133. /*!
  9134. Sets the pen that will be used to draw scatter points to \a pen.
  9135. If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after
  9136. a call to this function, even if \a pen is <tt>Qt::NoPen</tt>. If you have defined a pen
  9137. previously by calling this function and now wish to undefine the pen, call \ref undefinePen.
  9138. \see setBrush
  9139. */
  9140. void QCPScatterStyle::setPen(const QPen &pen)
  9141. {
  9142. mPenDefined = true;
  9143. mPen = pen;
  9144. }
  9145. /*!
  9146. Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter
  9147. shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does.
  9148. \see setPen
  9149. */
  9150. void QCPScatterStyle::setBrush(const QBrush &brush)
  9151. {
  9152. mBrush = brush;
  9153. }
  9154. /*!
  9155. Sets the pixmap that will be drawn as scatter point to \a pixmap.
  9156. Note that \ref setSize does not influence the appearance of the pixmap.
  9157. The scatter shape is automatically set to \ref ssPixmap.
  9158. */
  9159. void QCPScatterStyle::setPixmap(const QPixmap &pixmap)
  9160. {
  9161. setShape(ssPixmap);
  9162. mPixmap = pixmap;
  9163. }
  9164. /*!
  9165. Sets the custom shape that will be drawn as scatter point to \a customPath.
  9166. The scatter shape is automatically set to \ref ssCustom.
  9167. */
  9168. void QCPScatterStyle::setCustomPath(const QPainterPath &customPath)
  9169. {
  9170. setShape(ssCustom);
  9171. mCustomPath = customPath;
  9172. }
  9173. /*!
  9174. Sets this scatter style to have an undefined pen (see \ref isPenDefined for what an undefined pen
  9175. implies).
  9176. A call to \ref setPen will define a pen.
  9177. */
  9178. void QCPScatterStyle::undefinePen()
  9179. {
  9180. mPenDefined = false;
  9181. }
  9182. /*!
  9183. Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an
  9184. undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead.
  9185. This function is used by plottables (or any class that wants to draw scatters) just before a
  9186. number of scatters with this style shall be drawn with the \a painter.
  9187. \see drawShape
  9188. */
  9189. void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const
  9190. {
  9191. painter->setPen(mPenDefined ? mPen : defaultPen);
  9192. painter->setBrush(mBrush);
  9193. }
  9194. /*!
  9195. Draws the scatter shape with \a painter at position \a pos.
  9196. This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be
  9197. called before scatter points are drawn with \ref drawShape.
  9198. \see applyTo
  9199. */
  9200. void QCPScatterStyle::drawShape(QCPPainter *painter, const QPointF &pos) const
  9201. {
  9202. drawShape(painter, pos.x(), pos.y());
  9203. }
  9204. /*! \overload
  9205. Draws the scatter shape with \a painter at position \a x and \a y.
  9206. */
  9207. void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const
  9208. {
  9209. double w = mSize/2.0;
  9210. switch (mShape)
  9211. {
  9212. case ssNone: break;
  9213. case ssDot:
  9214. {
  9215. painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y));
  9216. break;
  9217. }
  9218. case ssCross:
  9219. {
  9220. painter->drawLine(QLineF(x-w, y-w, x+w, y+w));
  9221. painter->drawLine(QLineF(x-w, y+w, x+w, y-w));
  9222. break;
  9223. }
  9224. case ssPlus:
  9225. {
  9226. painter->drawLine(QLineF(x-w, y, x+w, y));
  9227. painter->drawLine(QLineF( x, y+w, x, y-w));
  9228. break;
  9229. }
  9230. case ssCircle:
  9231. {
  9232. painter->drawEllipse(QPointF(x , y), w, w);
  9233. break;
  9234. }
  9235. case ssDisc:
  9236. {
  9237. QBrush b = painter->brush();
  9238. painter->setBrush(painter->pen().color());
  9239. painter->drawEllipse(QPointF(x , y), w, w);
  9240. painter->setBrush(b);
  9241. break;
  9242. }
  9243. case ssSquare:
  9244. {
  9245. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  9246. break;
  9247. }
  9248. case ssDiamond:
  9249. {
  9250. QPointF lineArray[4] = {QPointF(x-w, y),
  9251. QPointF( x, y-w),
  9252. QPointF(x+w, y),
  9253. QPointF( x, y+w)};
  9254. painter->drawPolygon(lineArray, 4);
  9255. break;
  9256. }
  9257. case ssStar:
  9258. {
  9259. painter->drawLine(QLineF(x-w, y, x+w, y));
  9260. painter->drawLine(QLineF( x, y+w, x, y-w));
  9261. painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707));
  9262. painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707));
  9263. break;
  9264. }
  9265. case ssTriangle:
  9266. {
  9267. QPointF lineArray[3] = {QPointF(x-w, y+0.755*w),
  9268. QPointF(x+w, y+0.755*w),
  9269. QPointF( x, y-0.977*w)};
  9270. painter->drawPolygon(lineArray, 3);
  9271. break;
  9272. }
  9273. case ssTriangleInverted:
  9274. {
  9275. QPointF lineArray[3] = {QPointF(x-w, y-0.755*w),
  9276. QPointF(x+w, y-0.755*w),
  9277. QPointF( x, y+0.977*w)};
  9278. painter->drawPolygon(lineArray, 3);
  9279. break;
  9280. }
  9281. case ssCrossSquare:
  9282. {
  9283. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  9284. painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95));
  9285. painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w));
  9286. break;
  9287. }
  9288. case ssPlusSquare:
  9289. {
  9290. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  9291. painter->drawLine(QLineF(x-w, y, x+w*0.95, y));
  9292. painter->drawLine(QLineF( x, y+w, x, y-w));
  9293. break;
  9294. }
  9295. case ssCrossCircle:
  9296. {
  9297. painter->drawEllipse(QPointF(x, y), w, w);
  9298. painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670));
  9299. painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707));
  9300. break;
  9301. }
  9302. case ssPlusCircle:
  9303. {
  9304. painter->drawEllipse(QPointF(x, y), w, w);
  9305. painter->drawLine(QLineF(x-w, y, x+w, y));
  9306. painter->drawLine(QLineF( x, y+w, x, y-w));
  9307. break;
  9308. }
  9309. case ssPeace:
  9310. {
  9311. painter->drawEllipse(QPointF(x, y), w, w);
  9312. painter->drawLine(QLineF(x, y-w, x, y+w));
  9313. painter->drawLine(QLineF(x, y, x-w*0.707, y+w*0.707));
  9314. painter->drawLine(QLineF(x, y, x+w*0.707, y+w*0.707));
  9315. break;
  9316. }
  9317. case ssPixmap:
  9318. {
  9319. const double widthHalf = mPixmap.width()*0.5;
  9320. const double heightHalf = mPixmap.height()*0.5;
  9321. #if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
  9322. const QRectF clipRect = painter->clipRegion().boundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf);
  9323. #else
  9324. const QRectF clipRect = painter->clipBoundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf);
  9325. #endif
  9326. if (clipRect.contains(x, y))
  9327. painter->drawPixmap(x-widthHalf, y-heightHalf, mPixmap);
  9328. break;
  9329. }
  9330. case ssCustom:
  9331. {
  9332. QTransform oldTransform = painter->transform();
  9333. painter->translate(x, y);
  9334. painter->scale(mSize/6.0, mSize/6.0);
  9335. painter->drawPath(mCustomPath);
  9336. painter->setTransform(oldTransform);
  9337. break;
  9338. }
  9339. }
  9340. }
  9341. /* end of 'src/scatterstyle.cpp' */
  9342. /* including file 'src/plottable.cpp' */
  9343. /* modified 2021-03-29T02:30:44, size 38818 */
  9344. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9345. //////////////////// QCPSelectionDecorator
  9346. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9347. /*! \class QCPSelectionDecorator
  9348. \brief Controls how a plottable's data selection is drawn
  9349. Each \ref QCPAbstractPlottable instance has one \ref QCPSelectionDecorator (accessible via \ref
  9350. QCPAbstractPlottable::selectionDecorator) and uses it when drawing selected segments of its data.
  9351. The selection decorator controls both pen (\ref setPen) and brush (\ref setBrush), as well as the
  9352. scatter style (\ref setScatterStyle) if the plottable draws scatters. Since a \ref
  9353. QCPScatterStyle is itself composed of different properties such as color shape and size, the
  9354. decorator allows specifying exactly which of those properties shall be used for the selected data
  9355. point, via \ref setUsedScatterProperties.
  9356. A \ref QCPSelectionDecorator subclass instance can be passed to a plottable via \ref
  9357. QCPAbstractPlottable::setSelectionDecorator, allowing greater customizability of the appearance
  9358. of selected segments.
  9359. Use \ref copyFrom to easily transfer the settings of one decorator to another one. This is
  9360. especially useful since plottables take ownership of the passed selection decorator, and thus the
  9361. same decorator instance can not be passed to multiple plottables.
  9362. Selection decorators can also themselves perform drawing operations by reimplementing \ref
  9363. drawDecoration, which is called by the plottable's draw method. The base class \ref
  9364. QCPSelectionDecorator does not make use of this however. For example, \ref
  9365. QCPSelectionDecoratorBracket draws brackets around selected data segments.
  9366. */
  9367. /*!
  9368. Creates a new QCPSelectionDecorator instance with default values
  9369. */
  9370. QCPSelectionDecorator::QCPSelectionDecorator() :
  9371. mPen(QColor(80, 80, 255), 2.5),
  9372. mBrush(Qt::NoBrush),
  9373. mUsedScatterProperties(QCPScatterStyle::spNone),
  9374. mPlottable(nullptr)
  9375. {
  9376. }
  9377. QCPSelectionDecorator::~QCPSelectionDecorator()
  9378. {
  9379. }
  9380. /*!
  9381. Sets the pen that will be used by the parent plottable to draw selected data segments.
  9382. */
  9383. void QCPSelectionDecorator::setPen(const QPen &pen)
  9384. {
  9385. mPen = pen;
  9386. }
  9387. /*!
  9388. Sets the brush that will be used by the parent plottable to draw selected data segments.
  9389. */
  9390. void QCPSelectionDecorator::setBrush(const QBrush &brush)
  9391. {
  9392. mBrush = brush;
  9393. }
  9394. /*!
  9395. Sets the scatter style that will be used by the parent plottable to draw scatters in selected
  9396. data segments.
  9397. \a usedProperties specifies which parts of the passed \a scatterStyle will be used by the
  9398. plottable. The used properties can also be changed via \ref setUsedScatterProperties.
  9399. */
  9400. void QCPSelectionDecorator::setScatterStyle(const QCPScatterStyle &scatterStyle, QCPScatterStyle::ScatterProperties usedProperties)
  9401. {
  9402. mScatterStyle = scatterStyle;
  9403. setUsedScatterProperties(usedProperties);
  9404. }
  9405. /*!
  9406. Use this method to define which properties of the scatter style (set via \ref setScatterStyle)
  9407. will be used for selected data segments. All properties of the scatter style that are not
  9408. specified in \a properties will remain as specified in the plottable's original scatter style.
  9409. \see QCPScatterStyle::ScatterProperty
  9410. */
  9411. void QCPSelectionDecorator::setUsedScatterProperties(const QCPScatterStyle::ScatterProperties &properties)
  9412. {
  9413. mUsedScatterProperties = properties;
  9414. }
  9415. /*!
  9416. Sets the pen of \a painter to the pen of this selection decorator.
  9417. \see applyBrush, getFinalScatterStyle
  9418. */
  9419. void QCPSelectionDecorator::applyPen(QCPPainter *painter) const
  9420. {
  9421. painter->setPen(mPen);
  9422. }
  9423. /*!
  9424. Sets the brush of \a painter to the brush of this selection decorator.
  9425. \see applyPen, getFinalScatterStyle
  9426. */
  9427. void QCPSelectionDecorator::applyBrush(QCPPainter *painter) const
  9428. {
  9429. painter->setBrush(mBrush);
  9430. }
  9431. /*!
  9432. Returns the scatter style that the parent plottable shall use for selected scatter points. The
  9433. plottable's original (unselected) scatter style must be passed as \a unselectedStyle. Depending
  9434. on the setting of \ref setUsedScatterProperties, the returned scatter style is a mixture of this
  9435. selecion decorator's scatter style (\ref setScatterStyle), and \a unselectedStyle.
  9436. \see applyPen, applyBrush, setScatterStyle
  9437. */
  9438. QCPScatterStyle QCPSelectionDecorator::getFinalScatterStyle(const QCPScatterStyle &unselectedStyle) const
  9439. {
  9440. QCPScatterStyle result(unselectedStyle);
  9441. result.setFromOther(mScatterStyle, mUsedScatterProperties);
  9442. // if style shall inherit pen from plottable (has no own pen defined), give it the selected
  9443. // plottable pen explicitly, so it doesn't use the unselected plottable pen when used in the
  9444. // plottable:
  9445. if (!result.isPenDefined())
  9446. result.setPen(mPen);
  9447. return result;
  9448. }
  9449. /*!
  9450. Copies all properties (e.g. color, fill, scatter style) of the \a other selection decorator to
  9451. this selection decorator.
  9452. */
  9453. void QCPSelectionDecorator::copyFrom(const QCPSelectionDecorator *other)
  9454. {
  9455. setPen(other->pen());
  9456. setBrush(other->brush());
  9457. setScatterStyle(other->scatterStyle(), other->usedScatterProperties());
  9458. }
  9459. /*!
  9460. This method is called by all plottables' draw methods to allow custom selection decorations to be
  9461. drawn. Use the passed \a painter to perform the drawing operations. \a selection carries the data
  9462. selection for which the decoration shall be drawn.
  9463. The default base class implementation of \ref QCPSelectionDecorator has no special decoration, so
  9464. this method does nothing.
  9465. */
  9466. void QCPSelectionDecorator::drawDecoration(QCPPainter *painter, QCPDataSelection selection)
  9467. {
  9468. Q_UNUSED(painter)
  9469. Q_UNUSED(selection)
  9470. }
  9471. /*! \internal
  9472. This method is called as soon as a selection decorator is associated with a plottable, by a call
  9473. to \ref QCPAbstractPlottable::setSelectionDecorator. This way the selection decorator can obtain a pointer to the plottable that uses it (e.g. to access
  9474. data points via the \ref QCPAbstractPlottable::interface1D interface).
  9475. If the selection decorator was already added to a different plottable before, this method aborts
  9476. the registration and returns false.
  9477. */
  9478. bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottable)
  9479. {
  9480. if (!mPlottable)
  9481. {
  9482. mPlottable = plottable;
  9483. return true;
  9484. } else
  9485. {
  9486. qDebug() << Q_FUNC_INFO << "This selection decorator is already registered with plottable:" << reinterpret_cast<quintptr>(mPlottable);
  9487. return false;
  9488. }
  9489. }
  9490. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9491. //////////////////// QCPAbstractPlottable
  9492. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9493. /*! \class QCPAbstractPlottable
  9494. \brief The abstract base class for all data representing objects in a plot.
  9495. It defines a very basic interface like name, pen, brush, visibility etc. Since this class is
  9496. abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to
  9497. create new ways of displaying data (see "Creating own plottables" below). Plottables that display
  9498. one-dimensional data (i.e. data points have a single key dimension and one or multiple values at
  9499. each key) are based off of the template subclass \ref QCPAbstractPlottable1D, see details
  9500. there.
  9501. All further specifics are in the subclasses, for example:
  9502. \li A normal graph with possibly a line and/or scatter points \ref QCPGraph
  9503. (typically created with \ref QCustomPlot::addGraph)
  9504. \li A parametric curve: \ref QCPCurve
  9505. \li A bar chart: \ref QCPBars
  9506. \li A statistical box plot: \ref QCPStatisticalBox
  9507. \li A color encoded two-dimensional map: \ref QCPColorMap
  9508. \li An OHLC/Candlestick chart: \ref QCPFinancial
  9509. \section plottables-subclassing Creating own plottables
  9510. Subclassing directly from QCPAbstractPlottable is only recommended if you wish to display
  9511. two-dimensional data like \ref QCPColorMap, i.e. two logical key dimensions and one (or more)
  9512. data dimensions. If you want to display data with only one logical key dimension, you should
  9513. rather derive from \ref QCPAbstractPlottable1D.
  9514. If subclassing QCPAbstractPlottable directly, these are the pure virtual functions you must
  9515. implement:
  9516. \li \ref selectTest
  9517. \li \ref draw
  9518. \li \ref drawLegendIcon
  9519. \li \ref getKeyRange
  9520. \li \ref getValueRange
  9521. See the documentation of those functions for what they need to do.
  9522. For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot
  9523. coordinates to pixel coordinates. This function is quite convenient, because it takes the
  9524. orientation of the key and value axes into account for you (x and y are swapped when the key axis
  9525. is vertical and the value axis horizontal). If you are worried about performance (i.e. you need
  9526. to translate many points in a loop like QCPGraph), you can directly use \ref
  9527. QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis
  9528. yourself.
  9529. Here are some important members you inherit from QCPAbstractPlottable:
  9530. <table>
  9531. <tr>
  9532. <td>QCustomPlot *\b mParentPlot</td>
  9533. <td>A pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.</td>
  9534. </tr><tr>
  9535. <td>QString \b mName</td>
  9536. <td>The name of the plottable.</td>
  9537. </tr><tr>
  9538. <td>QPen \b mPen</td>
  9539. <td>The generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable
  9540. (e.g QCPGraph uses this pen for its graph lines and scatters)</td>
  9541. </tr><tr>
  9542. <td>QBrush \b mBrush</td>
  9543. <td>The generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable
  9544. (e.g. QCPGraph uses this brush to control filling under the graph)</td>
  9545. </tr><tr>
  9546. <td>QPointer<\ref QCPAxis> \b mKeyAxis, \b mValueAxis</td>
  9547. <td>The key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates
  9548. 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
  9549. the axes is null, don't draw the plottable.</td>
  9550. </tr><tr>
  9551. <td>\ref QCPSelectionDecorator \b mSelectionDecorator</td>
  9552. <td>The currently set selection decorator which specifies how selected data of the plottable shall be drawn and decorated.
  9553. When drawing your data, you must consult this decorator for the appropriate pen/brush before drawing unselected/selected data segments.
  9554. Finally, you should call its \ref QCPSelectionDecorator::drawDecoration method at the end of your \ref draw implementation.</td>
  9555. </tr><tr>
  9556. <td>\ref QCP::SelectionType \b mSelectable</td>
  9557. <td>In which composition, if at all, this plottable's data may be selected. Enforcing this setting on the data selection is done
  9558. by QCPAbstractPlottable automatically.</td>
  9559. </tr><tr>
  9560. <td>\ref QCPDataSelection \b mSelection</td>
  9561. <td>Holds the current selection state of the plottable's data, i.e. the selected data ranges (\ref QCPDataRange).</td>
  9562. </tr>
  9563. </table>
  9564. */
  9565. /* start of documentation of inline functions */
  9566. /*! \fn QCPSelectionDecorator *QCPAbstractPlottable::selectionDecorator() const
  9567. Provides access to the selection decorator of this plottable. The selection decorator controls
  9568. how selected data ranges are drawn (e.g. their pen color and fill), see \ref
  9569. QCPSelectionDecorator for details.
  9570. If you wish to use an own \ref QCPSelectionDecorator subclass, pass an instance of it to \ref
  9571. setSelectionDecorator.
  9572. */
  9573. /*! \fn bool QCPAbstractPlottable::selected() const
  9574. Returns true if there are any data points of the plottable currently selected. Use \ref selection
  9575. to retrieve the current \ref QCPDataSelection.
  9576. */
  9577. /*! \fn QCPDataSelection QCPAbstractPlottable::selection() const
  9578. Returns a \ref QCPDataSelection encompassing all the data points that are currently selected on
  9579. this plottable.
  9580. \see selected, setSelection, setSelectable
  9581. */
  9582. /*! \fn virtual QCPPlottableInterface1D *QCPAbstractPlottable::interface1D()
  9583. If this plottable is a one-dimensional plottable, i.e. it implements the \ref
  9584. QCPPlottableInterface1D, returns the \a this pointer with that type. Otherwise (e.g. in the case
  9585. of a \ref QCPColorMap) returns zero.
  9586. You can use this method to gain read access to data coordinates while holding a pointer to the
  9587. abstract base class only.
  9588. */
  9589. /* end of documentation of inline functions */
  9590. /* start of documentation of pure virtual functions */
  9591. /*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0
  9592. \internal
  9593. called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation
  9594. of this plottable inside \a rect, next to the plottable name.
  9595. The passed \a painter has its cliprect set to \a rect, so painting outside of \a rect won't
  9596. appear outside the legend icon border.
  9597. */
  9598. /*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const = 0
  9599. Returns the coordinate range that all data in this plottable span in the key axis dimension. For
  9600. logarithmic plots, one can set \a inSignDomain to either \ref QCP::sdNegative or \ref
  9601. QCP::sdPositive in order to restrict the returned range to that sign domain. E.g. when only
  9602. negative range is wanted, set \a inSignDomain to \ref QCP::sdNegative and all positive points
  9603. will be ignored for range calculation. For no restriction, just set \a inSignDomain to \ref
  9604. QCP::sdBoth (default). \a foundRange is an output parameter that indicates whether a range could
  9605. be found or not. If this is false, you shouldn't use the returned range (e.g. no points in data).
  9606. Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
  9607. this function may have size zero (e.g. when there is only one data point). In this case \a
  9608. foundRange would return true, but the returned range is not a valid range in terms of \ref
  9609. QCPRange::validRange.
  9610. \see rescaleAxes, getValueRange
  9611. */
  9612. /*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const = 0
  9613. Returns the coordinate range that the data points in the specified key range (\a inKeyRange) span
  9614. in the value axis dimension. For logarithmic plots, one can set \a inSignDomain to either \ref
  9615. QCP::sdNegative or \ref QCP::sdPositive in order to restrict the returned range to that sign
  9616. domain. E.g. when only negative range is wanted, set \a inSignDomain to \ref QCP::sdNegative and
  9617. all positive points will be ignored for range calculation. For no restriction, just set \a
  9618. inSignDomain to \ref QCP::sdBoth (default). \a foundRange is an output parameter that indicates
  9619. whether a range could be found or not. If this is false, you shouldn't use the returned range
  9620. (e.g. no points in data).
  9621. If \a inKeyRange has both lower and upper bound set to zero (is equal to <tt>QCPRange()</tt>),
  9622. all data points are considered, without any restriction on the keys.
  9623. Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
  9624. this function may have size zero (e.g. when there is only one data point). In this case \a
  9625. foundRange would return true, but the returned range is not a valid range in terms of \ref
  9626. QCPRange::validRange.
  9627. \see rescaleAxes, getKeyRange
  9628. */
  9629. /* end of documentation of pure virtual functions */
  9630. /* start of documentation of signals */
  9631. /*! \fn void QCPAbstractPlottable::selectionChanged(bool selected)
  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 selected indicates whether
  9634. there are any points selected or not.
  9635. \see selectionChanged(const QCPDataSelection &selection)
  9636. */
  9637. /*! \fn void QCPAbstractPlottable::selectionChanged(const QCPDataSelection &selection)
  9638. This signal is emitted when the selection state of this plottable has changed, either by user
  9639. interaction or by a direct call to \ref setSelection. The parameter \a selection holds the
  9640. currently selected data ranges.
  9641. \see selectionChanged(bool selected)
  9642. */
  9643. /*! \fn void QCPAbstractPlottable::selectableChanged(QCP::SelectionType selectable);
  9644. This signal is emitted when the selectability of this plottable has changed.
  9645. \see setSelectable
  9646. */
  9647. /* end of documentation of signals */
  9648. /*!
  9649. Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as
  9650. its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance
  9651. and have perpendicular orientations. If either of these restrictions is violated, a corresponding
  9652. message is printed to the debug output (qDebug), the construction is not aborted, though.
  9653. Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables,
  9654. it can't be directly instantiated.
  9655. You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead.
  9656. */
  9657. QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  9658. QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect()),
  9659. mName(),
  9660. mAntialiasedFill(true),
  9661. mAntialiasedScatters(true),
  9662. mPen(Qt::black),
  9663. mBrush(Qt::NoBrush),
  9664. mKeyAxis(keyAxis),
  9665. mValueAxis(valueAxis),
  9666. mSelectable(QCP::stWhole),
  9667. mSelectionDecorator(nullptr)
  9668. {
  9669. if (keyAxis->parentPlot() != valueAxis->parentPlot())
  9670. qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
  9671. if (keyAxis->orientation() == valueAxis->orientation())
  9672. qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other.";
  9673. mParentPlot->registerPlottable(this);
  9674. setSelectionDecorator(new QCPSelectionDecorator);
  9675. }
  9676. QCPAbstractPlottable::~QCPAbstractPlottable()
  9677. {
  9678. if (mSelectionDecorator)
  9679. {
  9680. delete mSelectionDecorator;
  9681. mSelectionDecorator = nullptr;
  9682. }
  9683. }
  9684. /*!
  9685. The name is the textual representation of this plottable as it is displayed in the legend
  9686. (\ref QCPLegend). It may contain any UTF-8 characters, including newlines.
  9687. */
  9688. void QCPAbstractPlottable::setName(const QString &name)
  9689. {
  9690. mName = name;
  9691. }
  9692. /*!
  9693. Sets whether fills of this plottable are drawn antialiased or not.
  9694. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  9695. QCustomPlot::setNotAntialiasedElements.
  9696. */
  9697. void QCPAbstractPlottable::setAntialiasedFill(bool enabled)
  9698. {
  9699. mAntialiasedFill = enabled;
  9700. }
  9701. /*!
  9702. Sets whether the scatter symbols of this plottable are drawn antialiased or not.
  9703. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  9704. QCustomPlot::setNotAntialiasedElements.
  9705. */
  9706. void QCPAbstractPlottable::setAntialiasedScatters(bool enabled)
  9707. {
  9708. mAntialiasedScatters = enabled;
  9709. }
  9710. /*!
  9711. The pen is used to draw basic lines that make up the plottable representation in the
  9712. plot.
  9713. For example, the \ref QCPGraph subclass draws its graph lines with this pen.
  9714. \see setBrush
  9715. */
  9716. void QCPAbstractPlottable::setPen(const QPen &pen)
  9717. {
  9718. mPen = pen;
  9719. }
  9720. /*!
  9721. The brush is used to draw basic fills of the plottable representation in the
  9722. plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
  9723. For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when
  9724. it's not set to Qt::NoBrush.
  9725. \see setPen
  9726. */
  9727. void QCPAbstractPlottable::setBrush(const QBrush &brush)
  9728. {
  9729. mBrush = brush;
  9730. }
  9731. /*!
  9732. The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
  9733. to the plottable's value axis. This function performs no checks to make sure this is the case.
  9734. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
  9735. y-axis (QCustomPlot::yAxis) as value axis.
  9736. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  9737. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  9738. \see setValueAxis
  9739. */
  9740. void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis)
  9741. {
  9742. mKeyAxis = axis;
  9743. }
  9744. /*!
  9745. The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is
  9746. orthogonal to the plottable's key axis. This function performs no checks to make sure this is the
  9747. case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and
  9748. the y-axis (QCustomPlot::yAxis) as value axis.
  9749. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  9750. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  9751. \see setKeyAxis
  9752. */
  9753. void QCPAbstractPlottable::setValueAxis(QCPAxis *axis)
  9754. {
  9755. mValueAxis = axis;
  9756. }
  9757. /*!
  9758. Sets which data ranges of this plottable are selected. Selected data ranges are drawn differently
  9759. (e.g. color) in the plot. This can be controlled via the selection decorator (see \ref
  9760. selectionDecorator).
  9761. The entire selection mechanism for plottables is handled automatically when \ref
  9762. QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
  9763. you wish to change the selection state programmatically.
  9764. Using \ref setSelectable you can further specify for each plottable whether and to which
  9765. granularity it is selectable. If \a selection is not compatible with the current \ref
  9766. QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted
  9767. accordingly (see \ref QCPDataSelection::enforceType).
  9768. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  9769. \see setSelectable, selectTest
  9770. */
  9771. void QCPAbstractPlottable::setSelection(QCPDataSelection selection)
  9772. {
  9773. selection.enforceType(mSelectable);
  9774. if (mSelection != selection)
  9775. {
  9776. mSelection = selection;
  9777. emit selectionChanged(selected());
  9778. emit selectionChanged(mSelection);
  9779. }
  9780. }
  9781. /*!
  9782. Use this method to set an own QCPSelectionDecorator (subclass) instance. This allows you to
  9783. customize the visual representation of selected data ranges further than by using the default
  9784. QCPSelectionDecorator.
  9785. The plottable takes ownership of the \a decorator.
  9786. The currently set decorator can be accessed via \ref selectionDecorator.
  9787. */
  9788. void QCPAbstractPlottable::setSelectionDecorator(QCPSelectionDecorator *decorator)
  9789. {
  9790. if (decorator)
  9791. {
  9792. if (decorator->registerWithPlottable(this))
  9793. {
  9794. delete mSelectionDecorator; // delete old decorator if necessary
  9795. mSelectionDecorator = decorator;
  9796. }
  9797. } else if (mSelectionDecorator) // just clear decorator
  9798. {
  9799. delete mSelectionDecorator;
  9800. mSelectionDecorator = nullptr;
  9801. }
  9802. }
  9803. /*!
  9804. Sets whether and to which granularity this plottable can be selected.
  9805. A selection can happen by clicking on the QCustomPlot surface (When \ref
  9806. QCustomPlot::setInteractions contains \ref QCP::iSelectPlottables), by dragging a selection rect
  9807. (When \ref QCustomPlot::setSelectionRectMode is \ref QCP::srmSelect), or programmatically by
  9808. calling \ref setSelection.
  9809. \see setSelection, QCP::SelectionType
  9810. */
  9811. void QCPAbstractPlottable::setSelectable(QCP::SelectionType selectable)
  9812. {
  9813. if (mSelectable != selectable)
  9814. {
  9815. mSelectable = selectable;
  9816. QCPDataSelection oldSelection = mSelection;
  9817. mSelection.enforceType(mSelectable);
  9818. emit selectableChanged(mSelectable);
  9819. if (mSelection != oldSelection)
  9820. {
  9821. emit selectionChanged(selected());
  9822. emit selectionChanged(mSelection);
  9823. }
  9824. }
  9825. }
  9826. /*!
  9827. Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface,
  9828. taking the orientations of the axes associated with this plottable into account (e.g. whether key
  9829. represents x or y).
  9830. \a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y.
  9831. \see pixelsToCoords, QCPAxis::coordToPixel
  9832. */
  9833. void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const
  9834. {
  9835. QCPAxis *keyAxis = mKeyAxis.data();
  9836. QCPAxis *valueAxis = mValueAxis.data();
  9837. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  9838. if (keyAxis->orientation() == Qt::Horizontal)
  9839. {
  9840. x = keyAxis->coordToPixel(key);
  9841. y = valueAxis->coordToPixel(value);
  9842. } else
  9843. {
  9844. y = keyAxis->coordToPixel(key);
  9845. x = valueAxis->coordToPixel(value);
  9846. }
  9847. }
  9848. /*! \overload
  9849. Transforms the given \a key and \a value to pixel coordinates and returns them in a QPointF.
  9850. */
  9851. const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const
  9852. {
  9853. QCPAxis *keyAxis = mKeyAxis.data();
  9854. QCPAxis *valueAxis = mValueAxis.data();
  9855. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
  9856. if (keyAxis->orientation() == Qt::Horizontal)
  9857. return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value));
  9858. else
  9859. return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key));
  9860. }
  9861. /*!
  9862. Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates,
  9863. taking the orientations of the axes associated with this plottable into account (e.g. whether key
  9864. represents x or y).
  9865. \a x and \a y are transformed to the plot coodinates and are written to \a key and \a value.
  9866. \see coordsToPixels, QCPAxis::coordToPixel
  9867. */
  9868. void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const
  9869. {
  9870. QCPAxis *keyAxis = mKeyAxis.data();
  9871. QCPAxis *valueAxis = mValueAxis.data();
  9872. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  9873. if (keyAxis->orientation() == Qt::Horizontal)
  9874. {
  9875. key = keyAxis->pixelToCoord(x);
  9876. value = valueAxis->pixelToCoord(y);
  9877. } else
  9878. {
  9879. key = keyAxis->pixelToCoord(y);
  9880. value = valueAxis->pixelToCoord(x);
  9881. }
  9882. }
  9883. /*! \overload
  9884. Returns the pixel input \a pixelPos as plot coordinates \a key and \a value.
  9885. */
  9886. void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
  9887. {
  9888. pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value);
  9889. }
  9890. /*!
  9891. Rescales the key and value axes associated with this plottable to contain all displayed data, so
  9892. the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make
  9893. sure not to rescale to an illegal range i.e. a range containing different signs and/or zero.
  9894. Instead it will stay in the current sign domain and ignore all parts of the plottable that lie
  9895. outside of that domain.
  9896. \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show
  9897. multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has
  9898. \a onlyEnlarge set to false (the default), and all subsequent set to true.
  9899. \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale
  9900. */
  9901. void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const
  9902. {
  9903. rescaleKeyAxis(onlyEnlarge);
  9904. rescaleValueAxis(onlyEnlarge);
  9905. }
  9906. /*!
  9907. Rescales the key axis of the plottable so the whole plottable is visible.
  9908. See \ref rescaleAxes for detailed behaviour.
  9909. */
  9910. void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const
  9911. {
  9912. QCPAxis *keyAxis = mKeyAxis.data();
  9913. if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
  9914. QCP::SignDomain signDomain = QCP::sdBoth;
  9915. if (keyAxis->scaleType() == QCPAxis::stLogarithmic)
  9916. signDomain = (keyAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  9917. bool foundRange;
  9918. QCPRange newRange = getKeyRange(foundRange, signDomain);
  9919. if (foundRange)
  9920. {
  9921. if (onlyEnlarge)
  9922. newRange.expand(keyAxis->range());
  9923. 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
  9924. {
  9925. 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
  9926. if (keyAxis->scaleType() == QCPAxis::stLinear)
  9927. {
  9928. newRange.lower = center-keyAxis->range().size()/2.0;
  9929. newRange.upper = center+keyAxis->range().size()/2.0;
  9930. } else // scaleType() == stLogarithmic
  9931. {
  9932. newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower);
  9933. newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower);
  9934. }
  9935. }
  9936. keyAxis->setRange(newRange);
  9937. }
  9938. }
  9939. /*!
  9940. Rescales the value axis of the plottable so the whole plottable is visible. If \a inKeyRange is
  9941. set to true, only the data points which are in the currently visible key axis range are
  9942. considered.
  9943. Returns true if the axis was actually scaled. This might not be the case if this plottable has an
  9944. invalid range, e.g. because it has no data points.
  9945. See \ref rescaleAxes for detailed behaviour.
  9946. */
  9947. bool QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const
  9948. {
  9949. QCPAxis *keyAxis = mKeyAxis.data();
  9950. QCPAxis *valueAxis = mValueAxis.data();
  9951. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return false; }
  9952. QCP::SignDomain signDomain = QCP::sdBoth;
  9953. if (valueAxis->scaleType() == QCPAxis::stLogarithmic)
  9954. signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  9955. bool foundRange;
  9956. QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange());
  9957. if (foundRange)
  9958. {
  9959. if (onlyEnlarge)
  9960. newRange.expand(valueAxis->range());
  9961. 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
  9962. {
  9963. 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
  9964. if (valueAxis->scaleType() == QCPAxis::stLinear)
  9965. {
  9966. newRange.lower = center-valueAxis->range().size()/2.0;
  9967. newRange.upper = center+valueAxis->range().size()/2.0;
  9968. } else // scaleType() == stLogarithmic
  9969. {
  9970. newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  9971. newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  9972. }
  9973. }
  9974. valueAxis->setRange(newRange);
  9975. }
  9976. return foundRange;
  9977. }
  9978. /*! \overload
  9979. Adds this plottable to the specified \a legend.
  9980. Creates a QCPPlottableLegendItem which is inserted into the legend. Returns true on success, i.e.
  9981. when the legend exists and a legend item associated with this plottable isn't already in the
  9982. legend.
  9983. If the plottable needs a more specialized representation in the legend, you can create a
  9984. corresponding subclass of \ref QCPPlottableLegendItem and add it to the legend manually instead
  9985. of calling this method.
  9986. \see removeFromLegend, QCPLegend::addItem
  9987. */
  9988. bool QCPAbstractPlottable::addToLegend(QCPLegend *legend)
  9989. {
  9990. if (!legend)
  9991. {
  9992. qDebug() << Q_FUNC_INFO << "passed legend is null";
  9993. return false;
  9994. }
  9995. if (legend->parentPlot() != mParentPlot)
  9996. {
  9997. qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable";
  9998. return false;
  9999. }
  10000. if (!legend->hasItemWithPlottable(this))
  10001. {
  10002. legend->addItem(new QCPPlottableLegendItem(legend, this));
  10003. return true;
  10004. } else
  10005. return false;
  10006. }
  10007. /*! \overload
  10008. Adds this plottable to the legend of the parent QCustomPlot (\ref QCustomPlot::legend).
  10009. \see removeFromLegend
  10010. */
  10011. bool QCPAbstractPlottable::addToLegend()
  10012. {
  10013. if (!mParentPlot || !mParentPlot->legend)
  10014. return false;
  10015. else
  10016. return addToLegend(mParentPlot->legend);
  10017. }
  10018. /*! \overload
  10019. Removes the plottable from the specifed \a legend. This means the \ref QCPPlottableLegendItem
  10020. that is associated with this plottable is removed.
  10021. Returns true on success, i.e. if the legend exists and a legend item associated with this
  10022. plottable was found and removed.
  10023. \see addToLegend, QCPLegend::removeItem
  10024. */
  10025. bool QCPAbstractPlottable::removeFromLegend(QCPLegend *legend) const
  10026. {
  10027. if (!legend)
  10028. {
  10029. qDebug() << Q_FUNC_INFO << "passed legend is null";
  10030. return false;
  10031. }
  10032. if (QCPPlottableLegendItem *lip = legend->itemWithPlottable(this))
  10033. return legend->removeItem(lip);
  10034. else
  10035. return false;
  10036. }
  10037. /*! \overload
  10038. Removes the plottable from the legend of the parent QCustomPlot.
  10039. \see addToLegend
  10040. */
  10041. bool QCPAbstractPlottable::removeFromLegend() const
  10042. {
  10043. if (!mParentPlot || !mParentPlot->legend)
  10044. return false;
  10045. else
  10046. return removeFromLegend(mParentPlot->legend);
  10047. }
  10048. /* inherits documentation from base class */
  10049. QRectF QCPAbstractPlottable::clipRect() const
  10050. {
  10051. if (mKeyAxis && mValueAxis)
  10052. return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect();
  10053. else
  10054. return {};
  10055. }
  10056. /* inherits documentation from base class */
  10057. QCP::Interaction QCPAbstractPlottable::selectionCategory() const
  10058. {
  10059. return QCP::iSelectPlottables;
  10060. }
  10061. /*! \internal
  10062. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  10063. before drawing plottable lines.
  10064. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  10065. This function takes into account the local setting of the antialiasing flag as well as the
  10066. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  10067. QCustomPlot::setNotAntialiasedElements.
  10068. \seebaseclassmethod
  10069. \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint
  10070. */
  10071. void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const
  10072. {
  10073. applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables);
  10074. }
  10075. /*! \internal
  10076. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  10077. before drawing plottable fills.
  10078. This function takes into account the local setting of the antialiasing flag as well as the
  10079. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  10080. QCustomPlot::setNotAntialiasedElements.
  10081. \see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint
  10082. */
  10083. void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const
  10084. {
  10085. applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills);
  10086. }
  10087. /*! \internal
  10088. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  10089. before drawing plottable scatter points.
  10090. This function takes into account the local setting of the antialiasing flag as well as the
  10091. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  10092. QCustomPlot::setNotAntialiasedElements.
  10093. \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint
  10094. */
  10095. void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const
  10096. {
  10097. applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
  10098. }
  10099. /* inherits documentation from base class */
  10100. void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  10101. {
  10102. Q_UNUSED(event)
  10103. if (mSelectable != QCP::stNone)
  10104. {
  10105. QCPDataSelection newSelection = details.value<QCPDataSelection>();
  10106. QCPDataSelection selectionBefore = mSelection;
  10107. if (additive)
  10108. {
  10109. if (mSelectable == QCP::stWhole) // in whole selection mode, we toggle to no selection even if currently unselected point was hit
  10110. {
  10111. if (selected())
  10112. setSelection(QCPDataSelection());
  10113. else
  10114. setSelection(newSelection);
  10115. } else // in all other selection modes we toggle selections of homogeneously selected/unselected segments
  10116. {
  10117. if (mSelection.contains(newSelection)) // if entire newSelection is already selected, toggle selection
  10118. setSelection(mSelection-newSelection);
  10119. else
  10120. setSelection(mSelection+newSelection);
  10121. }
  10122. } else
  10123. setSelection(newSelection);
  10124. if (selectionStateChanged)
  10125. *selectionStateChanged = mSelection != selectionBefore;
  10126. }
  10127. }
  10128. /* inherits documentation from base class */
  10129. void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged)
  10130. {
  10131. if (mSelectable != QCP::stNone)
  10132. {
  10133. QCPDataSelection selectionBefore = mSelection;
  10134. setSelection(QCPDataSelection());
  10135. if (selectionStateChanged)
  10136. *selectionStateChanged = mSelection != selectionBefore;
  10137. }
  10138. }
  10139. /* end of 'src/plottable.cpp' */
  10140. /* including file 'src/item.cpp' */
  10141. /* modified 2021-03-29T02:30:44, size 49486 */
  10142. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10143. //////////////////// QCPItemAnchor
  10144. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10145. /*! \class QCPItemAnchor
  10146. \brief An anchor of an item to which positions can be attached to.
  10147. An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't
  10148. control anything on its item, but provides a way to tie other items via their positions to the
  10149. anchor.
  10150. For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight.
  10151. Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can
  10152. attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by
  10153. calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the
  10154. QCPItemRect. This way the start of the line will now always follow the respective anchor location
  10155. on the rect item.
  10156. Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an
  10157. anchor to other positions.
  10158. To learn how to provide anchors in your own item subclasses, see the subclassing section of the
  10159. QCPAbstractItem documentation.
  10160. */
  10161. /* start documentation of inline functions */
  10162. /*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition()
  10163. Returns \c nullptr if this instance is merely a QCPItemAnchor, and a valid pointer of type
  10164. QCPItemPosition* if it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor).
  10165. This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids
  10166. dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with
  10167. gcc compiler).
  10168. */
  10169. /* end documentation of inline functions */
  10170. /*!
  10171. Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if
  10172. you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as
  10173. explained in the subclassing section of the QCPAbstractItem documentation.
  10174. */
  10175. QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId) :
  10176. mName(name),
  10177. mParentPlot(parentPlot),
  10178. mParentItem(parentItem),
  10179. mAnchorId(anchorId)
  10180. {
  10181. }
  10182. QCPItemAnchor::~QCPItemAnchor()
  10183. {
  10184. // unregister as parent at children:
  10185. foreach (QCPItemPosition *child, mChildrenX.values())
  10186. {
  10187. if (child->parentAnchorX() == this)
  10188. child->setParentAnchorX(nullptr); // this acts back on this anchor and child removes itself from mChildrenX
  10189. }
  10190. foreach (QCPItemPosition *child, mChildrenY.values())
  10191. {
  10192. if (child->parentAnchorY() == this)
  10193. child->setParentAnchorY(nullptr); // this acts back on this anchor and child removes itself from mChildrenY
  10194. }
  10195. }
  10196. /*!
  10197. Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface.
  10198. The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the
  10199. parent item, QCPItemAnchor is just an intermediary.
  10200. */
  10201. QPointF QCPItemAnchor::pixelPosition() const
  10202. {
  10203. if (mParentItem)
  10204. {
  10205. if (mAnchorId > -1)
  10206. {
  10207. return mParentItem->anchorPixelPosition(mAnchorId);
  10208. } else
  10209. {
  10210. qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId;
  10211. return {};
  10212. }
  10213. } else
  10214. {
  10215. qDebug() << Q_FUNC_INFO << "no parent item set";
  10216. return {};
  10217. }
  10218. }
  10219. /*! \internal
  10220. Adds \a pos to the childX list of this anchor, which keeps track of which children use this
  10221. anchor as parent anchor for the respective coordinate. This is necessary to notify the children
  10222. prior to destruction of the anchor.
  10223. Note that this function does not change the parent setting in \a pos.
  10224. */
  10225. void QCPItemAnchor::addChildX(QCPItemPosition *pos)
  10226. {
  10227. if (!mChildrenX.contains(pos))
  10228. mChildrenX.insert(pos);
  10229. else
  10230. qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
  10231. }
  10232. /*! \internal
  10233. Removes \a pos from the childX list of this anchor.
  10234. Note that this function does not change the parent setting in \a pos.
  10235. */
  10236. void QCPItemAnchor::removeChildX(QCPItemPosition *pos)
  10237. {
  10238. if (!mChildrenX.remove(pos))
  10239. qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
  10240. }
  10241. /*! \internal
  10242. Adds \a pos to the childY list of this anchor, which keeps track of which children use this
  10243. anchor as parent anchor for the respective coordinate. This is necessary to notify the children
  10244. prior to destruction of the anchor.
  10245. Note that this function does not change the parent setting in \a pos.
  10246. */
  10247. void QCPItemAnchor::addChildY(QCPItemPosition *pos)
  10248. {
  10249. if (!mChildrenY.contains(pos))
  10250. mChildrenY.insert(pos);
  10251. else
  10252. qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
  10253. }
  10254. /*! \internal
  10255. Removes \a pos from the childY list of this anchor.
  10256. Note that this function does not change the parent setting in \a pos.
  10257. */
  10258. void QCPItemAnchor::removeChildY(QCPItemPosition *pos)
  10259. {
  10260. if (!mChildrenY.remove(pos))
  10261. qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
  10262. }
  10263. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10264. //////////////////// QCPItemPosition
  10265. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10266. /*! \class QCPItemPosition
  10267. \brief Manages the position of an item.
  10268. Every item has at least one public QCPItemPosition member pointer which provides ways to position the
  10269. item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two:
  10270. \a topLeft and \a bottomRight.
  10271. QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type
  10272. defines how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel
  10273. coordinates, as plot coordinates of certain axes (\ref QCPItemPosition::setAxes), as fractions of
  10274. the axis rect (\ref QCPItemPosition::setAxisRect), etc. For more advanced plots it is also
  10275. possible to assign different types per X/Y coordinate of the position (see \ref setTypeX, \ref
  10276. setTypeY). This way an item could be positioned for example at a fixed pixel distance from the
  10277. top in the Y direction, while following a plot coordinate in the X direction.
  10278. A QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. This way you can tie
  10279. multiple items together. If the QCPItemPosition has a parent, its coordinates (\ref setCoords)
  10280. are considered to be absolute pixels in the reference frame of the parent anchor, where (0, 0)
  10281. means directly ontop of the parent anchor. For example, You could attach the \a start position of
  10282. a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting point of the line
  10283. always be centered under the text label, no matter where the text is moved to. For more advanced
  10284. plots, it is possible to assign different parent anchors per X/Y coordinate of the position, see
  10285. \ref setParentAnchorX, \ref setParentAnchorY. This way an item could follow another item in the X
  10286. direction but stay at a fixed position in the Y direction. Or even follow item A in X, and item B
  10287. in Y.
  10288. Note that every QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent
  10289. anchor for other positions.
  10290. To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPosition. This
  10291. works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref
  10292. setPixelPosition transforms the coordinates appropriately, to make the position appear at the specified
  10293. pixel values.
  10294. */
  10295. /* start documentation of inline functions */
  10296. /*! \fn QCPItemPosition::PositionType *QCPItemPosition::type() const
  10297. Returns the current position type.
  10298. If different types were set for X and Y (\ref setTypeX, \ref setTypeY), this method returns the
  10299. type of the X coordinate. In that case rather use \a typeX() and \a typeY().
  10300. \see setType
  10301. */
  10302. /*! \fn QCPItemAnchor *QCPItemPosition::parentAnchor() const
  10303. Returns the current parent anchor.
  10304. If different parent anchors were set for X and Y (\ref setParentAnchorX, \ref setParentAnchorY),
  10305. this method returns the parent anchor of the Y coordinate. In that case rather use \a
  10306. parentAnchorX() and \a parentAnchorY().
  10307. \see setParentAnchor
  10308. */
  10309. /* end documentation of inline functions */
  10310. /*!
  10311. Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if
  10312. you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as
  10313. explained in the subclassing section of the QCPAbstractItem documentation.
  10314. */
  10315. QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name) :
  10316. QCPItemAnchor(parentPlot, parentItem, name),
  10317. mPositionTypeX(ptAbsolute),
  10318. mPositionTypeY(ptAbsolute),
  10319. mKey(0),
  10320. mValue(0),
  10321. mParentAnchorX(nullptr),
  10322. mParentAnchorY(nullptr)
  10323. {
  10324. }
  10325. QCPItemPosition::~QCPItemPosition()
  10326. {
  10327. // unregister as parent at children:
  10328. // Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then
  10329. // the setParentAnchor(0) call the correct QCPItemPosition::pixelPosition function instead of QCPItemAnchor::pixelPosition
  10330. foreach (QCPItemPosition *child, mChildrenX.values())
  10331. {
  10332. if (child->parentAnchorX() == this)
  10333. child->setParentAnchorX(nullptr); // this acts back on this anchor and child removes itself from mChildrenX
  10334. }
  10335. foreach (QCPItemPosition *child, mChildrenY.values())
  10336. {
  10337. if (child->parentAnchorY() == this)
  10338. child->setParentAnchorY(nullptr); // this acts back on this anchor and child removes itself from mChildrenY
  10339. }
  10340. // unregister as child in parent:
  10341. if (mParentAnchorX)
  10342. mParentAnchorX->removeChildX(this);
  10343. if (mParentAnchorY)
  10344. mParentAnchorY->removeChildY(this);
  10345. }
  10346. /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
  10347. QCPAxisRect *QCPItemPosition::axisRect() const
  10348. {
  10349. return mAxisRect.data();
  10350. }
  10351. /*!
  10352. Sets the type of the position. The type defines how the coordinates passed to \ref setCoords
  10353. should be handled and how the QCPItemPosition should behave in the plot.
  10354. The possible values for \a type can be separated in two main categories:
  10355. \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords
  10356. and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes.
  10357. By default, the QCustomPlot's x- and yAxis are used.
  10358. \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This
  10359. corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref
  10360. ptAxisRectRatio. They differ only in the way the absolute position is described, see the
  10361. documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify
  10362. the axis rect with \ref setAxisRect. By default this is set to the main axis rect.
  10363. Note that the position type \ref ptPlotCoords is only available (and sensible) when the position
  10364. has no parent anchor (\ref setParentAnchor).
  10365. If the type is changed, the apparent pixel position on the plot is preserved. This means
  10366. the coordinates as retrieved with coords() and set with \ref setCoords may change in the process.
  10367. This method sets the type for both X and Y directions. It is also possible to set different types
  10368. for X and Y, see \ref setTypeX, \ref setTypeY.
  10369. */
  10370. void QCPItemPosition::setType(QCPItemPosition::PositionType type)
  10371. {
  10372. setTypeX(type);
  10373. setTypeY(type);
  10374. }
  10375. /*!
  10376. This method sets the position type of the X coordinate to \a type.
  10377. For a detailed description of what a position type is, see the documentation of \ref setType.
  10378. \see setType, setTypeY
  10379. */
  10380. void QCPItemPosition::setTypeX(QCPItemPosition::PositionType type)
  10381. {
  10382. if (mPositionTypeX != type)
  10383. {
  10384. // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
  10385. // were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning.
  10386. bool retainPixelPosition = true;
  10387. if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
  10388. retainPixelPosition = false;
  10389. if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
  10390. retainPixelPosition = false;
  10391. QPointF pixel;
  10392. if (retainPixelPosition)
  10393. pixel = pixelPosition();
  10394. mPositionTypeX = type;
  10395. if (retainPixelPosition)
  10396. setPixelPosition(pixel);
  10397. }
  10398. }
  10399. /*!
  10400. This method sets the position type of the Y coordinate to \a type.
  10401. For a detailed description of what a position type is, see the documentation of \ref setType.
  10402. \see setType, setTypeX
  10403. */
  10404. void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type)
  10405. {
  10406. if (mPositionTypeY != type)
  10407. {
  10408. // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
  10409. // were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning.
  10410. bool retainPixelPosition = true;
  10411. if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
  10412. retainPixelPosition = false;
  10413. if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
  10414. retainPixelPosition = false;
  10415. QPointF pixel;
  10416. if (retainPixelPosition)
  10417. pixel = pixelPosition();
  10418. mPositionTypeY = type;
  10419. if (retainPixelPosition)
  10420. setPixelPosition(pixel);
  10421. }
  10422. }
  10423. /*!
  10424. Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now
  10425. follow any position changes of the anchor. The local coordinate system of positions with a parent
  10426. anchor always is absolute pixels, with (0, 0) being exactly on top of the parent anchor. (Hence
  10427. the type shouldn't be set to \ref ptPlotCoords for positions with parent anchors.)
  10428. if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved
  10429. during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position
  10430. will be exactly on top of the parent anchor.
  10431. To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to \c nullptr.
  10432. If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is
  10433. set to \ref ptAbsolute, to keep the position in a valid state.
  10434. This method sets the parent anchor for both X and Y directions. It is also possible to set
  10435. different parents for X and Y, see \ref setParentAnchorX, \ref setParentAnchorY.
  10436. */
  10437. bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
  10438. {
  10439. bool successX = setParentAnchorX(parentAnchor, keepPixelPosition);
  10440. bool successY = setParentAnchorY(parentAnchor, keepPixelPosition);
  10441. return successX && successY;
  10442. }
  10443. /*!
  10444. This method sets the parent anchor of the X coordinate to \a parentAnchor.
  10445. For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor.
  10446. \see setParentAnchor, setParentAnchorY
  10447. */
  10448. bool QCPItemPosition::setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
  10449. {
  10450. // make sure self is not assigned as parent:
  10451. if (parentAnchor == this)
  10452. {
  10453. qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
  10454. return false;
  10455. }
  10456. // make sure no recursive parent-child-relationships are created:
  10457. QCPItemAnchor *currentParent = parentAnchor;
  10458. while (currentParent)
  10459. {
  10460. if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
  10461. {
  10462. // is a QCPItemPosition, might have further parent, so keep iterating
  10463. if (currentParentPos == this)
  10464. {
  10465. qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
  10466. return false;
  10467. }
  10468. currentParent = currentParentPos->parentAnchorX();
  10469. } else
  10470. {
  10471. // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
  10472. // same, to prevent a position being child of an anchor which itself depends on the position,
  10473. // because they're both on the same item:
  10474. if (currentParent->mParentItem == mParentItem)
  10475. {
  10476. qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
  10477. return false;
  10478. }
  10479. break;
  10480. }
  10481. }
  10482. // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
  10483. if (!mParentAnchorX && mPositionTypeX == ptPlotCoords)
  10484. setTypeX(ptAbsolute);
  10485. // save pixel position:
  10486. QPointF pixelP;
  10487. if (keepPixelPosition)
  10488. pixelP = pixelPosition();
  10489. // unregister at current parent anchor:
  10490. if (mParentAnchorX)
  10491. mParentAnchorX->removeChildX(this);
  10492. // register at new parent anchor:
  10493. if (parentAnchor)
  10494. parentAnchor->addChildX(this);
  10495. mParentAnchorX = parentAnchor;
  10496. // restore pixel position under new parent:
  10497. if (keepPixelPosition)
  10498. setPixelPosition(pixelP);
  10499. else
  10500. setCoords(0, coords().y());
  10501. return true;
  10502. }
  10503. /*!
  10504. This method sets the parent anchor of the Y coordinate to \a parentAnchor.
  10505. For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor.
  10506. \see setParentAnchor, setParentAnchorX
  10507. */
  10508. bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
  10509. {
  10510. // make sure self is not assigned as parent:
  10511. if (parentAnchor == this)
  10512. {
  10513. qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
  10514. return false;
  10515. }
  10516. // make sure no recursive parent-child-relationships are created:
  10517. QCPItemAnchor *currentParent = parentAnchor;
  10518. while (currentParent)
  10519. {
  10520. if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
  10521. {
  10522. // is a QCPItemPosition, might have further parent, so keep iterating
  10523. if (currentParentPos == this)
  10524. {
  10525. qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
  10526. return false;
  10527. }
  10528. currentParent = currentParentPos->parentAnchorY();
  10529. } else
  10530. {
  10531. // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
  10532. // same, to prevent a position being child of an anchor which itself depends on the position,
  10533. // because they're both on the same item:
  10534. if (currentParent->mParentItem == mParentItem)
  10535. {
  10536. qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
  10537. return false;
  10538. }
  10539. break;
  10540. }
  10541. }
  10542. // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
  10543. if (!mParentAnchorY && mPositionTypeY == ptPlotCoords)
  10544. setTypeY(ptAbsolute);
  10545. // save pixel position:
  10546. QPointF pixelP;
  10547. if (keepPixelPosition)
  10548. pixelP = pixelPosition();
  10549. // unregister at current parent anchor:
  10550. if (mParentAnchorY)
  10551. mParentAnchorY->removeChildY(this);
  10552. // register at new parent anchor:
  10553. if (parentAnchor)
  10554. parentAnchor->addChildY(this);
  10555. mParentAnchorY = parentAnchor;
  10556. // restore pixel position under new parent:
  10557. if (keepPixelPosition)
  10558. setPixelPosition(pixelP);
  10559. else
  10560. setCoords(coords().x(), 0);
  10561. return true;
  10562. }
  10563. /*!
  10564. Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type
  10565. (\ref setType, \ref setTypeX, \ref setTypeY).
  10566. For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position
  10567. on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the
  10568. QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the
  10569. plot coordinate system defined by the axes set by \ref setAxes. By default those are the
  10570. QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available
  10571. coordinate types and their meaning.
  10572. If different types were configured for X and Y (\ref setTypeX, \ref setTypeY), \a key and \a
  10573. value must also be provided in the different coordinate systems. Here, the X type refers to \a
  10574. key, and the Y type refers to \a value.
  10575. \see setPixelPosition
  10576. */
  10577. void QCPItemPosition::setCoords(double key, double value)
  10578. {
  10579. mKey = key;
  10580. mValue = value;
  10581. }
  10582. /*! \overload
  10583. Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the
  10584. meaning of \a value of the \ref setCoords(double key, double value) method.
  10585. */
  10586. void QCPItemPosition::setCoords(const QPointF &pos)
  10587. {
  10588. setCoords(pos.x(), pos.y());
  10589. }
  10590. /*!
  10591. Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It
  10592. includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor).
  10593. \see setPixelPosition
  10594. */
  10595. QPointF QCPItemPosition::pixelPosition() const
  10596. {
  10597. QPointF result;
  10598. // determine X:
  10599. switch (mPositionTypeX)
  10600. {
  10601. case ptAbsolute:
  10602. {
  10603. result.rx() = mKey;
  10604. if (mParentAnchorX)
  10605. result.rx() += mParentAnchorX->pixelPosition().x();
  10606. break;
  10607. }
  10608. case ptViewportRatio:
  10609. {
  10610. result.rx() = mKey*mParentPlot->viewport().width();
  10611. if (mParentAnchorX)
  10612. result.rx() += mParentAnchorX->pixelPosition().x();
  10613. else
  10614. result.rx() += mParentPlot->viewport().left();
  10615. break;
  10616. }
  10617. case ptAxisRectRatio:
  10618. {
  10619. if (mAxisRect)
  10620. {
  10621. result.rx() = mKey*mAxisRect.data()->width();
  10622. if (mParentAnchorX)
  10623. result.rx() += mParentAnchorX->pixelPosition().x();
  10624. else
  10625. result.rx() += mAxisRect.data()->left();
  10626. } else
  10627. qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
  10628. break;
  10629. }
  10630. case ptPlotCoords:
  10631. {
  10632. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
  10633. result.rx() = mKeyAxis.data()->coordToPixel(mKey);
  10634. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
  10635. result.rx() = mValueAxis.data()->coordToPixel(mValue);
  10636. else
  10637. qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined";
  10638. break;
  10639. }
  10640. }
  10641. // determine Y:
  10642. switch (mPositionTypeY)
  10643. {
  10644. case ptAbsolute:
  10645. {
  10646. result.ry() = mValue;
  10647. if (mParentAnchorY)
  10648. result.ry() += mParentAnchorY->pixelPosition().y();
  10649. break;
  10650. }
  10651. case ptViewportRatio:
  10652. {
  10653. result.ry() = mValue*mParentPlot->viewport().height();
  10654. if (mParentAnchorY)
  10655. result.ry() += mParentAnchorY->pixelPosition().y();
  10656. else
  10657. result.ry() += mParentPlot->viewport().top();
  10658. break;
  10659. }
  10660. case ptAxisRectRatio:
  10661. {
  10662. if (mAxisRect)
  10663. {
  10664. result.ry() = mValue*mAxisRect.data()->height();
  10665. if (mParentAnchorY)
  10666. result.ry() += mParentAnchorY->pixelPosition().y();
  10667. else
  10668. result.ry() += mAxisRect.data()->top();
  10669. } else
  10670. qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
  10671. break;
  10672. }
  10673. case ptPlotCoords:
  10674. {
  10675. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
  10676. result.ry() = mKeyAxis.data()->coordToPixel(mKey);
  10677. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
  10678. result.ry() = mValueAxis.data()->coordToPixel(mValue);
  10679. else
  10680. qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined";
  10681. break;
  10682. }
  10683. }
  10684. return result;
  10685. }
  10686. /*!
  10687. When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the
  10688. coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and
  10689. yAxis of the QCustomPlot.
  10690. */
  10691. void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis)
  10692. {
  10693. mKeyAxis = keyAxis;
  10694. mValueAxis = valueAxis;
  10695. }
  10696. /*!
  10697. When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the
  10698. coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of
  10699. the QCustomPlot.
  10700. */
  10701. void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect)
  10702. {
  10703. mAxisRect = axisRect;
  10704. }
  10705. /*!
  10706. Sets the apparent pixel position. This works no matter what type (\ref setType) this
  10707. QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed
  10708. appropriately, to make the position finally appear at the specified pixel values.
  10709. Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is
  10710. identical to that of \ref setCoords.
  10711. \see pixelPosition, setCoords
  10712. */
  10713. void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition)
  10714. {
  10715. double x = pixelPosition.x();
  10716. double y = pixelPosition.y();
  10717. switch (mPositionTypeX)
  10718. {
  10719. case ptAbsolute:
  10720. {
  10721. if (mParentAnchorX)
  10722. x -= mParentAnchorX->pixelPosition().x();
  10723. break;
  10724. }
  10725. case ptViewportRatio:
  10726. {
  10727. if (mParentAnchorX)
  10728. x -= mParentAnchorX->pixelPosition().x();
  10729. else
  10730. x -= mParentPlot->viewport().left();
  10731. x /= double(mParentPlot->viewport().width());
  10732. break;
  10733. }
  10734. case ptAxisRectRatio:
  10735. {
  10736. if (mAxisRect)
  10737. {
  10738. if (mParentAnchorX)
  10739. x -= mParentAnchorX->pixelPosition().x();
  10740. else
  10741. x -= mAxisRect.data()->left();
  10742. x /= double(mAxisRect.data()->width());
  10743. } else
  10744. qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
  10745. break;
  10746. }
  10747. case ptPlotCoords:
  10748. {
  10749. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
  10750. x = mKeyAxis.data()->pixelToCoord(x);
  10751. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
  10752. y = mValueAxis.data()->pixelToCoord(x);
  10753. else
  10754. qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined";
  10755. break;
  10756. }
  10757. }
  10758. switch (mPositionTypeY)
  10759. {
  10760. case ptAbsolute:
  10761. {
  10762. if (mParentAnchorY)
  10763. y -= mParentAnchorY->pixelPosition().y();
  10764. break;
  10765. }
  10766. case ptViewportRatio:
  10767. {
  10768. if (mParentAnchorY)
  10769. y -= mParentAnchorY->pixelPosition().y();
  10770. else
  10771. y -= mParentPlot->viewport().top();
  10772. y /= double(mParentPlot->viewport().height());
  10773. break;
  10774. }
  10775. case ptAxisRectRatio:
  10776. {
  10777. if (mAxisRect)
  10778. {
  10779. if (mParentAnchorY)
  10780. y -= mParentAnchorY->pixelPosition().y();
  10781. else
  10782. y -= mAxisRect.data()->top();
  10783. y /= double(mAxisRect.data()->height());
  10784. } else
  10785. qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
  10786. break;
  10787. }
  10788. case ptPlotCoords:
  10789. {
  10790. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
  10791. x = mKeyAxis.data()->pixelToCoord(y);
  10792. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
  10793. y = mValueAxis.data()->pixelToCoord(y);
  10794. else
  10795. qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined";
  10796. break;
  10797. }
  10798. }
  10799. setCoords(x, y);
  10800. }
  10801. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10802. //////////////////// QCPAbstractItem
  10803. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10804. /*! \class QCPAbstractItem
  10805. \brief The abstract base class for all items in a plot.
  10806. In QCustomPlot, items are supplemental graphical elements that are neither plottables
  10807. (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus
  10808. plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each
  10809. specific item has at least one QCPItemPosition member which controls the positioning. Some items
  10810. are defined by more than one coordinate and thus have two or more QCPItemPosition members (For
  10811. example, QCPItemRect has \a topLeft and \a bottomRight).
  10812. This abstract base class defines a very basic interface like visibility and clipping. Since this
  10813. class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass
  10814. yourself to create new items.
  10815. The built-in items are:
  10816. <table>
  10817. <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>
  10818. <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>
  10819. <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>
  10820. <tr><td>QCPItemRect</td><td>A rectangle</td></tr>
  10821. <tr><td>QCPItemEllipse</td><td>An ellipse</td></tr>
  10822. <tr><td>QCPItemPixmap</td><td>An arbitrary pixmap</td></tr>
  10823. <tr><td>QCPItemText</td><td>A text label</td></tr>
  10824. <tr><td>QCPItemBracket</td><td>A bracket which may be used to reference/highlight certain parts in the plot.</td></tr>
  10825. <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>
  10826. </table>
  10827. \section items-clipping Clipping
  10828. Items are by default clipped to the main axis rect (they are only visible inside the axis rect).
  10829. To make an item visible outside that axis rect, disable clipping via \ref setClipToAxisRect
  10830. "setClipToAxisRect(false)".
  10831. On the other hand if you want the item to be clipped to a different axis rect, specify it via
  10832. \ref setClipAxisRect. This clipAxisRect property of an item is only used for clipping behaviour, and
  10833. in principle is independent of the coordinate axes the item might be tied to via its position
  10834. members (\ref QCPItemPosition::setAxes). However, it is common that the axis rect for clipping
  10835. also contains the axes used for the item positions.
  10836. \section items-using Using items
  10837. First you instantiate the item you want to use and add it to the plot:
  10838. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-1
  10839. by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just
  10840. set the plot coordinates where the line should start/end:
  10841. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-2
  10842. If we don't want the line to be positioned in plot coordinates but a different coordinate system,
  10843. e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like this:
  10844. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-3
  10845. Then we can set the coordinates, this time in pixels:
  10846. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-4
  10847. and make the line visible on the entire QCustomPlot, by disabling clipping to the axis rect:
  10848. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-5
  10849. For more advanced plots, it is even possible to set different types and parent anchors per X/Y
  10850. coordinate of an item position, using for example \ref QCPItemPosition::setTypeX or \ref
  10851. QCPItemPosition::setParentAnchorX. For details, see the documentation of \ref QCPItemPosition.
  10852. \section items-subclassing Creating own items
  10853. To create an own item, you implement a subclass of QCPAbstractItem. These are the pure
  10854. virtual functions, you must implement:
  10855. \li \ref selectTest
  10856. \li \ref draw
  10857. See the documentation of those functions for what they need to do.
  10858. \subsection items-positioning Allowing the item to be positioned
  10859. As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall
  10860. have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add
  10861. a public member of type QCPItemPosition like so:
  10862. \code QCPItemPosition * const myPosition;\endcode
  10863. the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition
  10864. instance it points to, can be modified, of course).
  10865. The initialization of this pointer is made easy with the \ref createPosition function. Just assign
  10866. the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition
  10867. takes a string which is the name of the position, typically this is identical to the variable name.
  10868. For example, the constructor of QCPItemExample could look like this:
  10869. \code
  10870. QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) :
  10871. QCPAbstractItem(parentPlot),
  10872. myPosition(createPosition("myPosition"))
  10873. {
  10874. // other constructor code
  10875. }
  10876. \endcode
  10877. \subsection items-drawing The draw function
  10878. To give your item a visual representation, reimplement the \ref draw function and use the passed
  10879. QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the
  10880. position member(s) via \ref QCPItemPosition::pixelPosition.
  10881. To optimize performance you should calculate a bounding rect first (don't forget to take the pen
  10882. width into account), check whether it intersects the \ref clipRect, and only draw the item at all
  10883. if this is the case.
  10884. \subsection items-selection The selectTest function
  10885. Your implementation of the \ref selectTest function may use the helpers \ref
  10886. QCPVector2D::distanceSquaredToLine and \ref rectDistance. With these, the implementation of the
  10887. selection test becomes significantly simpler for most items. See the documentation of \ref
  10888. selectTest for what the function parameters mean and what the function should return.
  10889. \subsection anchors Providing anchors
  10890. Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public
  10891. member, e.g.
  10892. \code QCPItemAnchor * const bottom;\endcode
  10893. and create it in the constructor with the \ref createAnchor function, assigning it a name and an
  10894. anchor id (an integer enumerating all anchors on the item, you may create an own enum for this).
  10895. Since anchors can be placed anywhere, relative to the item's position(s), your item needs to
  10896. provide the position of every anchor with the reimplementation of the \ref anchorPixelPosition(int
  10897. anchorId) function.
  10898. In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel
  10899. position when anything attached to the anchor needs to know the coordinates.
  10900. */
  10901. /* start of documentation of inline functions */
  10902. /*! \fn QList<QCPItemPosition*> QCPAbstractItem::positions() const
  10903. Returns all positions of the item in a list.
  10904. \see anchors, position
  10905. */
  10906. /*! \fn QList<QCPItemAnchor*> QCPAbstractItem::anchors() const
  10907. Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always
  10908. also an anchor, the list will also contain the positions of this item.
  10909. \see positions, anchor
  10910. */
  10911. /* end of documentation of inline functions */
  10912. /* start documentation of pure virtual functions */
  10913. /*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0
  10914. \internal
  10915. Draws this item with the provided \a painter.
  10916. The cliprect of the provided painter is set to the rect returned by \ref clipRect before this
  10917. function is called. The clipRect depends on the clipping settings defined by \ref
  10918. setClipToAxisRect and \ref setClipAxisRect.
  10919. */
  10920. /* end documentation of pure virtual functions */
  10921. /* start documentation of signals */
  10922. /*! \fn void QCPAbstractItem::selectionChanged(bool selected)
  10923. This signal is emitted when the selection state of this item has changed, either by user interaction
  10924. or by a direct call to \ref setSelected.
  10925. */
  10926. /* end documentation of signals */
  10927. /*!
  10928. Base class constructor which initializes base class members.
  10929. */
  10930. QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) :
  10931. QCPLayerable(parentPlot),
  10932. mClipToAxisRect(false),
  10933. mSelectable(true),
  10934. mSelected(false)
  10935. {
  10936. parentPlot->registerItem(this);
  10937. QList<QCPAxisRect*> rects = parentPlot->axisRects();
  10938. if (!rects.isEmpty())
  10939. {
  10940. setClipToAxisRect(true);
  10941. setClipAxisRect(rects.first());
  10942. }
  10943. }
  10944. QCPAbstractItem::~QCPAbstractItem()
  10945. {
  10946. // don't delete mPositions because every position is also an anchor and thus in mAnchors
  10947. qDeleteAll(mAnchors);
  10948. }
  10949. /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
  10950. QCPAxisRect *QCPAbstractItem::clipAxisRect() const
  10951. {
  10952. return mClipAxisRect.data();
  10953. }
  10954. /*!
  10955. Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the
  10956. entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect.
  10957. \see setClipAxisRect
  10958. */
  10959. void QCPAbstractItem::setClipToAxisRect(bool clip)
  10960. {
  10961. mClipToAxisRect = clip;
  10962. if (mClipToAxisRect)
  10963. setParentLayerable(mClipAxisRect.data());
  10964. }
  10965. /*!
  10966. Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref
  10967. setClipToAxisRect is set to true.
  10968. \see setClipToAxisRect
  10969. */
  10970. void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect)
  10971. {
  10972. mClipAxisRect = rect;
  10973. if (mClipToAxisRect)
  10974. setParentLayerable(mClipAxisRect.data());
  10975. }
  10976. /*!
  10977. Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface.
  10978. (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.)
  10979. However, even when \a selectable was set to false, it is possible to set the selection manually,
  10980. by calling \ref setSelected.
  10981. \see QCustomPlot::setInteractions, setSelected
  10982. */
  10983. void QCPAbstractItem::setSelectable(bool selectable)
  10984. {
  10985. if (mSelectable != selectable)
  10986. {
  10987. mSelectable = selectable;
  10988. emit selectableChanged(mSelectable);
  10989. }
  10990. }
  10991. /*!
  10992. Sets whether this item is selected or not. When selected, it might use a different visual
  10993. appearance (e.g. pen and brush), this depends on the specific item though.
  10994. The entire selection mechanism for items is handled automatically when \ref
  10995. QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this
  10996. function when you wish to change the selection state manually.
  10997. This function can change the selection state even when \ref setSelectable was set to false.
  10998. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  10999. \see setSelectable, selectTest
  11000. */
  11001. void QCPAbstractItem::setSelected(bool selected)
  11002. {
  11003. if (mSelected != selected)
  11004. {
  11005. mSelected = selected;
  11006. emit selectionChanged(mSelected);
  11007. }
  11008. }
  11009. /*!
  11010. Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by
  11011. that name, returns \c nullptr.
  11012. This function provides an alternative way to access item positions. Normally, you access
  11013. positions direcly by their member pointers (which typically have the same variable name as \a
  11014. name).
  11015. \see positions, anchor
  11016. */
  11017. QCPItemPosition *QCPAbstractItem::position(const QString &name) const
  11018. {
  11019. foreach (QCPItemPosition *position, mPositions)
  11020. {
  11021. if (position->name() == name)
  11022. return position;
  11023. }
  11024. qDebug() << Q_FUNC_INFO << "position with name not found:" << name;
  11025. return nullptr;
  11026. }
  11027. /*!
  11028. Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by
  11029. that name, returns \c nullptr.
  11030. This function provides an alternative way to access item anchors. Normally, you access
  11031. anchors direcly by their member pointers (which typically have the same variable name as \a
  11032. name).
  11033. \see anchors, position
  11034. */
  11035. QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const
  11036. {
  11037. foreach (QCPItemAnchor *anchor, mAnchors)
  11038. {
  11039. if (anchor->name() == name)
  11040. return anchor;
  11041. }
  11042. qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name;
  11043. return nullptr;
  11044. }
  11045. /*!
  11046. Returns whether this item has an anchor with the specified \a name.
  11047. Note that you can check for positions with this function, too. This is because every position is
  11048. also an anchor (QCPItemPosition inherits from QCPItemAnchor).
  11049. \see anchor, position
  11050. */
  11051. bool QCPAbstractItem::hasAnchor(const QString &name) const
  11052. {
  11053. foreach (QCPItemAnchor *anchor, mAnchors)
  11054. {
  11055. if (anchor->name() == name)
  11056. return true;
  11057. }
  11058. return false;
  11059. }
  11060. /*! \internal
  11061. Returns the rect the visual representation of this item is clipped to. This depends on the
  11062. current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect.
  11063. If the item is not clipped to an axis rect, QCustomPlot's viewport rect is returned.
  11064. \see draw
  11065. */
  11066. QRectF QCPAbstractItem::clipRect() const
  11067. {
  11068. if (mClipToAxisRect && mClipAxisRect)
  11069. return mClipAxisRect.data()->rect();
  11070. else
  11071. return mParentPlot->viewport();
  11072. }
  11073. /*! \internal
  11074. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  11075. before drawing item lines.
  11076. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  11077. This function takes into account the local setting of the antialiasing flag as well as the
  11078. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  11079. QCustomPlot::setNotAntialiasedElements.
  11080. \see setAntialiased
  11081. */
  11082. void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
  11083. {
  11084. applyAntialiasingHint(painter, mAntialiased, QCP::aeItems);
  11085. }
  11086. /*! \internal
  11087. A convenience function which returns the selectTest value for a specified \a rect and a specified
  11088. click position \a pos. \a filledRect defines whether a click inside the rect should also be
  11089. considered a hit or whether only the rect border is sensitive to hits.
  11090. This function may be used to help with the implementation of the \ref selectTest function for
  11091. specific items.
  11092. For example, if your item consists of four rects, call this function four times, once for each
  11093. rect, in your \ref selectTest reimplementation. Finally, return the minimum (non -1) of all four
  11094. returned values.
  11095. */
  11096. double QCPAbstractItem::rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const
  11097. {
  11098. double result = -1;
  11099. // distance to border:
  11100. const QList<QLineF> lines = QList<QLineF>() << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight())
  11101. << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight());
  11102. const QCPVector2D posVec(pos);
  11103. double minDistSqr = (std::numeric_limits<double>::max)();
  11104. foreach (const QLineF &line, lines)
  11105. {
  11106. double distSqr = posVec.distanceSquaredToLine(line.p1(), line.p2());
  11107. if (distSqr < minDistSqr)
  11108. minDistSqr = distSqr;
  11109. }
  11110. result = qSqrt(minDistSqr);
  11111. // filled rect, allow click inside to count as hit:
  11112. if (filledRect && result > mParentPlot->selectionTolerance()*0.99)
  11113. {
  11114. if (rect.contains(pos))
  11115. result = mParentPlot->selectionTolerance()*0.99;
  11116. }
  11117. return result;
  11118. }
  11119. /*! \internal
  11120. Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in
  11121. item subclasses if they want to provide anchors (QCPItemAnchor).
  11122. For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor
  11123. ids and returns the respective pixel points of the specified anchor.
  11124. \see createAnchor
  11125. */
  11126. QPointF QCPAbstractItem::anchorPixelPosition(int anchorId) const
  11127. {
  11128. qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId;
  11129. return {};
  11130. }
  11131. /*! \internal
  11132. Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified
  11133. \a name must be a unique string that is usually identical to the variable name of the position
  11134. member (This is needed to provide the name-based \ref position access to positions).
  11135. Don't delete positions created by this function manually, as the item will take care of it.
  11136. Use this function in the constructor (initialization list) of the specific item subclass to
  11137. create each position member. Don't create QCPItemPositions with \b new yourself, because they
  11138. won't be registered with the item properly.
  11139. \see createAnchor
  11140. */
  11141. QCPItemPosition *QCPAbstractItem::createPosition(const QString &name)
  11142. {
  11143. if (hasAnchor(name))
  11144. qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
  11145. QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name);
  11146. mPositions.append(newPosition);
  11147. mAnchors.append(newPosition); // every position is also an anchor
  11148. newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis);
  11149. newPosition->setType(QCPItemPosition::ptPlotCoords);
  11150. if (mParentPlot->axisRect())
  11151. newPosition->setAxisRect(mParentPlot->axisRect());
  11152. newPosition->setCoords(0, 0);
  11153. return newPosition;
  11154. }
  11155. /*! \internal
  11156. Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified
  11157. \a name must be a unique string that is usually identical to the variable name of the anchor
  11158. member (This is needed to provide the name based \ref anchor access to anchors).
  11159. The \a anchorId must be a number identifying the created anchor. It is recommended to create an
  11160. enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor
  11161. to identify itself when it calls QCPAbstractItem::anchorPixelPosition. That function then returns
  11162. the correct pixel coordinates for the passed anchor id.
  11163. Don't delete anchors created by this function manually, as the item will take care of it.
  11164. Use this function in the constructor (initialization list) of the specific item subclass to
  11165. create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they
  11166. won't be registered with the item properly.
  11167. \see createPosition
  11168. */
  11169. QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId)
  11170. {
  11171. if (hasAnchor(name))
  11172. qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
  11173. QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId);
  11174. mAnchors.append(newAnchor);
  11175. return newAnchor;
  11176. }
  11177. /* inherits documentation from base class */
  11178. void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  11179. {
  11180. Q_UNUSED(event)
  11181. Q_UNUSED(details)
  11182. if (mSelectable)
  11183. {
  11184. bool selBefore = mSelected;
  11185. setSelected(additive ? !mSelected : true);
  11186. if (selectionStateChanged)
  11187. *selectionStateChanged = mSelected != selBefore;
  11188. }
  11189. }
  11190. /* inherits documentation from base class */
  11191. void QCPAbstractItem::deselectEvent(bool *selectionStateChanged)
  11192. {
  11193. if (mSelectable)
  11194. {
  11195. bool selBefore = mSelected;
  11196. setSelected(false);
  11197. if (selectionStateChanged)
  11198. *selectionStateChanged = mSelected != selBefore;
  11199. }
  11200. }
  11201. /* inherits documentation from base class */
  11202. QCP::Interaction QCPAbstractItem::selectionCategory() const
  11203. {
  11204. return QCP::iSelectItems;
  11205. }
  11206. /* end of 'src/item.cpp' */
  11207. /* including file 'src/core.cpp' */
  11208. /* modified 2021-03-29T02:30:44, size 127198 */
  11209. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11210. //////////////////// QCustomPlot
  11211. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11212. /*! \class QCustomPlot
  11213. \brief The central class of the library. This is the QWidget which displays the plot and
  11214. interacts with the user.
  11215. For tutorials on how to use QCustomPlot, see the website\n
  11216. http://www.qcustomplot.com/
  11217. */
  11218. /* start of documentation of inline functions */
  11219. /*! \fn QCPSelectionRect *QCustomPlot::selectionRect() const
  11220. Allows access to the currently used QCPSelectionRect instance (or subclass thereof), that is used
  11221. to handle and draw selection rect interactions (see \ref setSelectionRectMode).
  11222. \see setSelectionRect
  11223. */
  11224. /*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const
  11225. Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just
  11226. one cell with the main QCPAxisRect inside.
  11227. */
  11228. /* end of documentation of inline functions */
  11229. /* start of documentation of signals */
  11230. /*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event)
  11231. This signal is emitted when the QCustomPlot receives a mouse double click event.
  11232. */
  11233. /*! \fn void QCustomPlot::mousePress(QMouseEvent *event)
  11234. This signal is emitted when the QCustomPlot receives a mouse press event.
  11235. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
  11236. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
  11237. QCPAxisRect::setRangeDragAxes.
  11238. */
  11239. /*! \fn void QCustomPlot::mouseMove(QMouseEvent *event)
  11240. This signal is emitted when the QCustomPlot receives a mouse move event.
  11241. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
  11242. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
  11243. QCPAxisRect::setRangeDragAxes.
  11244. \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here,
  11245. because the dragging starting point was saved the moment the mouse was pressed. Thus it only has
  11246. a meaning for the range drag axes that were set at that moment. If you want to change the drag
  11247. axes, consider doing this in the \ref mousePress signal instead.
  11248. */
  11249. /*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event)
  11250. This signal is emitted when the QCustomPlot receives a mouse release event.
  11251. It is emitted before QCustomPlot handles any other mechanisms like object selection. So a
  11252. slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or
  11253. \ref QCPAbstractPlottable::setSelectable.
  11254. */
  11255. /*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event)
  11256. This signal is emitted when the QCustomPlot receives a mouse wheel event.
  11257. It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot
  11258. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref
  11259. QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor.
  11260. */
  11261. /*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event)
  11262. This signal is emitted when a plottable is 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 plottableDoubleClick
  11267. */
  11268. /*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event)
  11269. This signal is emitted when a plottable is double clicked.
  11270. \a event is the mouse event that caused the click and \a plottable is the plottable that received
  11271. the click. The parameter \a dataIndex indicates the data point that was closest to the click
  11272. position.
  11273. \see plottableClick
  11274. */
  11275. /*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event)
  11276. This signal is emitted when an item is clicked.
  11277. \a event is the mouse event that caused the click and \a item is the item that received the
  11278. click.
  11279. \see itemDoubleClick
  11280. */
  11281. /*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event)
  11282. This signal is emitted when an item is double clicked.
  11283. \a event is the mouse event that caused the click and \a item is the item that received the
  11284. click.
  11285. \see itemClick
  11286. */
  11287. /*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
  11288. This signal is emitted when an axis is clicked.
  11289. \a event is the mouse event that caused the click, \a axis is the axis that received the click and
  11290. \a part indicates the part of the axis that was clicked.
  11291. \see axisDoubleClick
  11292. */
  11293. /*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
  11294. This signal is emitted when an axis is double clicked.
  11295. \a event is the mouse event that caused the click, \a axis is the axis that received the click and
  11296. \a part indicates the part of the axis that was clicked.
  11297. \see axisClick
  11298. */
  11299. /*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
  11300. This signal is emitted when a legend (item) is clicked.
  11301. \a event is the mouse event that caused the click, \a legend is the legend that received the
  11302. click and \a item is the legend item that received the click. If only the legend and no item is
  11303. clicked, \a item is \c nullptr. This happens for a click inside the legend padding or the space
  11304. between two items.
  11305. \see legendDoubleClick
  11306. */
  11307. /*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
  11308. This signal is emitted when a legend (item) is double clicked.
  11309. \a event is the mouse event that caused the click, \a legend is the legend that received the
  11310. click and \a item is the legend item that received the click. If only the legend and no item is
  11311. clicked, \a item is \c nullptr. This happens for a click inside the legend padding or the space
  11312. between two items.
  11313. \see legendClick
  11314. */
  11315. /*! \fn void QCustomPlot::selectionChangedByUser()
  11316. This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by
  11317. clicking. It is not emitted when the selection state of an object has changed programmatically by
  11318. a direct call to <tt>setSelected()</tt>/<tt>setSelection()</tt> on an object or by calling \ref
  11319. deselectAll.
  11320. In addition to this signal, selectable objects also provide individual signals, for example \ref
  11321. QCPAxis::selectionChanged or \ref QCPAbstractPlottable::selectionChanged. Note that those signals
  11322. are emitted even if the selection state is changed programmatically.
  11323. See the documentation of \ref setInteractions for details about the selection mechanism.
  11324. \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends
  11325. */
  11326. /*! \fn void QCustomPlot::beforeReplot()
  11327. This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref
  11328. replot).
  11329. It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
  11330. replot synchronously, it won't cause an infinite recursion.
  11331. \see replot, afterReplot, afterLayout
  11332. */
  11333. /*! \fn void QCustomPlot::afterLayout()
  11334. This signal is emitted immediately after the layout step has been completed, which occurs right
  11335. before drawing the plot. This is typically during a call to \ref replot, and in such cases this
  11336. signal is emitted in between the signals \ref beforeReplot and \ref afterReplot. Unlike those
  11337. signals however, this signal is also emitted during off-screen painting, such as when calling
  11338. \ref toPixmap or \ref savePdf.
  11339. The layout step queries all layouts and layout elements in the plot for their proposed size and
  11340. arranges the objects accordingly as preparation for the subsequent drawing step. Through this
  11341. signal, you have the opportunity to update certain things in your plot that depend crucially on
  11342. the exact dimensions/positioning of layout elements such as axes and axis rects.
  11343. \warning However, changing any parameters of this QCustomPlot instance which would normally
  11344. affect the layouting (e.g. axis range order of magnitudes, tick label sizes, etc.) will not issue
  11345. a second run of the layout step. It will propagate directly to the draw step and may cause
  11346. graphical inconsistencies such as overlapping objects, if sizes or positions have changed.
  11347. \see updateLayout, beforeReplot, afterReplot
  11348. */
  11349. /*! \fn void QCustomPlot::afterReplot()
  11350. This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref
  11351. replot).
  11352. It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
  11353. replot synchronously, it won't cause an infinite recursion.
  11354. \see replot, beforeReplot, afterLayout
  11355. */
  11356. /* end of documentation of signals */
  11357. /* start of documentation of public members */
  11358. /*! \var QCPAxis *QCustomPlot::xAxis
  11359. A pointer to the primary x Axis (bottom) of the main axis rect of the plot.
  11360. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11361. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11362. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11363. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  11364. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  11365. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11366. axis rect), the corresponding pointers become \c nullptr.
  11367. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11368. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11369. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11370. is added after the main legend was removed before.
  11371. */
  11372. /*! \var QCPAxis *QCustomPlot::yAxis
  11373. A pointer to the primary y Axis (left) of the main axis rect of the plot.
  11374. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11375. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11376. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11377. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  11378. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  11379. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11380. axis rect), the corresponding pointers become \c nullptr.
  11381. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11382. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11383. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11384. is added after the main legend was removed before.
  11385. */
  11386. /*! \var QCPAxis *QCustomPlot::xAxis2
  11387. A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are
  11388. invisible by default. Use QCPAxis::setVisible to change this (or use \ref
  11389. QCPAxisRect::setupFullAxesBox).
  11390. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11391. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11392. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11393. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  11394. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  11395. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11396. axis rect), the corresponding pointers become \c nullptr.
  11397. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11398. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11399. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11400. is added after the main legend was removed before.
  11401. */
  11402. /*! \var QCPAxis *QCustomPlot::yAxis2
  11403. A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are
  11404. invisible by default. Use QCPAxis::setVisible to change this (or use \ref
  11405. QCPAxisRect::setupFullAxesBox).
  11406. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11407. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11408. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11409. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  11410. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  11411. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11412. axis rect), the corresponding pointers become \c nullptr.
  11413. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11414. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11415. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11416. is added after the main legend was removed before.
  11417. */
  11418. /*! \var QCPLegend *QCustomPlot::legend
  11419. A pointer to the default legend of the main axis rect. The legend is invisible by default. Use
  11420. QCPLegend::setVisible to change this.
  11421. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11422. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11423. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11424. layout system\endlink to add multiple legends to the plot, use the layout system interface to
  11425. access the new legend. For example, legends can be placed inside an axis rect's \ref
  11426. QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If
  11427. the default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11428. axis rect), the corresponding pointer becomes \c nullptr.
  11429. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11430. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11431. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11432. is added after the main legend was removed before.
  11433. */
  11434. /* end of documentation of public members */
  11435. /*!
  11436. Constructs a QCustomPlot and sets reasonable default values.
  11437. */
  11438. QCustomPlot::QCustomPlot(QWidget *parent) :
  11439. QWidget(parent),
  11440. xAxis(nullptr),
  11441. yAxis(nullptr),
  11442. xAxis2(nullptr),
  11443. yAxis2(nullptr),
  11444. legend(nullptr),
  11445. mBufferDevicePixelRatio(1.0), // will be adapted to primary screen below
  11446. mPlotLayout(nullptr),
  11447. mAutoAddPlottableToLegend(true),
  11448. mAntialiasedElements(QCP::aeNone),
  11449. mNotAntialiasedElements(QCP::aeNone),
  11450. mInteractions(QCP::iNone),
  11451. mSelectionTolerance(8),
  11452. mNoAntialiasingOnDrag(false),
  11453. mBackgroundBrush(Qt::white, Qt::SolidPattern),
  11454. mBackgroundScaled(true),
  11455. mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
  11456. mCurrentLayer(nullptr),
  11457. mPlottingHints(QCP::phCacheLabels|QCP::phImmediateRefresh),
  11458. mMultiSelectModifier(Qt::ControlModifier),
  11459. mSelectionRectMode(QCP::srmNone),
  11460. mSelectionRect(nullptr),
  11461. mOpenGl(false),
  11462. mMouseHasMoved(false),
  11463. mMouseEventLayerable(nullptr),
  11464. mMouseSignalLayerable(nullptr),
  11465. mReplotting(false),
  11466. mReplotQueued(false),
  11467. mReplotTime(0),
  11468. mReplotTimeAverage(0),
  11469. mOpenGlMultisamples(16),
  11470. mOpenGlAntialiasedElementsBackup(QCP::aeNone),
  11471. mOpenGlCacheLabelsBackup(true)
  11472. {
  11473. setAttribute(Qt::WA_NoMousePropagation);
  11474. setAttribute(Qt::WA_OpaquePaintEvent);
  11475. setFocusPolicy(Qt::ClickFocus);
  11476. setMouseTracking(true);
  11477. QLocale currentLocale = locale();
  11478. currentLocale.setNumberOptions(QLocale::OmitGroupSeparator);
  11479. setLocale(currentLocale);
  11480. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  11481. # ifdef QCP_DEVICEPIXELRATIO_FLOAT
  11482. setBufferDevicePixelRatio(QWidget::devicePixelRatioF());
  11483. # else
  11484. setBufferDevicePixelRatio(QWidget::devicePixelRatio());
  11485. # endif
  11486. #endif
  11487. mOpenGlAntialiasedElementsBackup = mAntialiasedElements;
  11488. mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels);
  11489. // create initial layers:
  11490. mLayers.append(new QCPLayer(this, QLatin1String("background")));
  11491. mLayers.append(new QCPLayer(this, QLatin1String("grid")));
  11492. mLayers.append(new QCPLayer(this, QLatin1String("main")));
  11493. mLayers.append(new QCPLayer(this, QLatin1String("axes")));
  11494. mLayers.append(new QCPLayer(this, QLatin1String("legend")));
  11495. mLayers.append(new QCPLayer(this, QLatin1String("overlay")));
  11496. updateLayerIndices();
  11497. setCurrentLayer(QLatin1String("main"));
  11498. layer(QLatin1String("overlay"))->setMode(QCPLayer::lmBuffered);
  11499. // create initial layout, axis rect and legend:
  11500. mPlotLayout = new QCPLayoutGrid;
  11501. mPlotLayout->initializeParentPlot(this);
  11502. mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry
  11503. mPlotLayout->setLayer(QLatin1String("main"));
  11504. QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true);
  11505. mPlotLayout->addElement(0, 0, defaultAxisRect);
  11506. xAxis = defaultAxisRect->axis(QCPAxis::atBottom);
  11507. yAxis = defaultAxisRect->axis(QCPAxis::atLeft);
  11508. xAxis2 = defaultAxisRect->axis(QCPAxis::atTop);
  11509. yAxis2 = defaultAxisRect->axis(QCPAxis::atRight);
  11510. legend = new QCPLegend;
  11511. legend->setVisible(false);
  11512. defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop);
  11513. defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12));
  11514. defaultAxisRect->setLayer(QLatin1String("background"));
  11515. xAxis->setLayer(QLatin1String("axes"));
  11516. yAxis->setLayer(QLatin1String("axes"));
  11517. xAxis2->setLayer(QLatin1String("axes"));
  11518. yAxis2->setLayer(QLatin1String("axes"));
  11519. xAxis->grid()->setLayer(QLatin1String("grid"));
  11520. yAxis->grid()->setLayer(QLatin1String("grid"));
  11521. xAxis2->grid()->setLayer(QLatin1String("grid"));
  11522. yAxis2->grid()->setLayer(QLatin1String("grid"));
  11523. legend->setLayer(QLatin1String("legend"));
  11524. // create selection rect instance:
  11525. mSelectionRect = new QCPSelectionRect(this);
  11526. mSelectionRect->setLayer(QLatin1String("overlay"));
  11527. setViewport(rect()); // needs to be called after mPlotLayout has been created
  11528. replot(rpQueuedReplot);
  11529. }
  11530. QCustomPlot::~QCustomPlot()
  11531. {
  11532. clearPlottables();
  11533. clearItems();
  11534. if (mPlotLayout)
  11535. {
  11536. delete mPlotLayout;
  11537. mPlotLayout = nullptr;
  11538. }
  11539. mCurrentLayer = nullptr;
  11540. qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed
  11541. mLayers.clear();
  11542. }
  11543. /*!
  11544. Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement.
  11545. This overrides the antialiasing settings for whole element groups, normally controlled with the
  11546. \a setAntialiasing function on the individual elements. If an element is neither specified in
  11547. \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
  11548. each individual element instance is used.
  11549. For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be
  11550. drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
  11551. to.
  11552. if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is
  11553. removed from there.
  11554. \see setNotAntialiasedElements
  11555. */
  11556. void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements)
  11557. {
  11558. mAntialiasedElements = antialiasedElements;
  11559. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  11560. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  11561. mNotAntialiasedElements |= ~mAntialiasedElements;
  11562. }
  11563. /*!
  11564. Sets whether the specified \a antialiasedElement is forcibly drawn antialiased.
  11565. See \ref setAntialiasedElements for details.
  11566. \see setNotAntialiasedElement
  11567. */
  11568. void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled)
  11569. {
  11570. if (!enabled && mAntialiasedElements.testFlag(antialiasedElement))
  11571. mAntialiasedElements &= ~antialiasedElement;
  11572. else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement))
  11573. mAntialiasedElements |= antialiasedElement;
  11574. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  11575. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  11576. mNotAntialiasedElements |= ~mAntialiasedElements;
  11577. }
  11578. /*!
  11579. Sets which elements are forcibly drawn not antialiased as an \a or combination of
  11580. QCP::AntialiasedElement.
  11581. This overrides the antialiasing settings for whole element groups, normally controlled with the
  11582. \a setAntialiasing function on the individual elements. If an element is neither specified in
  11583. \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
  11584. each individual element instance is used.
  11585. For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be
  11586. drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
  11587. to.
  11588. if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is
  11589. removed from there.
  11590. \see setAntialiasedElements
  11591. */
  11592. void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements &notAntialiasedElements)
  11593. {
  11594. mNotAntialiasedElements = notAntialiasedElements;
  11595. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  11596. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  11597. mAntialiasedElements |= ~mNotAntialiasedElements;
  11598. }
  11599. /*!
  11600. Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased.
  11601. See \ref setNotAntialiasedElements for details.
  11602. \see setAntialiasedElement
  11603. */
  11604. void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled)
  11605. {
  11606. if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement))
  11607. mNotAntialiasedElements &= ~notAntialiasedElement;
  11608. else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement))
  11609. mNotAntialiasedElements |= notAntialiasedElement;
  11610. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  11611. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  11612. mAntialiasedElements |= ~mNotAntialiasedElements;
  11613. }
  11614. /*!
  11615. If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the
  11616. plottable to the legend (QCustomPlot::legend).
  11617. \see addGraph, QCPLegend::addItem
  11618. */
  11619. void QCustomPlot::setAutoAddPlottableToLegend(bool on)
  11620. {
  11621. mAutoAddPlottableToLegend = on;
  11622. }
  11623. /*!
  11624. Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction
  11625. enums. There are the following types of interactions:
  11626. <b>Axis range manipulation</b> is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the
  11627. respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel.
  11628. For details how to control which axes the user may drag/zoom and in what orientations, see \ref
  11629. QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes,
  11630. \ref QCPAxisRect::setRangeZoomAxes.
  11631. <b>Plottable data selection</b> is controlled by \ref QCP::iSelectPlottables. If \ref
  11632. QCP::iSelectPlottables is set, the user may select plottables (graphs, curves, bars,...) and
  11633. their data by clicking on them or in their vicinity (\ref setSelectionTolerance). Whether the
  11634. user can actually select a plottable and its data can further be restricted with the \ref
  11635. QCPAbstractPlottable::setSelectable method on the specific plottable. For details, see the
  11636. special page about the \ref dataselection "data selection mechanism". To retrieve a list of all
  11637. currently selected plottables, call \ref selectedPlottables. If you're only interested in
  11638. QCPGraphs, you may use the convenience function \ref selectedGraphs.
  11639. <b>Item selection</b> is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user
  11640. may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find
  11641. out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of
  11642. all currently selected items, call \ref selectedItems.
  11643. <b>Axis selection</b> is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user
  11644. may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick
  11645. labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for
  11646. each axis. To retrieve a list of all axes that currently contain selected parts, call \ref
  11647. selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts().
  11648. <b>Legend selection</b> is controlled with \ref QCP::iSelectLegend. If this is set, the user may
  11649. select the legend itself or individual items by clicking on them. What parts exactly are
  11650. selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the
  11651. legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To
  11652. find out which child items are selected, call \ref QCPLegend::selectedItems.
  11653. <b>All other selectable elements</b> The selection of all other selectable objects (e.g.
  11654. QCPTextElement, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the
  11655. user may select those objects by clicking on them. To find out which are currently selected, you
  11656. need to check their selected state explicitly.
  11657. If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is
  11658. emitted. Each selectable object additionally emits an individual selectionChanged signal whenever
  11659. their selection state has changed, i.e. not only by user interaction.
  11660. To allow multiple objects to be selected by holding the selection modifier (\ref
  11661. setMultiSelectModifier), set the flag \ref QCP::iMultiSelect.
  11662. \note In addition to the selection mechanism presented here, QCustomPlot always emits
  11663. corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and
  11664. \ref plottableDoubleClick for example.
  11665. \see setInteraction, setSelectionTolerance
  11666. */
  11667. void QCustomPlot::setInteractions(const QCP::Interactions &interactions)
  11668. {
  11669. mInteractions = interactions;
  11670. }
  11671. /*!
  11672. Sets the single \a interaction of this QCustomPlot to \a enabled.
  11673. For details about the interaction system, see \ref setInteractions.
  11674. \see setInteractions
  11675. */
  11676. void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled)
  11677. {
  11678. if (!enabled && mInteractions.testFlag(interaction))
  11679. mInteractions &= ~interaction;
  11680. else if (enabled && !mInteractions.testFlag(interaction))
  11681. mInteractions |= interaction;
  11682. }
  11683. /*!
  11684. Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or
  11685. not.
  11686. If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a
  11687. potential selection when the minimum distance between the click position and the graph line is
  11688. smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks
  11689. directly inside the area and ignore this selection tolerance. In other words, it only has meaning
  11690. for parts of objects that are too thin to exactly hit with a click and thus need such a
  11691. tolerance.
  11692. \see setInteractions, QCPLayerable::selectTest
  11693. */
  11694. void QCustomPlot::setSelectionTolerance(int pixels)
  11695. {
  11696. mSelectionTolerance = pixels;
  11697. }
  11698. /*!
  11699. Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes
  11700. ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves
  11701. performance during dragging. Thus it creates a more responsive user experience. As soon as the
  11702. user stops dragging, the last replot is done with normal antialiasing, to restore high image
  11703. quality.
  11704. \see setAntialiasedElements, setNotAntialiasedElements
  11705. */
  11706. void QCustomPlot::setNoAntialiasingOnDrag(bool enabled)
  11707. {
  11708. mNoAntialiasingOnDrag = enabled;
  11709. }
  11710. /*!
  11711. Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint.
  11712. \see setPlottingHint
  11713. */
  11714. void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints)
  11715. {
  11716. mPlottingHints = hints;
  11717. }
  11718. /*!
  11719. Sets the specified plotting \a hint to \a enabled.
  11720. \see setPlottingHints
  11721. */
  11722. void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled)
  11723. {
  11724. QCP::PlottingHints newHints = mPlottingHints;
  11725. if (!enabled)
  11726. newHints &= ~hint;
  11727. else
  11728. newHints |= hint;
  11729. if (newHints != mPlottingHints)
  11730. setPlottingHints(newHints);
  11731. }
  11732. /*!
  11733. Sets the keyboard modifier that will be recognized as multi-select-modifier.
  11734. If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple
  11735. objects (or data points) by clicking on them one after the other while holding down \a modifier.
  11736. By default the multi-select-modifier is set to Qt::ControlModifier.
  11737. \see setInteractions
  11738. */
  11739. void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier)
  11740. {
  11741. mMultiSelectModifier = modifier;
  11742. }
  11743. /*!
  11744. Sets how QCustomPlot processes mouse click-and-drag interactions by the user.
  11745. If \a mode is \ref QCP::srmNone, the mouse drag is forwarded to the underlying objects. For
  11746. example, QCPAxisRect may process a mouse drag by dragging axis ranges, see \ref
  11747. QCPAxisRect::setRangeDrag. If \a mode is not \ref QCP::srmNone, the current selection rect (\ref
  11748. selectionRect) becomes activated and allows e.g. rect zooming and data point selection.
  11749. If you wish to provide your user both with axis range dragging and data selection/range zooming,
  11750. use this method to switch between the modes just before the interaction is processed, e.g. in
  11751. reaction to the \ref mousePress or \ref mouseMove signals. For example you could check whether
  11752. the user is holding a certain keyboard modifier, and then decide which \a mode shall be set.
  11753. If a selection rect interaction is currently active, and \a mode is set to \ref QCP::srmNone, the
  11754. interaction is canceled (\ref QCPSelectionRect::cancel). Switching between any of the other modes
  11755. will keep the selection rect active. Upon completion of the interaction, the behaviour is as
  11756. defined by the currently set \a mode, not the mode that was set when the interaction started.
  11757. \see setInteractions, setSelectionRect, QCPSelectionRect
  11758. */
  11759. void QCustomPlot::setSelectionRectMode(QCP::SelectionRectMode mode)
  11760. {
  11761. if (mSelectionRect)
  11762. {
  11763. if (mode == QCP::srmNone)
  11764. mSelectionRect->cancel(); // when switching to none, we immediately want to abort a potentially active selection rect
  11765. // disconnect old connections:
  11766. if (mSelectionRectMode == QCP::srmSelect)
  11767. disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
  11768. else if (mSelectionRectMode == QCP::srmZoom)
  11769. disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
  11770. // establish new ones:
  11771. if (mode == QCP::srmSelect)
  11772. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
  11773. else if (mode == QCP::srmZoom)
  11774. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
  11775. }
  11776. mSelectionRectMode = mode;
  11777. }
  11778. /*!
  11779. Sets the \ref QCPSelectionRect instance that QCustomPlot will use if \a mode is not \ref
  11780. QCP::srmNone and the user performs a click-and-drag interaction. QCustomPlot takes ownership of
  11781. the passed \a selectionRect. It can be accessed later via \ref selectionRect.
  11782. This method is useful if you wish to replace the default QCPSelectionRect instance with an
  11783. instance of a QCPSelectionRect subclass, to introduce custom behaviour of the selection rect.
  11784. \see setSelectionRectMode
  11785. */
  11786. void QCustomPlot::setSelectionRect(QCPSelectionRect *selectionRect)
  11787. {
  11788. delete mSelectionRect;
  11789. mSelectionRect = selectionRect;
  11790. if (mSelectionRect)
  11791. {
  11792. // establish connections with new selection rect:
  11793. if (mSelectionRectMode == QCP::srmSelect)
  11794. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
  11795. else if (mSelectionRectMode == QCP::srmZoom)
  11796. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
  11797. }
  11798. }
  11799. /*!
  11800. \warning This is still an experimental feature and its performance depends on the system that it
  11801. runs on. Having multiple QCustomPlot widgets in one application with enabled OpenGL rendering
  11802. might cause context conflicts on some systems.
  11803. This method allows to enable OpenGL plot rendering, for increased plotting performance of
  11804. graphically demanding plots (thick lines, translucent fills, etc.).
  11805. If \a enabled is set to true, QCustomPlot will try to initialize OpenGL and, if successful,
  11806. continue plotting with hardware acceleration. The parameter \a multisampling controls how many
  11807. samples will be used per pixel, it essentially controls the antialiasing quality. If \a
  11808. multisampling is set too high for the current graphics hardware, the maximum allowed value will
  11809. be used.
  11810. You can test whether switching to OpenGL rendering was successful by checking whether the
  11811. according getter \a QCustomPlot::openGl() returns true. If the OpenGL initialization fails,
  11812. rendering continues with the regular software rasterizer, and an according qDebug output is
  11813. generated.
  11814. If switching to OpenGL was successful, this method disables label caching (\ref setPlottingHint
  11815. "setPlottingHint(QCP::phCacheLabels, false)") and turns on QCustomPlot's antialiasing override
  11816. for all elements (\ref setAntialiasedElements "setAntialiasedElements(QCP::aeAll)"), leading to a
  11817. higher quality output. The antialiasing override allows for pixel-grid aligned drawing in the
  11818. OpenGL paint device. As stated before, in OpenGL rendering the actual antialiasing of the plot is
  11819. controlled with \a multisampling. If \a enabled is set to false, the antialiasing/label caching
  11820. settings are restored to what they were before OpenGL was enabled, if they weren't altered in the
  11821. meantime.
  11822. \note OpenGL support is only enabled if QCustomPlot is compiled with the macro \c QCUSTOMPLOT_USE_OPENGL
  11823. defined. This define must be set before including the QCustomPlot header both during compilation
  11824. of the QCustomPlot library as well as when compiling your application. It is best to just include
  11825. the line <tt>DEFINES += QCUSTOMPLOT_USE_OPENGL</tt> in the respective qmake project files.
  11826. \note If you are using a Qt version before 5.0, you must also add the module "opengl" to your \c
  11827. QT variable in the qmake project files. For Qt versions 5.0 and higher, QCustomPlot switches to a
  11828. newer OpenGL interface which is already in the "gui" module.
  11829. */
  11830. void QCustomPlot::setOpenGl(bool enabled, int multisampling)
  11831. {
  11832. mOpenGlMultisamples = qMax(0, multisampling);
  11833. #ifdef QCUSTOMPLOT_USE_OPENGL
  11834. mOpenGl = enabled;
  11835. if (mOpenGl)
  11836. {
  11837. if (setupOpenGl())
  11838. {
  11839. // backup antialiasing override and labelcaching setting so we can restore upon disabling OpenGL
  11840. mOpenGlAntialiasedElementsBackup = mAntialiasedElements;
  11841. mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels);
  11842. // set antialiasing override to antialias all (aligns gl pixel grid properly), and disable label caching (would use software rasterizer for pixmap caches):
  11843. setAntialiasedElements(QCP::aeAll);
  11844. setPlottingHint(QCP::phCacheLabels, false);
  11845. } else
  11846. {
  11847. qDebug() << Q_FUNC_INFO << "Failed to enable OpenGL, continuing plotting without hardware acceleration.";
  11848. mOpenGl = false;
  11849. }
  11850. } else
  11851. {
  11852. // restore antialiasing override and labelcaching to what it was before enabling OpenGL, if nobody changed it in the meantime:
  11853. if (mAntialiasedElements == QCP::aeAll)
  11854. setAntialiasedElements(mOpenGlAntialiasedElementsBackup);
  11855. if (!mPlottingHints.testFlag(QCP::phCacheLabels))
  11856. setPlottingHint(QCP::phCacheLabels, mOpenGlCacheLabelsBackup);
  11857. freeOpenGl();
  11858. }
  11859. // recreate all paint buffers:
  11860. mPaintBuffers.clear();
  11861. setupPaintBuffers();
  11862. #else
  11863. Q_UNUSED(enabled)
  11864. 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)";
  11865. #endif
  11866. }
  11867. /*!
  11868. Sets the viewport of this QCustomPlot. Usually users of QCustomPlot don't need to change the
  11869. viewport manually.
  11870. The viewport is the area in which the plot is drawn. All mechanisms, e.g. margin calculation take
  11871. the viewport to be the outer border of the plot. The viewport normally is the rect() of the
  11872. QCustomPlot widget, i.e. a rect with top left (0, 0) and size of the QCustomPlot widget.
  11873. Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically
  11874. an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger
  11875. and contains also the axes themselves, their tick numbers, their labels, or even additional axis
  11876. rects, color scales and other layout elements.
  11877. This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref
  11878. savePdf, etc. by temporarily changing the viewport size.
  11879. */
  11880. void QCustomPlot::setViewport(const QRect &rect)
  11881. {
  11882. mViewport = rect;
  11883. if (mPlotLayout)
  11884. mPlotLayout->setOuterRect(mViewport);
  11885. }
  11886. /*!
  11887. Sets the device pixel ratio used by the paint buffers of this QCustomPlot instance.
  11888. Normally, this doesn't need to be set manually, because it is initialized with the regular \a
  11889. QWidget::devicePixelRatio which is configured by Qt to fit the display device (e.g. 1 for normal
  11890. displays, 2 for High-DPI displays).
  11891. Device pixel ratios are supported by Qt only for Qt versions since 5.4. If this method is called
  11892. when QCustomPlot is being used with older Qt versions, outputs an according qDebug message and
  11893. leaves the internal buffer device pixel ratio at 1.0.
  11894. */
  11895. void QCustomPlot::setBufferDevicePixelRatio(double ratio)
  11896. {
  11897. if (!qFuzzyCompare(ratio, mBufferDevicePixelRatio))
  11898. {
  11899. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  11900. mBufferDevicePixelRatio = ratio;
  11901. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  11902. buffer->setDevicePixelRatio(mBufferDevicePixelRatio);
  11903. // Note: axis label cache has devicePixelRatio as part of cache hash, so no need to manually clear cache here
  11904. #else
  11905. qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
  11906. mBufferDevicePixelRatio = 1.0;
  11907. #endif
  11908. }
  11909. }
  11910. /*!
  11911. Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn
  11912. below all other objects in the plot.
  11913. For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be
  11914. enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is
  11915. preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  11916. consider using the overloaded version of this function.
  11917. If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will
  11918. first be filled with that brush, before drawing the background pixmap. This can be useful for
  11919. background pixmaps with translucent areas.
  11920. \see setBackgroundScaled, setBackgroundScaledMode
  11921. */
  11922. void QCustomPlot::setBackground(const QPixmap &pm)
  11923. {
  11924. mBackgroundPixmap = pm;
  11925. mScaledBackgroundPixmap = QPixmap();
  11926. }
  11927. /*!
  11928. Sets the background brush of the viewport (see \ref setViewport).
  11929. Before drawing everything else, the background is filled with \a brush. If a background pixmap
  11930. was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport
  11931. before the background pixmap is drawn. This can be useful for background pixmaps with translucent
  11932. areas.
  11933. Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be
  11934. useful for exporting to image formats which support transparency, e.g. \ref savePng.
  11935. \see setBackgroundScaled, setBackgroundScaledMode
  11936. */
  11937. void QCustomPlot::setBackground(const QBrush &brush)
  11938. {
  11939. mBackgroundBrush = brush;
  11940. }
  11941. /*! \overload
  11942. Allows setting the background pixmap of the viewport, whether it shall be scaled and how it
  11943. shall be scaled in one call.
  11944. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  11945. */
  11946. void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
  11947. {
  11948. mBackgroundPixmap = pm;
  11949. mScaledBackgroundPixmap = QPixmap();
  11950. mBackgroundScaled = scaled;
  11951. mBackgroundScaledMode = mode;
  11952. }
  11953. /*!
  11954. Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is
  11955. set to true, control whether and how the aspect ratio of the original pixmap is preserved with
  11956. \ref setBackgroundScaledMode.
  11957. Note that the scaled version of the original pixmap is buffered, so there is no performance
  11958. penalty on replots. (Except when the viewport dimensions are changed continuously.)
  11959. \see setBackground, setBackgroundScaledMode
  11960. */
  11961. void QCustomPlot::setBackgroundScaled(bool scaled)
  11962. {
  11963. mBackgroundScaled = scaled;
  11964. }
  11965. /*!
  11966. If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this
  11967. function to define whether and how the aspect ratio of the original pixmap is preserved.
  11968. \see setBackground, setBackgroundScaled
  11969. */
  11970. void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  11971. {
  11972. mBackgroundScaledMode = mode;
  11973. }
  11974. /*!
  11975. Returns the plottable with \a index. If the index is invalid, returns \c nullptr.
  11976. There is an overloaded version of this function with no parameter which returns the last added
  11977. plottable, see QCustomPlot::plottable()
  11978. \see plottableCount
  11979. */
  11980. QCPAbstractPlottable *QCustomPlot::plottable(int index)
  11981. {
  11982. if (index >= 0 && index < mPlottables.size())
  11983. {
  11984. return mPlottables.at(index);
  11985. } else
  11986. {
  11987. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  11988. return nullptr;
  11989. }
  11990. }
  11991. /*! \overload
  11992. Returns the last plottable that was added to the plot. If there are no plottables in the plot,
  11993. returns \c nullptr.
  11994. \see plottableCount
  11995. */
  11996. QCPAbstractPlottable *QCustomPlot::plottable()
  11997. {
  11998. if (!mPlottables.isEmpty())
  11999. {
  12000. return mPlottables.last();
  12001. } else
  12002. return nullptr;
  12003. }
  12004. /*!
  12005. Removes the specified plottable from the plot and deletes it. If necessary, the corresponding
  12006. legend item is also removed from the default legend (QCustomPlot::legend).
  12007. Returns true on success.
  12008. \see clearPlottables
  12009. */
  12010. bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable)
  12011. {
  12012. if (!mPlottables.contains(plottable))
  12013. {
  12014. qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast<quintptr>(plottable);
  12015. return false;
  12016. }
  12017. // remove plottable from legend:
  12018. plottable->removeFromLegend();
  12019. // special handling for QCPGraphs to maintain the simple graph interface:
  12020. if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable))
  12021. mGraphs.removeOne(graph);
  12022. // remove plottable:
  12023. delete plottable;
  12024. mPlottables.removeOne(plottable);
  12025. return true;
  12026. }
  12027. /*! \overload
  12028. Removes and deletes the plottable by its \a index.
  12029. */
  12030. bool QCustomPlot::removePlottable(int index)
  12031. {
  12032. if (index >= 0 && index < mPlottables.size())
  12033. return removePlottable(mPlottables[index]);
  12034. else
  12035. {
  12036. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12037. return false;
  12038. }
  12039. }
  12040. /*!
  12041. Removes all plottables from the plot and deletes them. Corresponding legend items are also
  12042. removed from the default legend (QCustomPlot::legend).
  12043. Returns the number of plottables removed.
  12044. \see removePlottable
  12045. */
  12046. int QCustomPlot::clearPlottables()
  12047. {
  12048. int c = mPlottables.size();
  12049. for (int i=c-1; i >= 0; --i)
  12050. removePlottable(mPlottables[i]);
  12051. return c;
  12052. }
  12053. /*!
  12054. Returns the number of currently existing plottables in the plot
  12055. \see plottable
  12056. */
  12057. int QCustomPlot::plottableCount() const
  12058. {
  12059. return mPlottables.size();
  12060. }
  12061. /*!
  12062. Returns a list of the selected plottables. If no plottables are currently selected, the list is empty.
  12063. There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs.
  12064. \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection
  12065. */
  12066. QList<QCPAbstractPlottable*> QCustomPlot::selectedPlottables() const
  12067. {
  12068. QList<QCPAbstractPlottable*> result;
  12069. foreach (QCPAbstractPlottable *plottable, mPlottables)
  12070. {
  12071. if (plottable->selected())
  12072. result.append(plottable);
  12073. }
  12074. return result;
  12075. }
  12076. /*!
  12077. Returns any plottable at the pixel position \a pos. Since it can capture all plottables, the
  12078. return type is the abstract base class of all plottables, QCPAbstractPlottable.
  12079. For details, and if you wish to specify a certain plottable type (e.g. QCPGraph), see the
  12080. template method plottableAt<PlottableType>()
  12081. \see plottableAt<PlottableType>(), itemAt, layoutElementAt
  12082. */
  12083. QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable, int *dataIndex) const
  12084. {
  12085. return plottableAt<QCPAbstractPlottable>(pos, onlySelectable, dataIndex);
  12086. }
  12087. /*!
  12088. Returns whether this QCustomPlot instance contains the \a plottable.
  12089. */
  12090. bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const
  12091. {
  12092. return mPlottables.contains(plottable);
  12093. }
  12094. /*!
  12095. Returns the graph with \a index. If the index is invalid, returns \c nullptr.
  12096. There is an overloaded version of this function with no parameter which returns the last created
  12097. graph, see QCustomPlot::graph()
  12098. \see graphCount, addGraph
  12099. */
  12100. QCPGraph *QCustomPlot::graph(int index) const
  12101. {
  12102. if (index >= 0 && index < mGraphs.size())
  12103. {
  12104. return mGraphs.at(index);
  12105. } else
  12106. {
  12107. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12108. return nullptr;
  12109. }
  12110. }
  12111. /*! \overload
  12112. Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot,
  12113. returns \c nullptr.
  12114. \see graphCount, addGraph
  12115. */
  12116. QCPGraph *QCustomPlot::graph() const
  12117. {
  12118. if (!mGraphs.isEmpty())
  12119. {
  12120. return mGraphs.last();
  12121. } else
  12122. return nullptr;
  12123. }
  12124. /*!
  12125. Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the
  12126. bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a
  12127. keyAxis and \a valueAxis must reside in this QCustomPlot.
  12128. \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically
  12129. "y") for the graph.
  12130. Returns a pointer to the newly created graph, or \c nullptr if adding the graph failed.
  12131. \see graph, graphCount, removeGraph, clearGraphs
  12132. */
  12133. QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis)
  12134. {
  12135. if (!keyAxis) keyAxis = xAxis;
  12136. if (!valueAxis) valueAxis = yAxis;
  12137. if (!keyAxis || !valueAxis)
  12138. {
  12139. qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)";
  12140. return nullptr;
  12141. }
  12142. if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this)
  12143. {
  12144. qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent";
  12145. return nullptr;
  12146. }
  12147. QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis);
  12148. newGraph->setName(QLatin1String("Graph ")+QString::number(mGraphs.size()));
  12149. return newGraph;
  12150. }
  12151. /*!
  12152. Removes the specified \a graph from the plot and deletes it. If necessary, the corresponding
  12153. legend item is also removed from the default legend (QCustomPlot::legend). If any other graphs in
  12154. the plot have a channel fill set towards the removed graph, the channel fill property of those
  12155. graphs is reset to \c nullptr (no channel fill).
  12156. Returns true on success.
  12157. \see clearGraphs
  12158. */
  12159. bool QCustomPlot::removeGraph(QCPGraph *graph)
  12160. {
  12161. return removePlottable(graph);
  12162. }
  12163. /*! \overload
  12164. Removes and deletes the graph by its \a index.
  12165. */
  12166. bool QCustomPlot::removeGraph(int index)
  12167. {
  12168. if (index >= 0 && index < mGraphs.size())
  12169. return removeGraph(mGraphs[index]);
  12170. else
  12171. return false;
  12172. }
  12173. /*!
  12174. Removes all graphs from the plot and deletes them. Corresponding legend items are also removed
  12175. from the default legend (QCustomPlot::legend).
  12176. Returns the number of graphs removed.
  12177. \see removeGraph
  12178. */
  12179. int QCustomPlot::clearGraphs()
  12180. {
  12181. int c = mGraphs.size();
  12182. for (int i=c-1; i >= 0; --i)
  12183. removeGraph(mGraphs[i]);
  12184. return c;
  12185. }
  12186. /*!
  12187. Returns the number of currently existing graphs in the plot
  12188. \see graph, addGraph
  12189. */
  12190. int QCustomPlot::graphCount() const
  12191. {
  12192. return mGraphs.size();
  12193. }
  12194. /*!
  12195. Returns a list of the selected graphs. If no graphs are currently selected, the list is empty.
  12196. If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars,
  12197. etc., use \ref selectedPlottables.
  12198. \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection
  12199. */
  12200. QList<QCPGraph*> QCustomPlot::selectedGraphs() const
  12201. {
  12202. QList<QCPGraph*> result;
  12203. foreach (QCPGraph *graph, mGraphs)
  12204. {
  12205. if (graph->selected())
  12206. result.append(graph);
  12207. }
  12208. return result;
  12209. }
  12210. /*!
  12211. Returns the item with \a index. If the index is invalid, returns \c nullptr.
  12212. There is an overloaded version of this function with no parameter which returns the last added
  12213. item, see QCustomPlot::item()
  12214. \see itemCount
  12215. */
  12216. QCPAbstractItem *QCustomPlot::item(int index) const
  12217. {
  12218. if (index >= 0 && index < mItems.size())
  12219. {
  12220. return mItems.at(index);
  12221. } else
  12222. {
  12223. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12224. return nullptr;
  12225. }
  12226. }
  12227. /*! \overload
  12228. Returns the last item that was added to this plot. If there are no items in the plot,
  12229. returns \c nullptr.
  12230. \see itemCount
  12231. */
  12232. QCPAbstractItem *QCustomPlot::item() const
  12233. {
  12234. if (!mItems.isEmpty())
  12235. {
  12236. return mItems.last();
  12237. } else
  12238. return nullptr;
  12239. }
  12240. /*!
  12241. Removes the specified item from the plot and deletes it.
  12242. Returns true on success.
  12243. \see clearItems
  12244. */
  12245. bool QCustomPlot::removeItem(QCPAbstractItem *item)
  12246. {
  12247. if (mItems.contains(item))
  12248. {
  12249. delete item;
  12250. mItems.removeOne(item);
  12251. return true;
  12252. } else
  12253. {
  12254. qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast<quintptr>(item);
  12255. return false;
  12256. }
  12257. }
  12258. /*! \overload
  12259. Removes and deletes the item by its \a index.
  12260. */
  12261. bool QCustomPlot::removeItem(int index)
  12262. {
  12263. if (index >= 0 && index < mItems.size())
  12264. return removeItem(mItems[index]);
  12265. else
  12266. {
  12267. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12268. return false;
  12269. }
  12270. }
  12271. /*!
  12272. Removes all items from the plot and deletes them.
  12273. Returns the number of items removed.
  12274. \see removeItem
  12275. */
  12276. int QCustomPlot::clearItems()
  12277. {
  12278. int c = mItems.size();
  12279. for (int i=c-1; i >= 0; --i)
  12280. removeItem(mItems[i]);
  12281. return c;
  12282. }
  12283. /*!
  12284. Returns the number of currently existing items in the plot
  12285. \see item
  12286. */
  12287. int QCustomPlot::itemCount() const
  12288. {
  12289. return mItems.size();
  12290. }
  12291. /*!
  12292. Returns a list of the selected items. If no items are currently selected, the list is empty.
  12293. \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected
  12294. */
  12295. QList<QCPAbstractItem*> QCustomPlot::selectedItems() const
  12296. {
  12297. QList<QCPAbstractItem*> result;
  12298. foreach (QCPAbstractItem *item, mItems)
  12299. {
  12300. if (item->selected())
  12301. result.append(item);
  12302. }
  12303. return result;
  12304. }
  12305. /*!
  12306. Returns the item at the pixel position \a pos. Since it can capture all items, the
  12307. return type is the abstract base class of all items, QCPAbstractItem.
  12308. For details, and if you wish to specify a certain item type (e.g. QCPItemLine), see the
  12309. template method itemAt<ItemType>()
  12310. \see itemAt<ItemType>(), plottableAt, layoutElementAt
  12311. */
  12312. QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const
  12313. {
  12314. return itemAt<QCPAbstractItem>(pos, onlySelectable);
  12315. }
  12316. /*!
  12317. Returns whether this QCustomPlot contains the \a item.
  12318. \see item
  12319. */
  12320. bool QCustomPlot::hasItem(QCPAbstractItem *item) const
  12321. {
  12322. return mItems.contains(item);
  12323. }
  12324. /*!
  12325. Returns the layer with the specified \a name. If there is no layer with the specified name, \c
  12326. nullptr is returned.
  12327. Layer names are case-sensitive.
  12328. \see addLayer, moveLayer, removeLayer
  12329. */
  12330. QCPLayer *QCustomPlot::layer(const QString &name) const
  12331. {
  12332. foreach (QCPLayer *layer, mLayers)
  12333. {
  12334. if (layer->name() == name)
  12335. return layer;
  12336. }
  12337. return nullptr;
  12338. }
  12339. /*! \overload
  12340. Returns the layer by \a index. If the index is invalid, \c nullptr is returned.
  12341. \see addLayer, moveLayer, removeLayer
  12342. */
  12343. QCPLayer *QCustomPlot::layer(int index) const
  12344. {
  12345. if (index >= 0 && index < mLayers.size())
  12346. {
  12347. return mLayers.at(index);
  12348. } else
  12349. {
  12350. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12351. return nullptr;
  12352. }
  12353. }
  12354. /*!
  12355. Returns the layer that is set as current layer (see \ref setCurrentLayer).
  12356. */
  12357. QCPLayer *QCustomPlot::currentLayer() const
  12358. {
  12359. return mCurrentLayer;
  12360. }
  12361. /*!
  12362. Sets the layer with the specified \a name to be the current layer. All layerables (\ref
  12363. QCPLayerable), e.g. plottables and items, are created on the current layer.
  12364. Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot.
  12365. Layer names are case-sensitive.
  12366. \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer
  12367. */
  12368. bool QCustomPlot::setCurrentLayer(const QString &name)
  12369. {
  12370. if (QCPLayer *newCurrentLayer = layer(name))
  12371. {
  12372. return setCurrentLayer(newCurrentLayer);
  12373. } else
  12374. {
  12375. qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name;
  12376. return false;
  12377. }
  12378. }
  12379. /*! \overload
  12380. Sets the provided \a layer to be the current layer.
  12381. Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot.
  12382. \see addLayer, moveLayer, removeLayer
  12383. */
  12384. bool QCustomPlot::setCurrentLayer(QCPLayer *layer)
  12385. {
  12386. if (!mLayers.contains(layer))
  12387. {
  12388. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  12389. return false;
  12390. }
  12391. mCurrentLayer = layer;
  12392. return true;
  12393. }
  12394. /*!
  12395. Returns the number of currently existing layers in the plot
  12396. \see layer, addLayer
  12397. */
  12398. int QCustomPlot::layerCount() const
  12399. {
  12400. return mLayers.size();
  12401. }
  12402. /*!
  12403. Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which
  12404. must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer.
  12405. Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a
  12406. valid layer inside this QCustomPlot.
  12407. If \a otherLayer is 0, the highest layer in the QCustomPlot will be used.
  12408. For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer.
  12409. \see layer, moveLayer, removeLayer
  12410. */
  12411. bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
  12412. {
  12413. if (!otherLayer)
  12414. otherLayer = mLayers.last();
  12415. if (!mLayers.contains(otherLayer))
  12416. {
  12417. qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
  12418. return false;
  12419. }
  12420. if (layer(name))
  12421. {
  12422. qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name;
  12423. return false;
  12424. }
  12425. QCPLayer *newLayer = new QCPLayer(this, name);
  12426. mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer);
  12427. updateLayerIndices();
  12428. setupPaintBuffers(); // associates new layer with the appropriate paint buffer
  12429. return true;
  12430. }
  12431. /*!
  12432. Removes the specified \a layer and returns true on success.
  12433. All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below
  12434. \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both
  12435. cases, the total rendering order of all layerables in the QCustomPlot is preserved.
  12436. If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom
  12437. layer) becomes the new current layer.
  12438. It is not possible to remove the last layer of the plot.
  12439. \see layer, addLayer, moveLayer
  12440. */
  12441. bool QCustomPlot::removeLayer(QCPLayer *layer)
  12442. {
  12443. if (!mLayers.contains(layer))
  12444. {
  12445. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  12446. return false;
  12447. }
  12448. if (mLayers.size() < 2)
  12449. {
  12450. qDebug() << Q_FUNC_INFO << "can't remove last layer";
  12451. return false;
  12452. }
  12453. // append all children of this layer to layer below (if this is lowest layer, prepend to layer above)
  12454. int removedIndex = layer->index();
  12455. bool isFirstLayer = removedIndex==0;
  12456. QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1);
  12457. QList<QCPLayerable*> children = layer->children();
  12458. if (isFirstLayer) // prepend in reverse order (such that relative order stays the same)
  12459. std::reverse(children.begin(), children.end());
  12460. foreach (QCPLayerable *child, children)
  12461. child->moveToLayer(targetLayer, isFirstLayer); // prepend if isFirstLayer, otherwise append
  12462. // if removed layer is current layer, change current layer to layer below/above:
  12463. if (layer == mCurrentLayer)
  12464. setCurrentLayer(targetLayer);
  12465. // invalidate the paint buffer that was responsible for this layer:
  12466. if (QSharedPointer<QCPAbstractPaintBuffer> pb = layer->mPaintBuffer.toStrongRef())
  12467. pb->setInvalidated();
  12468. // remove layer:
  12469. delete layer;
  12470. mLayers.removeOne(layer);
  12471. updateLayerIndices();
  12472. return true;
  12473. }
  12474. /*!
  12475. Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or
  12476. below is controlled with \a insertMode.
  12477. Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the
  12478. QCustomPlot.
  12479. \see layer, addLayer, moveLayer
  12480. */
  12481. bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
  12482. {
  12483. if (!mLayers.contains(layer))
  12484. {
  12485. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  12486. return false;
  12487. }
  12488. if (!mLayers.contains(otherLayer))
  12489. {
  12490. qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
  12491. return false;
  12492. }
  12493. if (layer->index() > otherLayer->index())
  12494. mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0));
  12495. else if (layer->index() < otherLayer->index())
  12496. mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 0:-1));
  12497. // invalidate the paint buffers that are responsible for the layers:
  12498. if (QSharedPointer<QCPAbstractPaintBuffer> pb = layer->mPaintBuffer.toStrongRef())
  12499. pb->setInvalidated();
  12500. if (QSharedPointer<QCPAbstractPaintBuffer> pb = otherLayer->mPaintBuffer.toStrongRef())
  12501. pb->setInvalidated();
  12502. updateLayerIndices();
  12503. return true;
  12504. }
  12505. /*!
  12506. Returns the number of axis rects in the plot.
  12507. All axis rects can be accessed via QCustomPlot::axisRect().
  12508. Initially, only one axis rect exists in the plot.
  12509. \see axisRect, axisRects
  12510. */
  12511. int QCustomPlot::axisRectCount() const
  12512. {
  12513. return axisRects().size();
  12514. }
  12515. /*!
  12516. Returns the axis rect with \a index.
  12517. Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were
  12518. added, all of them may be accessed with this function in a linear fashion (even when they are
  12519. nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout).
  12520. The order of the axis rects is given by the fill order of the \ref QCPLayout that is holding
  12521. them. For example, if the axis rects are in the top level grid layout (accessible via \ref
  12522. QCustomPlot::plotLayout), they are ordered from left to right, top to bottom, if the layout's
  12523. default \ref QCPLayoutGrid::setFillOrder "setFillOrder" of \ref QCPLayoutGrid::foColumnsFirst
  12524. "foColumnsFirst" wasn't changed.
  12525. If you want to access axis rects by their row and column index, use the layout interface. For
  12526. example, use \ref QCPLayoutGrid::element of the top level grid layout, and \c qobject_cast the
  12527. returned layout element to \ref QCPAxisRect. (See also \ref thelayoutsystem.)
  12528. \see axisRectCount, axisRects, QCPLayoutGrid::setFillOrder
  12529. */
  12530. QCPAxisRect *QCustomPlot::axisRect(int index) const
  12531. {
  12532. const QList<QCPAxisRect*> rectList = axisRects();
  12533. if (index >= 0 && index < rectList.size())
  12534. {
  12535. return rectList.at(index);
  12536. } else
  12537. {
  12538. // qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index;
  12539. return nullptr;
  12540. }
  12541. }
  12542. /*!
  12543. Returns all axis rects in the plot.
  12544. The order of the axis rects is given by the fill order of the \ref QCPLayout that is holding
  12545. them. For example, if the axis rects are in the top level grid layout (accessible via \ref
  12546. QCustomPlot::plotLayout), they are ordered from left to right, top to bottom, if the layout's
  12547. default \ref QCPLayoutGrid::setFillOrder "setFillOrder" of \ref QCPLayoutGrid::foColumnsFirst
  12548. "foColumnsFirst" wasn't changed.
  12549. \see axisRectCount, axisRect, QCPLayoutGrid::setFillOrder
  12550. */
  12551. QList<QCPAxisRect*> QCustomPlot::axisRects() const
  12552. {
  12553. QList<QCPAxisRect*> result;
  12554. QStack<QCPLayoutElement*> elementStack;
  12555. if (mPlotLayout)
  12556. elementStack.push(mPlotLayout);
  12557. while (!elementStack.isEmpty())
  12558. {
  12559. foreach (QCPLayoutElement *element, elementStack.pop()->elements(false))
  12560. {
  12561. if (element)
  12562. {
  12563. elementStack.push(element);
  12564. if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(element))
  12565. result.append(ar);
  12566. }
  12567. }
  12568. }
  12569. return result;
  12570. }
  12571. /*!
  12572. Returns the layout element at pixel position \a pos. If there is no element at that position,
  12573. returns \c nullptr.
  12574. Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on
  12575. any of its parent elements is set to false, it will not be considered.
  12576. \see itemAt, plottableAt
  12577. */
  12578. QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const
  12579. {
  12580. QCPLayoutElement *currentElement = mPlotLayout;
  12581. bool searchSubElements = true;
  12582. while (searchSubElements && currentElement)
  12583. {
  12584. searchSubElements = false;
  12585. foreach (QCPLayoutElement *subElement, currentElement->elements(false))
  12586. {
  12587. if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
  12588. {
  12589. currentElement = subElement;
  12590. searchSubElements = true;
  12591. break;
  12592. }
  12593. }
  12594. }
  12595. return currentElement;
  12596. }
  12597. /*!
  12598. Returns the layout element of type \ref QCPAxisRect at pixel position \a pos. This method ignores
  12599. other layout elements even if they are visually in front of the axis rect (e.g. a \ref
  12600. QCPLegend). If there is no axis rect at that position, returns \c nullptr.
  12601. Only visible axis rects are used. If \ref QCPLayoutElement::setVisible on the axis rect itself or
  12602. on any of its parent elements is set to false, it will not be considered.
  12603. \see layoutElementAt
  12604. */
  12605. QCPAxisRect *QCustomPlot::axisRectAt(const QPointF &pos) const
  12606. {
  12607. QCPAxisRect *result = nullptr;
  12608. QCPLayoutElement *currentElement = mPlotLayout;
  12609. bool searchSubElements = true;
  12610. while (searchSubElements && currentElement)
  12611. {
  12612. searchSubElements = false;
  12613. foreach (QCPLayoutElement *subElement, currentElement->elements(false))
  12614. {
  12615. if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
  12616. {
  12617. currentElement = subElement;
  12618. searchSubElements = true;
  12619. if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(currentElement))
  12620. result = ar;
  12621. break;
  12622. }
  12623. }
  12624. }
  12625. return result;
  12626. }
  12627. /*!
  12628. Returns the axes that currently have selected parts, i.e. whose selection state is not \ref
  12629. QCPAxis::spNone.
  12630. \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts,
  12631. QCPAxis::setSelectableParts
  12632. */
  12633. QList<QCPAxis*> QCustomPlot::selectedAxes() const
  12634. {
  12635. QList<QCPAxis*> result, allAxes;
  12636. foreach (QCPAxisRect *rect, axisRects())
  12637. allAxes << rect->axes();
  12638. foreach (QCPAxis *axis, allAxes)
  12639. {
  12640. if (axis->selectedParts() != QCPAxis::spNone)
  12641. result.append(axis);
  12642. }
  12643. return result;
  12644. }
  12645. /*!
  12646. Returns the legends that currently have selected parts, i.e. whose selection state is not \ref
  12647. QCPLegend::spNone.
  12648. \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts,
  12649. QCPLegend::setSelectableParts, QCPLegend::selectedItems
  12650. */
  12651. QList<QCPLegend*> QCustomPlot::selectedLegends() const
  12652. {
  12653. QList<QCPLegend*> result;
  12654. QStack<QCPLayoutElement*> elementStack;
  12655. if (mPlotLayout)
  12656. elementStack.push(mPlotLayout);
  12657. while (!elementStack.isEmpty())
  12658. {
  12659. foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false))
  12660. {
  12661. if (subElement)
  12662. {
  12663. elementStack.push(subElement);
  12664. if (QCPLegend *leg = qobject_cast<QCPLegend*>(subElement))
  12665. {
  12666. if (leg->selectedParts() != QCPLegend::spNone)
  12667. result.append(leg);
  12668. }
  12669. }
  12670. }
  12671. }
  12672. return result;
  12673. }
  12674. /*!
  12675. Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot.
  12676. Since calling this function is not a user interaction, this does not emit the \ref
  12677. selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the
  12678. objects were previously selected.
  12679. \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends
  12680. */
  12681. void QCustomPlot::deselectAll()
  12682. {
  12683. foreach (QCPLayer *layer, mLayers)
  12684. {
  12685. foreach (QCPLayerable *layerable, layer->children())
  12686. layerable->deselectEvent(nullptr);
  12687. }
  12688. }
  12689. /*!
  12690. Causes a complete replot into the internal paint buffer(s). Finally, the widget surface is
  12691. refreshed with the new buffer contents. This is the method that must be called to make changes to
  12692. the plot, e.g. on the axis ranges or data points of graphs, visible.
  12693. The parameter \a refreshPriority can be used to fine-tune the timing of the replot. For example
  12694. if your application calls \ref replot very quickly in succession (e.g. multiple independent
  12695. functions change some aspects of the plot and each wants to make sure the change gets replotted),
  12696. it is advisable to set \a refreshPriority to \ref QCustomPlot::rpQueuedReplot. This way, the
  12697. actual replotting is deferred to the next event loop iteration. Multiple successive calls of \ref
  12698. replot with this priority will only cause a single replot, avoiding redundant replots and
  12699. improving performance.
  12700. Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the
  12701. QCustomPlot widget and user interactions (object selection and range dragging/zooming).
  12702. Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref
  12703. afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two
  12704. signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite
  12705. recursion.
  12706. If a layer is in mode \ref QCPLayer::lmBuffered (\ref QCPLayer::setMode), it is also possible to
  12707. replot only that specific layer via \ref QCPLayer::replot. See the documentation there for
  12708. details.
  12709. \see replotTime
  12710. */
  12711. void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority)
  12712. {
  12713. if (refreshPriority == QCustomPlot::rpQueuedReplot)
  12714. {
  12715. if (!mReplotQueued)
  12716. {
  12717. mReplotQueued = true;
  12718. QTimer::singleShot(0, this, SLOT(replot()));
  12719. }
  12720. return;
  12721. }
  12722. if (mReplotting) // incase signals loop back to replot slot
  12723. return;
  12724. mReplotting = true;
  12725. mReplotQueued = false;
  12726. emit beforeReplot();
  12727. # if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
  12728. QTime replotTimer;
  12729. replotTimer.start();
  12730. # else
  12731. QElapsedTimer replotTimer;
  12732. replotTimer.start();
  12733. # endif
  12734. updateLayout();
  12735. // draw all layered objects (grid, axes, plottables, items, legend,...) into their buffers:
  12736. setupPaintBuffers();
  12737. foreach (QCPLayer *layer, mLayers)
  12738. layer->drawToPaintBuffer();
  12739. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  12740. buffer->setInvalidated(false);
  12741. if ((refreshPriority == rpRefreshHint && mPlottingHints.testFlag(QCP::phImmediateRefresh)) || refreshPriority==rpImmediateRefresh)
  12742. repaint();
  12743. else
  12744. update();
  12745. # if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
  12746. mReplotTime = replotTimer.elapsed();
  12747. # else
  12748. mReplotTime = replotTimer.nsecsElapsed()*1e-6;
  12749. # endif
  12750. if (!qFuzzyIsNull(mReplotTimeAverage))
  12751. mReplotTimeAverage = mReplotTimeAverage*0.9 + mReplotTime*0.1; // exponential moving average with a time constant of 10 last replots
  12752. else
  12753. mReplotTimeAverage = mReplotTime; // no previous replots to average with, so initialize with replot time
  12754. emit afterReplot();
  12755. mReplotting = false;
  12756. }
  12757. /*!
  12758. Returns the time in milliseconds that the last replot took. If \a average is set to true, an
  12759. exponential moving average over the last couple of replots is returned.
  12760. \see replot
  12761. */
  12762. double QCustomPlot::replotTime(bool average) const
  12763. {
  12764. return average ? mReplotTimeAverage : mReplotTime;
  12765. }
  12766. /*!
  12767. Rescales the axes such that all plottables (like graphs) in the plot are fully visible.
  12768. if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true
  12769. (QCPLayerable::setVisible), will be used to rescale the axes.
  12770. \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale
  12771. */
  12772. void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables)
  12773. {
  12774. QList<QCPAxis*> allAxes;
  12775. foreach (QCPAxisRect *rect, axisRects())
  12776. allAxes << rect->axes();
  12777. foreach (QCPAxis *axis, allAxes)
  12778. axis->rescale(onlyVisiblePlottables);
  12779. }
  12780. /*!
  12781. Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale
  12782. of texts and lines will be derived from the specified \a width and \a height. This means, the
  12783. output will look like the normal on-screen output of a QCustomPlot widget with the corresponding
  12784. pixel width and height. If either \a width or \a height is zero, the exported image will have the
  12785. same dimensions as the QCustomPlot widget currently has.
  12786. Setting \a exportPen to \ref QCP::epNoCosmetic allows to disable the use of cosmetic pens when
  12787. drawing to the PDF file. Cosmetic pens are pens with numerical width 0, which are always drawn as
  12788. a one pixel wide line, no matter what zoom factor is set in the PDF-Viewer. For more information
  12789. about cosmetic pens, see the QPainter and QPen documentation.
  12790. The objects of the plot will appear in the current selection state. If you don't want any
  12791. selected objects to be painted in their selected look, deselect everything with \ref deselectAll
  12792. before calling this function.
  12793. Returns true on success.
  12794. \warning
  12795. \li If you plan on editing the exported PDF file with a vector graphics editor like Inkscape, it
  12796. is advised to set \a exportPen to \ref QCP::epNoCosmetic to avoid losing those cosmetic lines
  12797. (which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks).
  12798. \li If calling this function inside the constructor of the parent of the QCustomPlot widget
  12799. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12800. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12801. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12802. aren't defined yet inside the constructor, so you would get an image that has strange
  12803. widths/heights.
  12804. \a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting
  12805. PDF file.
  12806. \note On Android systems, this method does nothing and issues an according qDebug warning
  12807. message. This is also the case if for other reasons the define flag \c QT_NO_PRINTER is set.
  12808. \see savePng, saveBmp, saveJpg, saveRastered
  12809. */
  12810. bool QCustomPlot::savePdf(const QString &fileName, int width, int height, QCP::ExportPen exportPen, const QString &pdfCreator, const QString &pdfTitle)
  12811. {
  12812. bool success = false;
  12813. #ifdef QT_NO_PRINTER
  12814. Q_UNUSED(fileName)
  12815. Q_UNUSED(exportPen)
  12816. Q_UNUSED(width)
  12817. Q_UNUSED(height)
  12818. Q_UNUSED(pdfCreator)
  12819. Q_UNUSED(pdfTitle)
  12820. qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created.";
  12821. #else
  12822. int newWidth, newHeight;
  12823. if (width == 0 || height == 0)
  12824. {
  12825. newWidth = this->width();
  12826. newHeight = this->height();
  12827. } else
  12828. {
  12829. newWidth = width;
  12830. newHeight = height;
  12831. }
  12832. QPrinter printer(QPrinter::ScreenResolution);
  12833. printer.setOutputFileName(fileName);
  12834. printer.setOutputFormat(QPrinter::PdfFormat);
  12835. printer.setColorMode(QPrinter::Color);
  12836. printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator);
  12837. printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle);
  12838. QRect oldViewport = viewport();
  12839. setViewport(QRect(0, 0, newWidth, newHeight));
  12840. #if QT_VERSION < QT_VERSION_CHECK(5, 3, 0)
  12841. printer.setFullPage(true);
  12842. printer.setPaperSize(viewport().size(), QPrinter::DevicePixel);
  12843. #else
  12844. QPageLayout pageLayout;
  12845. pageLayout.setMode(QPageLayout::FullPageMode);
  12846. pageLayout.setOrientation(QPageLayout::Portrait);
  12847. pageLayout.setMargins(QMarginsF(0, 0, 0, 0));
  12848. pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch));
  12849. printer.setPageLayout(pageLayout);
  12850. #endif
  12851. QCPPainter printpainter;
  12852. if (printpainter.begin(&printer))
  12853. {
  12854. printpainter.setMode(QCPPainter::pmVectorized);
  12855. printpainter.setMode(QCPPainter::pmNoCaching);
  12856. printpainter.setMode(QCPPainter::pmNonCosmetic, exportPen==QCP::epNoCosmetic);
  12857. printpainter.setWindow(mViewport);
  12858. if (mBackgroundBrush.style() != Qt::NoBrush &&
  12859. mBackgroundBrush.color() != Qt::white &&
  12860. mBackgroundBrush.color() != Qt::transparent &&
  12861. mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent
  12862. printpainter.fillRect(viewport(), mBackgroundBrush);
  12863. draw(&printpainter);
  12864. printpainter.end();
  12865. success = true;
  12866. }
  12867. setViewport(oldViewport);
  12868. #endif // QT_NO_PRINTER
  12869. return success;
  12870. }
  12871. /*!
  12872. Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width
  12873. and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
  12874. current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
  12875. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
  12876. parameter.
  12877. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  12878. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  12879. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  12880. 200*200 pixel resolution.
  12881. If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
  12882. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  12883. QCustomPlot to place objects with sub-pixel accuracy.
  12884. image compression can be controlled with the \a quality parameter which must be between 0 and 100
  12885. or -1 to use the default setting.
  12886. The \a resolution will be written to the image file header and has no direct consequence for the
  12887. quality or the pixel size. However, if opening the image with a tool which respects the metadata,
  12888. it will be able to scale the image to match either a given size in real units of length (inch,
  12889. centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
  12890. given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
  12891. resolution unit internally.
  12892. Returns true on success. If this function fails, most likely the PNG format isn't supported by
  12893. the system, see Qt docs about QImageWriter::supportedImageFormats().
  12894. The objects of the plot will appear in the current selection state. If you don't want any selected
  12895. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  12896. this function.
  12897. If you want the PNG to have a transparent background, call \ref setBackground(const QBrush &brush)
  12898. with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving.
  12899. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  12900. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12901. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12902. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12903. aren't defined yet inside the constructor, so you would get an image that has strange
  12904. widths/heights.
  12905. \see savePdf, saveBmp, saveJpg, saveRastered
  12906. */
  12907. bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
  12908. {
  12909. return saveRastered(fileName, width, height, scale, "PNG", quality, resolution, resolutionUnit);
  12910. }
  12911. /*!
  12912. Saves a JPEG image file to \a fileName on disc. The output plot will have the dimensions \a width
  12913. and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
  12914. current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
  12915. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
  12916. parameter.
  12917. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  12918. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  12919. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  12920. 200*200 pixel resolution.
  12921. If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
  12922. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  12923. QCustomPlot to place objects with sub-pixel accuracy.
  12924. image compression can be controlled with the \a quality parameter which must be between 0 and 100
  12925. or -1 to use the default setting.
  12926. The \a resolution will be written to the image file header and has no direct consequence for the
  12927. quality or the pixel size. However, if opening the image with a tool which respects the metadata,
  12928. it will be able to scale the image to match either a given size in real units of length (inch,
  12929. centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
  12930. given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
  12931. resolution unit internally.
  12932. Returns true on success. If this function fails, most likely the JPEG format isn't supported by
  12933. the system, see Qt docs about QImageWriter::supportedImageFormats().
  12934. The objects of the plot will appear in the current selection state. If you don't want any selected
  12935. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  12936. this function.
  12937. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  12938. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12939. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12940. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12941. aren't defined yet inside the constructor, so you would get an image that has strange
  12942. widths/heights.
  12943. \see savePdf, savePng, saveBmp, saveRastered
  12944. */
  12945. bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
  12946. {
  12947. return saveRastered(fileName, width, height, scale, "JPG", quality, resolution, resolutionUnit);
  12948. }
  12949. /*!
  12950. Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width
  12951. and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
  12952. current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
  12953. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
  12954. parameter.
  12955. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  12956. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  12957. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  12958. 200*200 pixel resolution.
  12959. If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
  12960. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  12961. QCustomPlot to place objects with sub-pixel accuracy.
  12962. The \a resolution will be written to the image file header and has no direct consequence for the
  12963. quality or the pixel size. However, if opening the image with a tool which respects the metadata,
  12964. it will be able to scale the image to match either a given size in real units of length (inch,
  12965. centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
  12966. given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
  12967. resolution unit internally.
  12968. Returns true on success. If this function fails, most likely the BMP format isn't supported by
  12969. the system, see Qt docs about QImageWriter::supportedImageFormats().
  12970. The objects of the plot will appear in the current selection state. If you don't want any selected
  12971. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  12972. this function.
  12973. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  12974. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12975. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12976. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12977. aren't defined yet inside the constructor, so you would get an image that has strange
  12978. widths/heights.
  12979. \see savePdf, savePng, saveJpg, saveRastered
  12980. */
  12981. bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale, int resolution, QCP::ResolutionUnit resolutionUnit)
  12982. {
  12983. return saveRastered(fileName, width, height, scale, "BMP", -1, resolution, resolutionUnit);
  12984. }
  12985. /*! \internal
  12986. Returns a minimum size hint that corresponds to the minimum size of the top level layout
  12987. (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum
  12988. size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot.
  12989. This is especially important, when placed in a QLayout where other components try to take in as
  12990. much space as possible (e.g. QMdiArea).
  12991. */
  12992. QSize QCustomPlot::minimumSizeHint() const
  12993. {
  12994. return mPlotLayout->minimumOuterSizeHint().toSize();
  12995. }
  12996. /*! \internal
  12997. Returns a size hint that is the same as \ref minimumSizeHint.
  12998. */
  12999. QSize QCustomPlot::sizeHint() const
  13000. {
  13001. return mPlotLayout->minimumOuterSizeHint().toSize();
  13002. }
  13003. /*! \internal
  13004. Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but
  13005. draws the internal buffer on the widget surface.
  13006. */
  13007. void QCustomPlot::paintEvent(QPaintEvent *event)
  13008. {
  13009. Q_UNUSED(event)
  13010. QCPPainter painter(this);
  13011. if (painter.isActive())
  13012. {
  13013. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  13014. painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem
  13015. #endif
  13016. if (mBackgroundBrush.style() != Qt::NoBrush)
  13017. painter.fillRect(mViewport, mBackgroundBrush);
  13018. drawBackground(&painter);
  13019. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  13020. buffer->draw(&painter);
  13021. }
  13022. }
  13023. /*! \internal
  13024. Event handler for a resize of the QCustomPlot widget. The viewport (which becomes the outer rect
  13025. of mPlotLayout) is resized appropriately. Finally a \ref replot is performed.
  13026. */
  13027. void QCustomPlot::resizeEvent(QResizeEvent *event)
  13028. {
  13029. Q_UNUSED(event)
  13030. // resize and repaint the buffer:
  13031. setViewport(rect());
  13032. replot(rpQueuedRefresh); // queued refresh is important here, to prevent painting issues in some contexts (e.g. MDI subwindow)
  13033. }
  13034. /*! \internal
  13035. Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then
  13036. determines the layerable under the cursor and forwards the event to it. Finally, emits the
  13037. specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref
  13038. axisDoubleClick, etc.).
  13039. \see mousePressEvent, mouseReleaseEvent
  13040. */
  13041. void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event)
  13042. {
  13043. emit mouseDoubleClick(event);
  13044. mMouseHasMoved = false;
  13045. mMousePressPos = event->pos();
  13046. // determine layerable under the cursor (this event is called instead of the second press event in a double-click):
  13047. QList<QVariant> details;
  13048. QList<QCPLayerable*> candidates = layerableListAt(mMousePressPos, false, &details);
  13049. for (int i=0; i<candidates.size(); ++i)
  13050. {
  13051. event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
  13052. candidates.at(i)->mouseDoubleClickEvent(event, details.at(i));
  13053. if (event->isAccepted())
  13054. {
  13055. mMouseEventLayerable = candidates.at(i);
  13056. mMouseEventLayerableDetails = details.at(i);
  13057. break;
  13058. }
  13059. }
  13060. // emit specialized object double click signals:
  13061. if (!candidates.isEmpty())
  13062. {
  13063. if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(candidates.first()))
  13064. {
  13065. int dataIndex = 0;
  13066. if (!details.first().value<QCPDataSelection>().isEmpty())
  13067. dataIndex = details.first().value<QCPDataSelection>().dataRange().begin();
  13068. emit plottableDoubleClick(ap, dataIndex, event);
  13069. } else if (QCPAxis *ax = qobject_cast<QCPAxis*>(candidates.first()))
  13070. emit axisDoubleClick(ax, details.first().value<QCPAxis::SelectablePart>(), event);
  13071. else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(candidates.first()))
  13072. emit itemDoubleClick(ai, event);
  13073. else if (QCPLegend *lg = qobject_cast<QCPLegend*>(candidates.first()))
  13074. emit legendDoubleClick(lg, nullptr, event);
  13075. else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(candidates.first()))
  13076. emit legendDoubleClick(li->parentLegend(), li, event);
  13077. }
  13078. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13079. }
  13080. /*! \internal
  13081. Event handler for when a mouse button is pressed. Emits the mousePress signal.
  13082. If the current \ref setSelectionRectMode is not \ref QCP::srmNone, passes the event to the
  13083. selection rect. Otherwise determines the layerable under the cursor and forwards the event to it.
  13084. \see mouseMoveEvent, mouseReleaseEvent
  13085. */
  13086. void QCustomPlot::mousePressEvent(QMouseEvent *event)
  13087. {
  13088. emit mousePress(event);
  13089. // save some state to tell in releaseEvent whether it was a click:
  13090. mMouseHasMoved = false;
  13091. mMousePressPos = event->pos();
  13092. if (mSelectionRect && mSelectionRectMode != QCP::srmNone)
  13093. {
  13094. if (mSelectionRectMode != QCP::srmZoom || qobject_cast<QCPAxisRect*>(axisRectAt(mMousePressPos))) // in zoom mode only activate selection rect if on an axis rect
  13095. mSelectionRect->startSelection(event);
  13096. } else
  13097. {
  13098. // no selection rect interaction, prepare for click signal emission and forward event to layerable under the cursor:
  13099. QList<QVariant> details;
  13100. QList<QCPLayerable*> candidates = layerableListAt(mMousePressPos, false, &details);
  13101. if (!candidates.isEmpty())
  13102. {
  13103. mMouseSignalLayerable = candidates.first(); // candidate for signal emission is always topmost hit layerable (signal emitted in release event)
  13104. mMouseSignalLayerableDetails = details.first();
  13105. }
  13106. // forward event to topmost candidate which accepts the event:
  13107. for (int i=0; i<candidates.size(); ++i)
  13108. {
  13109. event->accept(); // default impl of QCPLayerable's mouse events call ignore() on the event, in that case propagate to next candidate in list
  13110. candidates.at(i)->mousePressEvent(event, details.at(i));
  13111. if (event->isAccepted())
  13112. {
  13113. mMouseEventLayerable = candidates.at(i);
  13114. mMouseEventLayerableDetails = details.at(i);
  13115. break;
  13116. }
  13117. }
  13118. }
  13119. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13120. }
  13121. /*! \internal
  13122. Event handler for when the cursor is moved. Emits the \ref mouseMove signal.
  13123. If the selection rect (\ref setSelectionRect) is currently active, the event is forwarded to it
  13124. in order to update the rect geometry.
  13125. Otherwise, if a layout element has mouse capture focus (a mousePressEvent happened on top of the
  13126. layout element before), the mouseMoveEvent is forwarded to that element.
  13127. \see mousePressEvent, mouseReleaseEvent
  13128. */
  13129. void QCustomPlot::mouseMoveEvent(QMouseEvent *event)
  13130. {
  13131. emit mouseMove(event);
  13132. if (!mMouseHasMoved && (mMousePressPos-event->pos()).manhattanLength() > 3)
  13133. mMouseHasMoved = true; // moved too far from mouse press position, don't handle as click on mouse release
  13134. if (mSelectionRect && mSelectionRect->isActive())
  13135. mSelectionRect->moveSelection(event);
  13136. else if (mMouseEventLayerable) // call event of affected layerable:
  13137. mMouseEventLayerable->mouseMoveEvent(event, mMousePressPos);
  13138. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13139. }
  13140. /*! \internal
  13141. Event handler for when a mouse button is released. Emits the \ref mouseRelease signal.
  13142. If the mouse was moved less than a certain threshold in any direction since the \ref
  13143. mousePressEvent, it is considered a click which causes the selection mechanism (if activated via
  13144. \ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse
  13145. click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.)
  13146. If a layerable is the mouse capturer (a \ref mousePressEvent happened on top of the layerable
  13147. before), the \ref mouseReleaseEvent is forwarded to that element.
  13148. \see mousePressEvent, mouseMoveEvent
  13149. */
  13150. void QCustomPlot::mouseReleaseEvent(QMouseEvent *event)
  13151. {
  13152. emit mouseRelease(event);
  13153. if (!mMouseHasMoved) // mouse hasn't moved (much) between press and release, so handle as click
  13154. {
  13155. emit mouseClick(event);
  13156. if (mSelectionRect && mSelectionRect->isActive()) // a simple click shouldn't successfully finish a selection rect, so cancel it here
  13157. mSelectionRect->cancel();
  13158. if (event->button() == Qt::LeftButton)
  13159. processPointSelection(event);
  13160. // emit specialized click signals of QCustomPlot instance:
  13161. if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(mMouseSignalLayerable))
  13162. {
  13163. int dataIndex = 0;
  13164. if (!mMouseSignalLayerableDetails.value<QCPDataSelection>().isEmpty())
  13165. dataIndex = mMouseSignalLayerableDetails.value<QCPDataSelection>().dataRange().begin();
  13166. emit plottableClick(ap, dataIndex, event);
  13167. } else if (QCPAxis *ax = qobject_cast<QCPAxis*>(mMouseSignalLayerable))
  13168. emit axisClick(ax, mMouseSignalLayerableDetails.value<QCPAxis::SelectablePart>(), event);
  13169. else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(mMouseSignalLayerable))
  13170. emit itemClick(ai, event);
  13171. else if (QCPLegend *lg = qobject_cast<QCPLegend*>(mMouseSignalLayerable))
  13172. emit legendClick(lg, nullptr, event);
  13173. else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(mMouseSignalLayerable))
  13174. emit legendClick(li->parentLegend(), li, event);
  13175. mMouseSignalLayerable = nullptr;
  13176. }
  13177. if (mSelectionRect && mSelectionRect->isActive()) // Note: if a click was detected above, the selection rect is canceled there
  13178. {
  13179. // finish selection rect, the appropriate action will be taken via signal-slot connection:
  13180. mSelectionRect->endSelection(event);
  13181. } else
  13182. {
  13183. // call event of affected layerable:
  13184. if (mMouseEventLayerable)
  13185. {
  13186. mMouseEventLayerable->mouseReleaseEvent(event, mMousePressPos);
  13187. mMouseEventLayerable = nullptr;
  13188. }
  13189. }
  13190. if (noAntialiasingOnDrag())
  13191. replot(rpQueuedReplot);
  13192. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13193. }
  13194. /*! \internal
  13195. Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then
  13196. determines the affected layerable and forwards the event to it.
  13197. */
  13198. void QCustomPlot::wheelEvent(QWheelEvent *event)
  13199. {
  13200. emit mouseWheel(event);
  13201. #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  13202. const QPointF pos = event->pos();
  13203. #else
  13204. const QPointF pos = event->position();
  13205. #endif
  13206. // forward event to layerable under cursor:
  13207. foreach (QCPLayerable *candidate, layerableListAt(pos, false))
  13208. {
  13209. event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
  13210. candidate->wheelEvent(event);
  13211. if (event->isAccepted())
  13212. break;
  13213. }
  13214. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13215. }
  13216. /*! \internal
  13217. This function draws the entire plot, including background pixmap, with the specified \a painter.
  13218. It does not make use of the paint buffers like \ref replot, so this is the function typically
  13219. used by saving/exporting methods such as \ref savePdf or \ref toPainter.
  13220. Note that it does not fill the background with the background brush (as the user may specify with
  13221. \ref setBackground(const QBrush &brush)), this is up to the respective functions calling this
  13222. method.
  13223. */
  13224. void QCustomPlot::draw(QCPPainter *painter)
  13225. {
  13226. updateLayout();
  13227. // draw viewport background pixmap:
  13228. drawBackground(painter);
  13229. // draw all layered objects (grid, axes, plottables, items, legend,...):
  13230. foreach (QCPLayer *layer, mLayers)
  13231. layer->draw(painter);
  13232. /* Debug code to draw all layout element rects
  13233. foreach (QCPLayoutElement* el, findChildren<QCPLayoutElement*>())
  13234. {
  13235. painter->setBrush(Qt::NoBrush);
  13236. painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine));
  13237. painter->drawRect(el->rect());
  13238. painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine));
  13239. painter->drawRect(el->outerRect());
  13240. }
  13241. */
  13242. }
  13243. /*! \internal
  13244. Performs the layout update steps defined by \ref QCPLayoutElement::UpdatePhase, by calling \ref
  13245. QCPLayoutElement::update on the main plot layout.
  13246. Here, the layout elements calculate their positions and margins, and prepare for the following
  13247. draw call.
  13248. */
  13249. void QCustomPlot::updateLayout()
  13250. {
  13251. // run through layout phases:
  13252. mPlotLayout->update(QCPLayoutElement::upPreparation);
  13253. mPlotLayout->update(QCPLayoutElement::upMargins);
  13254. mPlotLayout->update(QCPLayoutElement::upLayout);
  13255. emit afterLayout();
  13256. }
  13257. /*! \internal
  13258. Draws the viewport background pixmap of the plot.
  13259. If a pixmap was provided via \ref setBackground, this function buffers the scaled version
  13260. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  13261. the viewport with the provided \a painter. The scaled version is buffered in
  13262. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  13263. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  13264. dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
  13265. set.
  13266. Note that this function does not draw a fill with the background brush
  13267. (\ref setBackground(const QBrush &brush)) beneath the pixmap.
  13268. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  13269. */
  13270. void QCustomPlot::drawBackground(QCPPainter *painter)
  13271. {
  13272. // Note: background color is handled in individual replot/save functions
  13273. // draw background pixmap (on top of fill, if brush specified):
  13274. if (!mBackgroundPixmap.isNull())
  13275. {
  13276. if (mBackgroundScaled)
  13277. {
  13278. // check whether mScaledBackground needs to be updated:
  13279. QSize scaledSize(mBackgroundPixmap.size());
  13280. scaledSize.scale(mViewport.size(), mBackgroundScaledMode);
  13281. if (mScaledBackgroundPixmap.size() != scaledSize)
  13282. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
  13283. painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect());
  13284. } else
  13285. {
  13286. painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()));
  13287. }
  13288. }
  13289. }
  13290. /*! \internal
  13291. Goes through the layers and makes sure this QCustomPlot instance holds the correct number of
  13292. paint buffers and that they have the correct configuration (size, pixel ratio, etc.).
  13293. Allocations, reallocations and deletions of paint buffers are performed as necessary. It also
  13294. associates the paint buffers with the layers, so they draw themselves into the right buffer when
  13295. \ref QCPLayer::drawToPaintBuffer is called. This means it associates adjacent \ref
  13296. QCPLayer::lmLogical layers to a mutual paint buffer and creates dedicated paint buffers for
  13297. layers in \ref QCPLayer::lmBuffered mode.
  13298. This method uses \ref createPaintBuffer to create new paint buffers.
  13299. After this method, the paint buffers are empty (filled with \c Qt::transparent) and invalidated
  13300. (so an attempt to replot only a single buffered layer causes a full replot).
  13301. This method is called in every \ref replot call, prior to actually drawing the layers (into their
  13302. associated paint buffer). If the paint buffers don't need changing/reallocating, this method
  13303. basically leaves them alone and thus finishes very fast.
  13304. */
  13305. void QCustomPlot::setupPaintBuffers()
  13306. {
  13307. int bufferIndex = 0;
  13308. if (mPaintBuffers.isEmpty())
  13309. mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
  13310. for (int layerIndex = 0; layerIndex < mLayers.size(); ++layerIndex)
  13311. {
  13312. QCPLayer *layer = mLayers.at(layerIndex);
  13313. if (layer->mode() == QCPLayer::lmLogical)
  13314. {
  13315. layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef();
  13316. } else if (layer->mode() == QCPLayer::lmBuffered)
  13317. {
  13318. ++bufferIndex;
  13319. if (bufferIndex >= mPaintBuffers.size())
  13320. mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
  13321. layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef();
  13322. 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
  13323. {
  13324. ++bufferIndex;
  13325. if (bufferIndex >= mPaintBuffers.size())
  13326. mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
  13327. }
  13328. }
  13329. }
  13330. // remove unneeded buffers:
  13331. while (mPaintBuffers.size()-1 > bufferIndex)
  13332. mPaintBuffers.removeLast();
  13333. // resize buffers to viewport size and clear contents:
  13334. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  13335. {
  13336. buffer->setSize(viewport().size()); // won't do anything if already correct size
  13337. buffer->clear(Qt::transparent);
  13338. buffer->setInvalidated();
  13339. }
  13340. }
  13341. /*! \internal
  13342. This method is used by \ref setupPaintBuffers when it needs to create new paint buffers.
  13343. Depending on the current setting of \ref setOpenGl, and the current Qt version, different
  13344. backends (subclasses of \ref QCPAbstractPaintBuffer) are created, initialized with the proper
  13345. size and device pixel ratio, and returned.
  13346. */
  13347. QCPAbstractPaintBuffer *QCustomPlot::createPaintBuffer()
  13348. {
  13349. if (mOpenGl)
  13350. {
  13351. #if defined(QCP_OPENGL_FBO)
  13352. return new QCPPaintBufferGlFbo(viewport().size(), mBufferDevicePixelRatio, mGlContext, mGlPaintDevice);
  13353. #elif defined(QCP_OPENGL_PBUFFER)
  13354. return new QCPPaintBufferGlPbuffer(viewport().size(), mBufferDevicePixelRatio, mOpenGlMultisamples);
  13355. #else
  13356. 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.";
  13357. return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio);
  13358. #endif
  13359. } else
  13360. return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio);
  13361. }
  13362. /*!
  13363. This method returns whether any of the paint buffers held by this QCustomPlot instance are
  13364. invalidated.
  13365. If any buffer is invalidated, a partial replot (\ref QCPLayer::replot) is not allowed and always
  13366. causes a full replot (\ref QCustomPlot::replot) of all layers. This is the case when for example
  13367. the layer order has changed, new layers were added or removed, layer modes were changed (\ref
  13368. QCPLayer::setMode), or layerables were added or removed.
  13369. \see QCPAbstractPaintBuffer::setInvalidated
  13370. */
  13371. bool QCustomPlot::hasInvalidatedPaintBuffers()
  13372. {
  13373. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  13374. {
  13375. if (buffer->invalidated())
  13376. return true;
  13377. }
  13378. return false;
  13379. }
  13380. /*! \internal
  13381. When \ref setOpenGl is set to true, this method is used to initialize OpenGL (create a context,
  13382. surface, paint device).
  13383. Returns true on success.
  13384. If this method is successful, all paint buffers should be deleted and then reallocated by calling
  13385. \ref setupPaintBuffers, so the OpenGL-based paint buffer subclasses (\ref
  13386. QCPPaintBufferGlPbuffer, \ref QCPPaintBufferGlFbo) are used for subsequent replots.
  13387. \see freeOpenGl
  13388. */
  13389. bool QCustomPlot::setupOpenGl()
  13390. {
  13391. #ifdef QCP_OPENGL_FBO
  13392. freeOpenGl();
  13393. QSurfaceFormat proposedSurfaceFormat;
  13394. proposedSurfaceFormat.setSamples(mOpenGlMultisamples);
  13395. #ifdef QCP_OPENGL_OFFSCREENSURFACE
  13396. QOffscreenSurface *surface = new QOffscreenSurface;
  13397. #else
  13398. QWindow *surface = new QWindow;
  13399. surface->setSurfaceType(QSurface::OpenGLSurface);
  13400. #endif
  13401. surface->setFormat(proposedSurfaceFormat);
  13402. surface->create();
  13403. mGlSurface = QSharedPointer<QSurface>(surface);
  13404. mGlContext = QSharedPointer<QOpenGLContext>(new QOpenGLContext);
  13405. mGlContext->setFormat(mGlSurface->format());
  13406. if (!mGlContext->create())
  13407. {
  13408. qDebug() << Q_FUNC_INFO << "Failed to create OpenGL context";
  13409. mGlContext.clear();
  13410. mGlSurface.clear();
  13411. return false;
  13412. }
  13413. if (!mGlContext->makeCurrent(mGlSurface.data())) // context needs to be current to create paint device
  13414. {
  13415. qDebug() << Q_FUNC_INFO << "Failed to make opengl context current";
  13416. mGlContext.clear();
  13417. mGlSurface.clear();
  13418. return false;
  13419. }
  13420. if (!QOpenGLFramebufferObject::hasOpenGLFramebufferObjects())
  13421. {
  13422. qDebug() << Q_FUNC_INFO << "OpenGL of this system doesn't support frame buffer objects";
  13423. mGlContext.clear();
  13424. mGlSurface.clear();
  13425. return false;
  13426. }
  13427. mGlPaintDevice = QSharedPointer<QOpenGLPaintDevice>(new QOpenGLPaintDevice);
  13428. return true;
  13429. #elif defined(QCP_OPENGL_PBUFFER)
  13430. return QGLFormat::hasOpenGL();
  13431. #else
  13432. return false;
  13433. #endif
  13434. }
  13435. /*! \internal
  13436. When \ref setOpenGl is set to false, this method is used to deinitialize OpenGL (releases the
  13437. context and frees resources).
  13438. After OpenGL is disabled, all paint buffers should be deleted and then reallocated by calling
  13439. \ref setupPaintBuffers, so the standard software rendering paint buffer subclass (\ref
  13440. QCPPaintBufferPixmap) is used for subsequent replots.
  13441. \see setupOpenGl
  13442. */
  13443. void QCustomPlot::freeOpenGl()
  13444. {
  13445. #ifdef QCP_OPENGL_FBO
  13446. mGlPaintDevice.clear();
  13447. mGlContext.clear();
  13448. mGlSurface.clear();
  13449. #endif
  13450. }
  13451. /*! \internal
  13452. This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot
  13453. so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly.
  13454. */
  13455. void QCustomPlot::axisRemoved(QCPAxis *axis)
  13456. {
  13457. if (xAxis == axis)
  13458. xAxis = nullptr;
  13459. if (xAxis2 == axis)
  13460. xAxis2 = nullptr;
  13461. if (yAxis == axis)
  13462. yAxis = nullptr;
  13463. if (yAxis2 == axis)
  13464. yAxis2 = nullptr;
  13465. // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers
  13466. }
  13467. /*! \internal
  13468. This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so
  13469. it may clear its QCustomPlot::legend member accordingly.
  13470. */
  13471. void QCustomPlot::legendRemoved(QCPLegend *legend)
  13472. {
  13473. if (this->legend == legend)
  13474. this->legend = nullptr;
  13475. }
  13476. /*! \internal
  13477. This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref
  13478. setSelectionRectMode is set to \ref QCP::srmSelect.
  13479. First, it determines which axis rect was the origin of the selection rect judging by the starting
  13480. point of the selection. Then it goes through the plottables (\ref QCPAbstractPlottable1D to be
  13481. precise) associated with that axis rect and finds the data points that are in \a rect. It does
  13482. this by querying their \ref QCPAbstractPlottable1D::selectTestRect method.
  13483. Then, the actual selection is done by calling the plottables' \ref
  13484. QCPAbstractPlottable::selectEvent, placing the found selected data points in the \a details
  13485. parameter as <tt>QVariant(\ref QCPDataSelection)</tt>. All plottables that weren't touched by \a
  13486. rect receive a \ref QCPAbstractPlottable::deselectEvent.
  13487. \see processRectZoom
  13488. */
  13489. void QCustomPlot::processRectSelection(QRect rect, QMouseEvent *event)
  13490. {
  13491. typedef QPair<QCPAbstractPlottable*, QCPDataSelection> SelectionCandidate;
  13492. typedef QMultiMap<int, SelectionCandidate> SelectionCandidates; // map key is number of selected data points, so we have selections sorted by size
  13493. bool selectionStateChanged = false;
  13494. if (mInteractions.testFlag(QCP::iSelectPlottables))
  13495. {
  13496. SelectionCandidates potentialSelections;
  13497. QRectF rectF(rect.normalized());
  13498. if (QCPAxisRect *affectedAxisRect = axisRectAt(rectF.topLeft()))
  13499. {
  13500. // determine plottables that were hit by the rect and thus are candidates for selection:
  13501. foreach (QCPAbstractPlottable *plottable, affectedAxisRect->plottables())
  13502. {
  13503. if (QCPPlottableInterface1D *plottableInterface = plottable->interface1D())
  13504. {
  13505. QCPDataSelection dataSel = plottableInterface->selectTestRect(rectF, true);
  13506. if (!dataSel.isEmpty())
  13507. potentialSelections.insert(dataSel.dataPointCount(), SelectionCandidate(plottable, dataSel));
  13508. }
  13509. }
  13510. if (!mInteractions.testFlag(QCP::iMultiSelect))
  13511. {
  13512. // only leave plottable with most selected points in map, since we will only select a single plottable:
  13513. if (!potentialSelections.isEmpty())
  13514. {
  13515. SelectionCandidates::iterator it = potentialSelections.begin();
  13516. while (it != std::prev(potentialSelections.end())) // erase all except last element
  13517. it = potentialSelections.erase(it);
  13518. }
  13519. }
  13520. bool additive = event->modifiers().testFlag(mMultiSelectModifier);
  13521. // deselect all other layerables if not additive selection:
  13522. if (!additive)
  13523. {
  13524. // emit deselection except to those plottables who will be selected afterwards:
  13525. foreach (QCPLayer *layer, mLayers)
  13526. {
  13527. foreach (QCPLayerable *layerable, layer->children())
  13528. {
  13529. if ((potentialSelections.isEmpty() || potentialSelections.constBegin()->first != layerable) && mInteractions.testFlag(layerable->selectionCategory()))
  13530. {
  13531. bool selChanged = false;
  13532. layerable->deselectEvent(&selChanged);
  13533. selectionStateChanged |= selChanged;
  13534. }
  13535. }
  13536. }
  13537. }
  13538. // go through selections in reverse (largest selection first) and emit select events:
  13539. SelectionCandidates::const_iterator it = potentialSelections.constEnd();
  13540. while (it != potentialSelections.constBegin())
  13541. {
  13542. --it;
  13543. if (mInteractions.testFlag(it.value().first->selectionCategory()))
  13544. {
  13545. bool selChanged = false;
  13546. it.value().first->selectEvent(event, additive, QVariant::fromValue(it.value().second), &selChanged);
  13547. selectionStateChanged |= selChanged;
  13548. }
  13549. }
  13550. }
  13551. }
  13552. if (selectionStateChanged)
  13553. {
  13554. emit selectionChangedByUser();
  13555. replot(rpQueuedReplot);
  13556. } else if (mSelectionRect)
  13557. mSelectionRect->layer()->replot();
  13558. }
  13559. /*! \internal
  13560. This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref
  13561. setSelectionRectMode is set to \ref QCP::srmZoom.
  13562. It determines which axis rect was the origin of the selection rect judging by the starting point
  13563. of the selection, and then zooms the axes defined via \ref QCPAxisRect::setRangeZoomAxes to the
  13564. provided \a rect (see \ref QCPAxisRect::zoom).
  13565. \see processRectSelection
  13566. */
  13567. void QCustomPlot::processRectZoom(QRect rect, QMouseEvent *event)
  13568. {
  13569. Q_UNUSED(event)
  13570. if (QCPAxisRect *axisRect = axisRectAt(rect.topLeft()))
  13571. {
  13572. QList<QCPAxis*> affectedAxes = QList<QCPAxis*>() << axisRect->rangeZoomAxes(Qt::Horizontal) << axisRect->rangeZoomAxes(Qt::Vertical);
  13573. affectedAxes.removeAll(static_cast<QCPAxis*>(nullptr));
  13574. axisRect->zoom(QRectF(rect), affectedAxes);
  13575. }
  13576. replot(rpQueuedReplot); // always replot to make selection rect disappear
  13577. }
  13578. /*! \internal
  13579. This method is called when a simple left mouse click was detected on the QCustomPlot surface.
  13580. It first determines the layerable that was hit by the click, and then calls its \ref
  13581. QCPLayerable::selectEvent. All other layerables receive a QCPLayerable::deselectEvent (unless the
  13582. multi-select modifier was pressed, see \ref setMultiSelectModifier).
  13583. In this method the hit layerable is determined a second time using \ref layerableAt (after the
  13584. one in \ref mousePressEvent), because we want \a onlySelectable set to true this time. This
  13585. implies that the mouse event grabber (mMouseEventLayerable) may be a different one from the
  13586. clicked layerable determined here. For example, if a non-selectable layerable is in front of a
  13587. selectable layerable at the click position, the front layerable will receive mouse events but the
  13588. selectable one in the back will receive the \ref QCPLayerable::selectEvent.
  13589. \see processRectSelection, QCPLayerable::selectTest
  13590. */
  13591. void QCustomPlot::processPointSelection(QMouseEvent *event)
  13592. {
  13593. QVariant details;
  13594. QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details);
  13595. bool selectionStateChanged = false;
  13596. bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier);
  13597. // deselect all other layerables if not additive selection:
  13598. if (!additive)
  13599. {
  13600. foreach (QCPLayer *layer, mLayers)
  13601. {
  13602. foreach (QCPLayerable *layerable, layer->children())
  13603. {
  13604. if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory()))
  13605. {
  13606. bool selChanged = false;
  13607. layerable->deselectEvent(&selChanged);
  13608. selectionStateChanged |= selChanged;
  13609. }
  13610. }
  13611. }
  13612. }
  13613. if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory()))
  13614. {
  13615. // a layerable was actually clicked, call its selectEvent:
  13616. bool selChanged = false;
  13617. clickedLayerable->selectEvent(event, additive, details, &selChanged);
  13618. selectionStateChanged |= selChanged;
  13619. }
  13620. if (selectionStateChanged)
  13621. {
  13622. emit selectionChangedByUser();
  13623. replot(rpQueuedReplot);
  13624. }
  13625. }
  13626. /*! \internal
  13627. Registers the specified plottable with this QCustomPlot and, if \ref setAutoAddPlottableToLegend
  13628. is enabled, adds it to the legend (QCustomPlot::legend). QCustomPlot takes ownership of the
  13629. plottable.
  13630. Returns true on success, i.e. when \a plottable isn't already in this plot and the parent plot of
  13631. \a plottable is this QCustomPlot.
  13632. This method is called automatically in the QCPAbstractPlottable base class constructor.
  13633. */
  13634. bool QCustomPlot::registerPlottable(QCPAbstractPlottable *plottable)
  13635. {
  13636. if (mPlottables.contains(plottable))
  13637. {
  13638. qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast<quintptr>(plottable);
  13639. return false;
  13640. }
  13641. if (plottable->parentPlot() != this)
  13642. {
  13643. qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(plottable);
  13644. return false;
  13645. }
  13646. mPlottables.append(plottable);
  13647. // possibly add plottable to legend:
  13648. if (mAutoAddPlottableToLegend)
  13649. plottable->addToLegend();
  13650. if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
  13651. plottable->setLayer(currentLayer());
  13652. return true;
  13653. }
  13654. /*! \internal
  13655. In order to maintain the simplified graph interface of QCustomPlot, this method is called by the
  13656. QCPGraph constructor to register itself with this QCustomPlot's internal graph list. Returns true
  13657. on success, i.e. if \a graph is valid and wasn't already registered with this QCustomPlot.
  13658. This graph specific registration happens in addition to the call to \ref registerPlottable by the
  13659. QCPAbstractPlottable base class.
  13660. */
  13661. bool QCustomPlot::registerGraph(QCPGraph *graph)
  13662. {
  13663. if (!graph)
  13664. {
  13665. qDebug() << Q_FUNC_INFO << "passed graph is zero";
  13666. return false;
  13667. }
  13668. if (mGraphs.contains(graph))
  13669. {
  13670. qDebug() << Q_FUNC_INFO << "graph already registered with this QCustomPlot";
  13671. return false;
  13672. }
  13673. mGraphs.append(graph);
  13674. return true;
  13675. }
  13676. /*! \internal
  13677. Registers the specified item with this QCustomPlot. QCustomPlot takes ownership of the item.
  13678. Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a
  13679. item is this QCustomPlot.
  13680. This method is called automatically in the QCPAbstractItem base class constructor.
  13681. */
  13682. bool QCustomPlot::registerItem(QCPAbstractItem *item)
  13683. {
  13684. if (mItems.contains(item))
  13685. {
  13686. qDebug() << Q_FUNC_INFO << "item already added to this QCustomPlot:" << reinterpret_cast<quintptr>(item);
  13687. return false;
  13688. }
  13689. if (item->parentPlot() != this)
  13690. {
  13691. qDebug() << Q_FUNC_INFO << "item not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(item);
  13692. return false;
  13693. }
  13694. mItems.append(item);
  13695. if (!item->layer()) // usually the layer is already set in the constructor of the item (via QCPLayerable constructor)
  13696. item->setLayer(currentLayer());
  13697. return true;
  13698. }
  13699. /*! \internal
  13700. Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called
  13701. after every operation that changes the layer indices, like layer removal, layer creation, layer
  13702. moving.
  13703. */
  13704. void QCustomPlot::updateLayerIndices() const
  13705. {
  13706. for (int i=0; i<mLayers.size(); ++i)
  13707. mLayers.at(i)->mIndex = i;
  13708. }
  13709. /*! \internal
  13710. Returns the top-most layerable at pixel position \a pos. If \a onlySelectable is set to true,
  13711. only those layerables that are selectable will be considered. (Layerable subclasses communicate
  13712. their selectability via the QCPLayerable::selectTest method, by returning -1.)
  13713. \a selectionDetails is an output parameter that contains selection specifics of the affected
  13714. layerable. This is useful if the respective layerable shall be given a subsequent
  13715. QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
  13716. information about which part of the layerable was hit, in multi-part layerables (e.g.
  13717. QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref
  13718. QCPDataSelection instance with the single data point which is closest to \a pos.
  13719. \see layerableListAt, layoutElementAt, axisRectAt
  13720. */
  13721. QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const
  13722. {
  13723. QList<QVariant> details;
  13724. QList<QCPLayerable*> candidates = layerableListAt(pos, onlySelectable, selectionDetails ? &details : nullptr);
  13725. if (selectionDetails && !details.isEmpty())
  13726. *selectionDetails = details.first();
  13727. if (!candidates.isEmpty())
  13728. return candidates.first();
  13729. else
  13730. return nullptr;
  13731. }
  13732. /*! \internal
  13733. Returns the layerables at pixel position \a pos. If \a onlySelectable is set to true, only those
  13734. layerables that are selectable will be considered. (Layerable subclasses communicate their
  13735. selectability via the QCPLayerable::selectTest method, by returning -1.)
  13736. The returned list is sorted by the layerable/drawing order such that the layerable that appears
  13737. on top in the plot is at index 0 of the returned list. If you only need to know the top
  13738. layerable, rather use \ref layerableAt.
  13739. \a selectionDetails is an output parameter that contains selection specifics of the affected
  13740. layerable. This is useful if the respective layerable shall be given a subsequent
  13741. QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
  13742. information about which part of the layerable was hit, in multi-part layerables (e.g.
  13743. QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref
  13744. QCPDataSelection instance with the single data point which is closest to \a pos.
  13745. \see layerableAt, layoutElementAt, axisRectAt
  13746. */
  13747. QList<QCPLayerable*> QCustomPlot::layerableListAt(const QPointF &pos, bool onlySelectable, QList<QVariant> *selectionDetails) const
  13748. {
  13749. QList<QCPLayerable*> result;
  13750. for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex)
  13751. {
  13752. const QList<QCPLayerable*> layerables = mLayers.at(layerIndex)->children();
  13753. for (int i=layerables.size()-1; i>=0; --i)
  13754. {
  13755. if (!layerables.at(i)->realVisibility())
  13756. continue;
  13757. QVariant details;
  13758. double dist = layerables.at(i)->selectTest(pos, onlySelectable, selectionDetails ? &details : nullptr);
  13759. if (dist >= 0 && dist < selectionTolerance())
  13760. {
  13761. result.append(layerables.at(i));
  13762. if (selectionDetails)
  13763. selectionDetails->append(details);
  13764. }
  13765. }
  13766. }
  13767. return result;
  13768. }
  13769. /*!
  13770. Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is
  13771. sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead
  13772. to a full resolution file with width 200.) If the \a format supports compression, \a quality may
  13773. be between 0 and 100 to control it.
  13774. Returns true on success. If this function fails, most likely the given \a format isn't supported
  13775. by the system, see Qt docs about QImageWriter::supportedImageFormats().
  13776. The \a resolution will be written to the image file header (if the file format supports this) and
  13777. has no direct consequence for the quality or the pixel size. However, if opening the image with a
  13778. tool which respects the metadata, it will be able to scale the image to match either a given size
  13779. in real units of length (inch, centimeters, etc.), or the target display DPI. You can specify in
  13780. which units \a resolution is given, by setting \a resolutionUnit. The \a resolution is converted
  13781. to the format's expected resolution unit internally.
  13782. \see saveBmp, saveJpg, savePng, savePdf
  13783. */
  13784. bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
  13785. {
  13786. QImage buffer = toPixmap(width, height, scale).toImage();
  13787. int dotsPerMeter = 0;
  13788. switch (resolutionUnit)
  13789. {
  13790. case QCP::ruDotsPerMeter: dotsPerMeter = resolution; break;
  13791. case QCP::ruDotsPerCentimeter: dotsPerMeter = resolution*100; break;
  13792. case QCP::ruDotsPerInch: dotsPerMeter = int(resolution/0.0254); break;
  13793. }
  13794. buffer.setDotsPerMeterX(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools
  13795. buffer.setDotsPerMeterY(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools
  13796. if (!buffer.isNull())
  13797. return buffer.save(fileName, format, quality);
  13798. else
  13799. return false;
  13800. }
  13801. /*!
  13802. Renders the plot to a pixmap and returns it.
  13803. The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and
  13804. scale 2.0 lead to a full resolution pixmap with width 200.)
  13805. \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf
  13806. */
  13807. QPixmap QCustomPlot::toPixmap(int width, int height, double scale)
  13808. {
  13809. // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too.
  13810. int newWidth, newHeight;
  13811. if (width == 0 || height == 0)
  13812. {
  13813. newWidth = this->width();
  13814. newHeight = this->height();
  13815. } else
  13816. {
  13817. newWidth = width;
  13818. newHeight = height;
  13819. }
  13820. int scaledWidth = qRound(scale*newWidth);
  13821. int scaledHeight = qRound(scale*newHeight);
  13822. QPixmap result(scaledWidth, scaledHeight);
  13823. result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later
  13824. QCPPainter painter;
  13825. painter.begin(&result);
  13826. if (painter.isActive())
  13827. {
  13828. QRect oldViewport = viewport();
  13829. setViewport(QRect(0, 0, newWidth, newHeight));
  13830. painter.setMode(QCPPainter::pmNoCaching);
  13831. if (!qFuzzyCompare(scale, 1.0))
  13832. {
  13833. if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales
  13834. painter.setMode(QCPPainter::pmNonCosmetic);
  13835. painter.scale(scale, scale);
  13836. }
  13837. if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) // solid fills were done a few lines above with QPixmap::fill
  13838. painter.fillRect(mViewport, mBackgroundBrush);
  13839. draw(&painter);
  13840. setViewport(oldViewport);
  13841. painter.end();
  13842. } else // might happen if pixmap has width or height zero
  13843. {
  13844. qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap";
  13845. return QPixmap();
  13846. }
  13847. return result;
  13848. }
  13849. /*!
  13850. Renders the plot using the passed \a painter.
  13851. 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
  13852. appear scaled accordingly.
  13853. \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter
  13854. on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with
  13855. the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter.
  13856. \see toPixmap
  13857. */
  13858. void QCustomPlot::toPainter(QCPPainter *painter, int width, int height)
  13859. {
  13860. // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too.
  13861. int newWidth, newHeight;
  13862. if (width == 0 || height == 0)
  13863. {
  13864. newWidth = this->width();
  13865. newHeight = this->height();
  13866. } else
  13867. {
  13868. newWidth = width;
  13869. newHeight = height;
  13870. }
  13871. if (painter->isActive())
  13872. {
  13873. QRect oldViewport = viewport();
  13874. setViewport(QRect(0, 0, newWidth, newHeight));
  13875. painter->setMode(QCPPainter::pmNoCaching);
  13876. 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
  13877. painter->fillRect(mViewport, mBackgroundBrush);
  13878. draw(painter);
  13879. setViewport(oldViewport);
  13880. } else
  13881. qDebug() << Q_FUNC_INFO << "Passed painter is not active";
  13882. }
  13883. /* end of 'src/core.cpp' */
  13884. /* including file 'src/colorgradient.cpp' */
  13885. /* modified 2021-03-29T02:30:44, size 25278 */
  13886. ////////////////////////////////////////////////////////////////////////////////////////////////////
  13887. //////////////////// QCPColorGradient
  13888. ////////////////////////////////////////////////////////////////////////////////////////////////////
  13889. /*! \class QCPColorGradient
  13890. \brief Defines a color gradient for use with e.g. \ref QCPColorMap
  13891. This class describes a color gradient which can be used to encode data with color. For example,
  13892. QCPColorMap and QCPColorScale have \ref QCPColorMap::setGradient "setGradient" methods which
  13893. take an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color)
  13894. with a \a position from 0 to 1. In between these defined color positions, the
  13895. color will be interpolated linearly either in RGB or HSV space, see \ref setColorInterpolation.
  13896. Alternatively, load one of the preset color gradients shown in the image below, with \ref
  13897. loadPreset, or by directly specifying the preset in the constructor.
  13898. Apart from red, green and blue components, the gradient also interpolates the alpha values of the
  13899. configured color stops. This allows to display some portions of the data range as transparent in
  13900. the plot.
  13901. How NaN values are interpreted can be configured with \ref setNanHandling.
  13902. \image html QCPColorGradient.png
  13903. The constructor \ref QCPColorGradient(GradientPreset preset) allows directly converting a \ref
  13904. GradientPreset to a QCPColorGradient. This means that you can directly pass \ref GradientPreset
  13905. to all the \a setGradient methods, e.g.:
  13906. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorgradient-setgradient
  13907. The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the
  13908. color gradient shall be applied periodically (wrapping around) to data values that lie outside
  13909. the data range specified on the plottable instance can be controlled with \ref setPeriodic.
  13910. */
  13911. /*!
  13912. Constructs a new, empty QCPColorGradient with no predefined color stops. You can add own color
  13913. stops with \ref setColorStopAt.
  13914. The color level count is initialized to 350.
  13915. */
  13916. QCPColorGradient::QCPColorGradient() :
  13917. mLevelCount(350),
  13918. mColorInterpolation(ciRGB),
  13919. mNanHandling(nhNone),
  13920. mNanColor(Qt::black),
  13921. mPeriodic(false),
  13922. mColorBufferInvalidated(true)
  13923. {
  13924. mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
  13925. }
  13926. /*!
  13927. Constructs a new QCPColorGradient initialized with the colors and color interpolation according
  13928. to \a preset.
  13929. The color level count is initialized to 350.
  13930. */
  13931. QCPColorGradient::QCPColorGradient(GradientPreset preset) :
  13932. mLevelCount(350),
  13933. mColorInterpolation(ciRGB),
  13934. mNanHandling(nhNone),
  13935. mNanColor(Qt::black),
  13936. mPeriodic(false),
  13937. mColorBufferInvalidated(true)
  13938. {
  13939. mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
  13940. loadPreset(preset);
  13941. }
  13942. /* undocumented operator */
  13943. bool QCPColorGradient::operator==(const QCPColorGradient &other) const
  13944. {
  13945. return ((other.mLevelCount == this->mLevelCount) &&
  13946. (other.mColorInterpolation == this->mColorInterpolation) &&
  13947. (other.mNanHandling == this ->mNanHandling) &&
  13948. (other.mNanColor == this->mNanColor) &&
  13949. (other.mPeriodic == this->mPeriodic) &&
  13950. (other.mColorStops == this->mColorStops));
  13951. }
  13952. /*!
  13953. Sets the number of discretization levels of the color gradient to \a n. The default is 350 which
  13954. is typically enough to create a smooth appearance. The minimum number of levels is 2.
  13955. \image html QCPColorGradient-levelcount.png
  13956. */
  13957. void QCPColorGradient::setLevelCount(int n)
  13958. {
  13959. if (n < 2)
  13960. {
  13961. qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n;
  13962. n = 2;
  13963. }
  13964. if (n != mLevelCount)
  13965. {
  13966. mLevelCount = n;
  13967. mColorBufferInvalidated = true;
  13968. }
  13969. }
  13970. /*!
  13971. Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the
  13972. colors are the values of the passed QMap \a colorStops. In between these color stops, the color
  13973. is interpolated according to \ref setColorInterpolation.
  13974. A more convenient way to create a custom gradient may be to clear all color stops with \ref
  13975. clearColorStops (or creating a new, empty QCPColorGradient) and then adding them one by one with
  13976. \ref setColorStopAt.
  13977. \see clearColorStops
  13978. */
  13979. void QCPColorGradient::setColorStops(const QMap<double, QColor> &colorStops)
  13980. {
  13981. mColorStops = colorStops;
  13982. mColorBufferInvalidated = true;
  13983. }
  13984. /*!
  13985. Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between
  13986. these color stops, the color is interpolated according to \ref setColorInterpolation.
  13987. \see setColorStops, clearColorStops
  13988. */
  13989. void QCPColorGradient::setColorStopAt(double position, const QColor &color)
  13990. {
  13991. mColorStops.insert(position, color);
  13992. mColorBufferInvalidated = true;
  13993. }
  13994. /*!
  13995. Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be
  13996. interpolated linearly in RGB or in HSV color space.
  13997. For example, a sweep in RGB space from red to green will have a muddy brown intermediate color,
  13998. whereas in HSV space the intermediate color is yellow.
  13999. */
  14000. void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation)
  14001. {
  14002. if (interpolation != mColorInterpolation)
  14003. {
  14004. mColorInterpolation = interpolation;
  14005. mColorBufferInvalidated = true;
  14006. }
  14007. }
  14008. /*!
  14009. Sets how NaNs in the data are displayed in the plot.
  14010. \see setNanColor
  14011. */
  14012. void QCPColorGradient::setNanHandling(QCPColorGradient::NanHandling handling)
  14013. {
  14014. mNanHandling = handling;
  14015. }
  14016. /*!
  14017. Sets the color that NaN data is represented by, if \ref setNanHandling is set
  14018. to ref nhNanColor.
  14019. \see setNanHandling
  14020. */
  14021. void QCPColorGradient::setNanColor(const QColor &color)
  14022. {
  14023. mNanColor = color;
  14024. }
  14025. /*!
  14026. Sets whether data points that are outside the configured data range (e.g. \ref
  14027. QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether
  14028. they all have the same color, corresponding to the respective gradient boundary color.
  14029. \image html QCPColorGradient-periodic.png
  14030. As shown in the image above, gradients that have the same start and end color are especially
  14031. suitable for a periodic gradient mapping, since they produce smooth color transitions throughout
  14032. the color map. A preset that has this property is \ref gpHues.
  14033. In practice, using periodic color gradients makes sense when the data corresponds to a periodic
  14034. dimension, such as an angle or a phase. If this is not the case, the color encoding might become
  14035. ambiguous, because multiple different data values are shown as the same color.
  14036. */
  14037. void QCPColorGradient::setPeriodic(bool enabled)
  14038. {
  14039. mPeriodic = enabled;
  14040. }
  14041. /*! \overload
  14042. This method is used to quickly convert a \a data array to colors. The colors will be output in
  14043. the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this
  14044. function. The data range that shall be used for mapping the data value to the gradient is passed
  14045. in \a range. \a logarithmic indicates whether the data values shall be mapped to colors
  14046. logarithmically.
  14047. if \a data actually contains 2D-data linearized via <tt>[row*columnCount + column]</tt>, you can
  14048. set \a dataIndexFactor to <tt>columnCount</tt> to convert a column instead of a row of the data
  14049. array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data
  14050. is addressed <tt>data[i*dataIndexFactor]</tt>.
  14051. Use the overloaded method to additionally provide alpha map data.
  14052. The QRgb values that are placed in \a scanLine have their r, g, and b components premultiplied
  14053. with alpha (see QImage::Format_ARGB32_Premultiplied).
  14054. */
  14055. void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
  14056. {
  14057. // If you change something here, make sure to also adapt color() and the other colorize() overload
  14058. if (!data)
  14059. {
  14060. qDebug() << Q_FUNC_INFO << "null pointer given as data";
  14061. return;
  14062. }
  14063. if (!scanLine)
  14064. {
  14065. qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
  14066. return;
  14067. }
  14068. if (mColorBufferInvalidated)
  14069. updateColorBuffer();
  14070. const bool skipNanCheck = mNanHandling == nhNone;
  14071. const double posToIndexFactor = !logarithmic ? (mLevelCount-1)/range.size() : (mLevelCount-1)/qLn(range.upper/range.lower);
  14072. for (int i=0; i<n; ++i)
  14073. {
  14074. const double value = data[dataIndexFactor*i];
  14075. if (skipNanCheck || !std::isnan(value))
  14076. {
  14077. int index = int((!logarithmic ? value-range.lower : qLn(value/range.lower)) * posToIndexFactor);
  14078. if (!mPeriodic)
  14079. {
  14080. index = qBound(0, index, mLevelCount-1);
  14081. } else
  14082. {
  14083. index %= mLevelCount;
  14084. if (index < 0)
  14085. index += mLevelCount;
  14086. }
  14087. scanLine[i] = mColorBuffer.at(index);
  14088. } else
  14089. {
  14090. switch(mNanHandling)
  14091. {
  14092. case nhLowestColor: scanLine[i] = mColorBuffer.first(); break;
  14093. case nhHighestColor: scanLine[i] = mColorBuffer.last(); break;
  14094. case nhTransparent: scanLine[i] = qRgba(0, 0, 0, 0); break;
  14095. case nhNanColor: scanLine[i] = mNanColor.rgba(); break;
  14096. case nhNone: break; // shouldn't happen
  14097. }
  14098. }
  14099. }
  14100. }
  14101. /*! \overload
  14102. Additionally to the other overload of \ref colorize, this method takes the array \a alpha, which
  14103. has the same size and structure as \a data and encodes the alpha information per data point.
  14104. The QRgb values that are placed in \a scanLine have their r, g and b components premultiplied
  14105. with alpha (see QImage::Format_ARGB32_Premultiplied).
  14106. */
  14107. void QCPColorGradient::colorize(const double *data, const unsigned char *alpha, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
  14108. {
  14109. // If you change something here, make sure to also adapt color() and the other colorize() overload
  14110. if (!data)
  14111. {
  14112. qDebug() << Q_FUNC_INFO << "null pointer given as data";
  14113. return;
  14114. }
  14115. if (!alpha)
  14116. {
  14117. qDebug() << Q_FUNC_INFO << "null pointer given as alpha";
  14118. return;
  14119. }
  14120. if (!scanLine)
  14121. {
  14122. qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
  14123. return;
  14124. }
  14125. if (mColorBufferInvalidated)
  14126. updateColorBuffer();
  14127. const bool skipNanCheck = mNanHandling == nhNone;
  14128. const double posToIndexFactor = !logarithmic ? (mLevelCount-1)/range.size() : (mLevelCount-1)/qLn(range.upper/range.lower);
  14129. for (int i=0; i<n; ++i)
  14130. {
  14131. const double value = data[dataIndexFactor*i];
  14132. if (skipNanCheck || !std::isnan(value))
  14133. {
  14134. int index = int((!logarithmic ? value-range.lower : qLn(value/range.lower)) * posToIndexFactor);
  14135. if (!mPeriodic)
  14136. {
  14137. index = qBound(0, index, mLevelCount-1);
  14138. } else
  14139. {
  14140. index %= mLevelCount;
  14141. if (index < 0)
  14142. index += mLevelCount;
  14143. }
  14144. if (alpha[dataIndexFactor*i] == 255)
  14145. {
  14146. scanLine[i] = mColorBuffer.at(index);
  14147. } else
  14148. {
  14149. const QRgb rgb = mColorBuffer.at(index);
  14150. const float alphaF = alpha[dataIndexFactor*i]/255.0f;
  14151. 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
  14152. }
  14153. } else
  14154. {
  14155. switch(mNanHandling)
  14156. {
  14157. case nhLowestColor: scanLine[i] = mColorBuffer.first(); break;
  14158. case nhHighestColor: scanLine[i] = mColorBuffer.last(); break;
  14159. case nhTransparent: scanLine[i] = qRgba(0, 0, 0, 0); break;
  14160. case nhNanColor: scanLine[i] = mNanColor.rgba(); break;
  14161. case nhNone: break; // shouldn't happen
  14162. }
  14163. }
  14164. }
  14165. }
  14166. /*! \internal
  14167. This method is used to colorize a single data value given in \a position, to colors. The data
  14168. range that shall be used for mapping the data value to the gradient is passed in \a range. \a
  14169. logarithmic indicates whether the data value shall be mapped to a color logarithmically.
  14170. If an entire array of data values shall be converted, rather use \ref colorize, for better
  14171. performance.
  14172. The returned QRgb has its r, g and b components premultiplied with alpha (see
  14173. QImage::Format_ARGB32_Premultiplied).
  14174. */
  14175. QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic)
  14176. {
  14177. // If you change something here, make sure to also adapt ::colorize()
  14178. if (mColorBufferInvalidated)
  14179. updateColorBuffer();
  14180. const bool skipNanCheck = mNanHandling == nhNone;
  14181. if (!skipNanCheck && std::isnan(position))
  14182. {
  14183. switch(mNanHandling)
  14184. {
  14185. case nhLowestColor: return mColorBuffer.first();
  14186. case nhHighestColor: return mColorBuffer.last();
  14187. case nhTransparent: return qRgba(0, 0, 0, 0);
  14188. case nhNanColor: return mNanColor.rgba();
  14189. case nhNone: return qRgba(0, 0, 0, 0); // shouldn't happen
  14190. }
  14191. }
  14192. const double posToIndexFactor = !logarithmic ? (mLevelCount-1)/range.size() : (mLevelCount-1)/qLn(range.upper/range.lower);
  14193. int index = int((!logarithmic ? position-range.lower : qLn(position/range.lower)) * posToIndexFactor);
  14194. if (!mPeriodic)
  14195. {
  14196. index = qBound(0, index, mLevelCount-1);
  14197. } else
  14198. {
  14199. index %= mLevelCount;
  14200. if (index < 0)
  14201. index += mLevelCount;
  14202. }
  14203. return mColorBuffer.at(index);
  14204. }
  14205. /*!
  14206. Clears the current color stops and loads the specified \a preset. A preset consists of predefined
  14207. color stops and the corresponding color interpolation method.
  14208. The available presets are:
  14209. \image html QCPColorGradient.png
  14210. */
  14211. void QCPColorGradient::loadPreset(GradientPreset preset)
  14212. {
  14213. clearColorStops();
  14214. switch (preset)
  14215. {
  14216. case gpGrayscale:
  14217. setColorInterpolation(ciRGB);
  14218. setColorStopAt(0, Qt::black);
  14219. setColorStopAt(1, Qt::white);
  14220. break;
  14221. case gpHot:
  14222. setColorInterpolation(ciRGB);
  14223. setColorStopAt(0, QColor(50, 0, 0));
  14224. setColorStopAt(0.2, QColor(180, 10, 0));
  14225. setColorStopAt(0.4, QColor(245, 50, 0));
  14226. setColorStopAt(0.6, QColor(255, 150, 10));
  14227. setColorStopAt(0.8, QColor(255, 255, 50));
  14228. setColorStopAt(1, QColor(255, 255, 255));
  14229. break;
  14230. case gpCold:
  14231. setColorInterpolation(ciRGB);
  14232. setColorStopAt(0, QColor(0, 0, 50));
  14233. setColorStopAt(0.2, QColor(0, 10, 180));
  14234. setColorStopAt(0.4, QColor(0, 50, 245));
  14235. setColorStopAt(0.6, QColor(10, 150, 255));
  14236. setColorStopAt(0.8, QColor(50, 255, 255));
  14237. setColorStopAt(1, QColor(255, 255, 255));
  14238. break;
  14239. case gpNight:
  14240. setColorInterpolation(ciHSV);
  14241. setColorStopAt(0, QColor(10, 20, 30));
  14242. setColorStopAt(1, QColor(250, 255, 250));
  14243. break;
  14244. case gpCandy:
  14245. setColorInterpolation(ciHSV);
  14246. setColorStopAt(0, QColor(0, 0, 255));
  14247. setColorStopAt(1, QColor(255, 250, 250));
  14248. break;
  14249. case gpGeography:
  14250. setColorInterpolation(ciRGB);
  14251. setColorStopAt(0, QColor(70, 170, 210));
  14252. setColorStopAt(0.20, QColor(90, 160, 180));
  14253. setColorStopAt(0.25, QColor(45, 130, 175));
  14254. setColorStopAt(0.30, QColor(100, 140, 125));
  14255. setColorStopAt(0.5, QColor(100, 140, 100));
  14256. setColorStopAt(0.6, QColor(130, 145, 120));
  14257. setColorStopAt(0.7, QColor(140, 130, 120));
  14258. setColorStopAt(0.9, QColor(180, 190, 190));
  14259. setColorStopAt(1, QColor(210, 210, 230));
  14260. break;
  14261. case gpIon:
  14262. setColorInterpolation(ciHSV);
  14263. setColorStopAt(0, QColor(50, 10, 10));
  14264. setColorStopAt(0.45, QColor(0, 0, 255));
  14265. setColorStopAt(0.8, QColor(0, 255, 255));
  14266. setColorStopAt(1, QColor(0, 255, 0));
  14267. break;
  14268. case gpThermal:
  14269. setColorInterpolation(ciRGB);
  14270. setColorStopAt(0, QColor(0, 0, 50));
  14271. setColorStopAt(0.15, QColor(20, 0, 120));
  14272. setColorStopAt(0.33, QColor(200, 30, 140));
  14273. setColorStopAt(0.6, QColor(255, 100, 0));
  14274. setColorStopAt(0.85, QColor(255, 255, 40));
  14275. setColorStopAt(1, QColor(255, 255, 255));
  14276. break;
  14277. case gpPolar:
  14278. setColorInterpolation(ciRGB);
  14279. setColorStopAt(0, QColor(50, 255, 255));
  14280. setColorStopAt(0.18, QColor(10, 70, 255));
  14281. setColorStopAt(0.28, QColor(10, 10, 190));
  14282. setColorStopAt(0.5, QColor(0, 0, 0));
  14283. setColorStopAt(0.72, QColor(190, 10, 10));
  14284. setColorStopAt(0.82, QColor(255, 70, 10));
  14285. setColorStopAt(1, QColor(255, 255, 50));
  14286. break;
  14287. case gpSpectrum:
  14288. setColorInterpolation(ciHSV);
  14289. setColorStopAt(0, QColor(50, 0, 50));
  14290. setColorStopAt(0.15, QColor(0, 0, 255));
  14291. setColorStopAt(0.35, QColor(0, 255, 255));
  14292. setColorStopAt(0.6, QColor(255, 255, 0));
  14293. setColorStopAt(0.75, QColor(255, 30, 0));
  14294. setColorStopAt(1, QColor(50, 0, 0));
  14295. break;
  14296. case gpJet:
  14297. setColorInterpolation(ciRGB);
  14298. setColorStopAt(0, QColor(0, 0, 100));
  14299. setColorStopAt(0.15, QColor(0, 50, 255));
  14300. setColorStopAt(0.35, QColor(0, 255, 255));
  14301. setColorStopAt(0.65, QColor(255, 255, 0));
  14302. setColorStopAt(0.85, QColor(255, 30, 0));
  14303. setColorStopAt(1, QColor(100, 0, 0));
  14304. break;
  14305. case gpHues:
  14306. setColorInterpolation(ciHSV);
  14307. setColorStopAt(0, QColor(255, 0, 0));
  14308. setColorStopAt(1.0/3.0, QColor(0, 0, 255));
  14309. setColorStopAt(2.0/3.0, QColor(0, 255, 0));
  14310. setColorStopAt(1, QColor(255, 0, 0));
  14311. break;
  14312. }
  14313. }
  14314. /*!
  14315. Clears all color stops.
  14316. \see setColorStops, setColorStopAt
  14317. */
  14318. void QCPColorGradient::clearColorStops()
  14319. {
  14320. mColorStops.clear();
  14321. mColorBufferInvalidated = true;
  14322. }
  14323. /*!
  14324. Returns an inverted gradient. The inverted gradient has all properties as this \ref
  14325. QCPColorGradient, but the order of the color stops is inverted.
  14326. \see setColorStops, setColorStopAt
  14327. */
  14328. QCPColorGradient QCPColorGradient::inverted() const
  14329. {
  14330. QCPColorGradient result(*this);
  14331. result.clearColorStops();
  14332. for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
  14333. result.setColorStopAt(1.0-it.key(), it.value());
  14334. return result;
  14335. }
  14336. /*! \internal
  14337. Returns true if the color gradient uses transparency, i.e. if any of the configured color stops
  14338. has an alpha value below 255.
  14339. */
  14340. bool QCPColorGradient::stopsUseAlpha() const
  14341. {
  14342. for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
  14343. {
  14344. if (it.value().alpha() < 255)
  14345. return true;
  14346. }
  14347. return false;
  14348. }
  14349. /*! \internal
  14350. Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly
  14351. convert positions to colors. This is where the interpolation between color stops is calculated.
  14352. */
  14353. void QCPColorGradient::updateColorBuffer()
  14354. {
  14355. if (mColorBuffer.size() != mLevelCount)
  14356. mColorBuffer.resize(mLevelCount);
  14357. if (mColorStops.size() > 1)
  14358. {
  14359. double indexToPosFactor = 1.0/double(mLevelCount-1);
  14360. const bool useAlpha = stopsUseAlpha();
  14361. for (int i=0; i<mLevelCount; ++i)
  14362. {
  14363. double position = i*indexToPosFactor;
  14364. QMap<double, QColor>::const_iterator it = mColorStops.lowerBound(position);
  14365. if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop
  14366. {
  14367. if (useAlpha)
  14368. {
  14369. const QColor col = std::prev(it).value();
  14370. const double alphaPremultiplier = col.alpha()/255.0; // since we use QImage::Format_ARGB32_Premultiplied
  14371. mColorBuffer[i] = qRgba(int(col.red()*alphaPremultiplier),
  14372. int(col.green()*alphaPremultiplier),
  14373. int(col.blue()*alphaPremultiplier),
  14374. col.alpha());
  14375. } else
  14376. mColorBuffer[i] = std::prev(it).value().rgba();
  14377. } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop
  14378. {
  14379. if (useAlpha)
  14380. {
  14381. const QColor &col = it.value();
  14382. const double alphaPremultiplier = col.alpha()/255.0; // since we use QImage::Format_ARGB32_Premultiplied
  14383. mColorBuffer[i] = qRgba(int(col.red()*alphaPremultiplier),
  14384. int(col.green()*alphaPremultiplier),
  14385. int(col.blue()*alphaPremultiplier),
  14386. col.alpha());
  14387. } else
  14388. mColorBuffer[i] = it.value().rgba();
  14389. } else // position is in between stops (or on an intermediate stop), interpolate color
  14390. {
  14391. QMap<double, QColor>::const_iterator high = it;
  14392. QMap<double, QColor>::const_iterator low = std::prev(it);
  14393. double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1
  14394. switch (mColorInterpolation)
  14395. {
  14396. case ciRGB:
  14397. {
  14398. if (useAlpha)
  14399. {
  14400. const int alpha = int((1-t)*low.value().alpha() + t*high.value().alpha());
  14401. const double alphaPremultiplier = alpha/255.0; // since we use QImage::Format_ARGB32_Premultiplied
  14402. mColorBuffer[i] = qRgba(int( ((1-t)*low.value().red() + t*high.value().red())*alphaPremultiplier ),
  14403. int( ((1-t)*low.value().green() + t*high.value().green())*alphaPremultiplier ),
  14404. int( ((1-t)*low.value().blue() + t*high.value().blue())*alphaPremultiplier ),
  14405. alpha);
  14406. } else
  14407. {
  14408. mColorBuffer[i] = qRgb(int( ((1-t)*low.value().red() + t*high.value().red()) ),
  14409. int( ((1-t)*low.value().green() + t*high.value().green()) ),
  14410. int( ((1-t)*low.value().blue() + t*high.value().blue())) );
  14411. }
  14412. break;
  14413. }
  14414. case ciHSV:
  14415. {
  14416. QColor lowHsv = low.value().toHsv();
  14417. QColor highHsv = high.value().toHsv();
  14418. double hue = 0;
  14419. double hueDiff = highHsv.hueF()-lowHsv.hueF();
  14420. if (hueDiff > 0.5)
  14421. hue = lowHsv.hueF() - t*(1.0-hueDiff);
  14422. else if (hueDiff < -0.5)
  14423. hue = lowHsv.hueF() + t*(1.0+hueDiff);
  14424. else
  14425. hue = lowHsv.hueF() + t*hueDiff;
  14426. if (hue < 0) hue += 1.0;
  14427. else if (hue >= 1.0) hue -= 1.0;
  14428. if (useAlpha)
  14429. {
  14430. const QRgb rgb = QColor::fromHsvF(hue,
  14431. (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(),
  14432. (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
  14433. const double alpha = (1-t)*lowHsv.alphaF() + t*highHsv.alphaF();
  14434. mColorBuffer[i] = qRgba(int(qRed(rgb)*alpha), int(qGreen(rgb)*alpha), int(qBlue(rgb)*alpha), int(255*alpha));
  14435. }
  14436. else
  14437. {
  14438. mColorBuffer[i] = QColor::fromHsvF(hue,
  14439. (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(),
  14440. (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
  14441. }
  14442. break;
  14443. }
  14444. }
  14445. }
  14446. }
  14447. } else if (mColorStops.size() == 1)
  14448. {
  14449. const QRgb rgb = mColorStops.constBegin().value().rgb();
  14450. const double alpha = mColorStops.constBegin().value().alphaF();
  14451. mColorBuffer.fill(qRgba(int(qRed(rgb)*alpha), int(qGreen(rgb)*alpha), int(qBlue(rgb)*alpha), int(255*alpha)));
  14452. } else // mColorStops is empty, fill color buffer with black
  14453. {
  14454. mColorBuffer.fill(qRgb(0, 0, 0));
  14455. }
  14456. mColorBufferInvalidated = false;
  14457. }
  14458. /* end of 'src/colorgradient.cpp' */
  14459. /* including file 'src/selectiondecorator-bracket.cpp' */
  14460. /* modified 2021-03-29T02:30:44, size 12308 */
  14461. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14462. //////////////////// QCPSelectionDecoratorBracket
  14463. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14464. /*! \class QCPSelectionDecoratorBracket
  14465. \brief A selection decorator which draws brackets around each selected data segment
  14466. Additionally to the regular highlighting of selected segments via color, fill and scatter style,
  14467. this \ref QCPSelectionDecorator subclass draws markers at the begin and end of each selected data
  14468. segment of the plottable.
  14469. The shape of the markers can be controlled with \ref setBracketStyle, \ref setBracketWidth and
  14470. \ref setBracketHeight. The color/fill can be controlled with \ref setBracketPen and \ref
  14471. setBracketBrush.
  14472. To introduce custom bracket styles, it is only necessary to sublcass \ref
  14473. QCPSelectionDecoratorBracket and reimplement \ref drawBracket. The rest will be managed by the
  14474. base class.
  14475. */
  14476. /*!
  14477. Creates a new QCPSelectionDecoratorBracket instance with default values.
  14478. */
  14479. QCPSelectionDecoratorBracket::QCPSelectionDecoratorBracket() :
  14480. mBracketPen(QPen(Qt::black)),
  14481. mBracketBrush(Qt::NoBrush),
  14482. mBracketWidth(5),
  14483. mBracketHeight(50),
  14484. mBracketStyle(bsSquareBracket),
  14485. mTangentToData(false),
  14486. mTangentAverage(2)
  14487. {
  14488. }
  14489. QCPSelectionDecoratorBracket::~QCPSelectionDecoratorBracket()
  14490. {
  14491. }
  14492. /*!
  14493. Sets the pen that will be used to draw the brackets at the beginning and end of each selected
  14494. data segment.
  14495. */
  14496. void QCPSelectionDecoratorBracket::setBracketPen(const QPen &pen)
  14497. {
  14498. mBracketPen = pen;
  14499. }
  14500. /*!
  14501. Sets the brush that will be used to draw the brackets at the beginning and end of each selected
  14502. data segment.
  14503. */
  14504. void QCPSelectionDecoratorBracket::setBracketBrush(const QBrush &brush)
  14505. {
  14506. mBracketBrush = brush;
  14507. }
  14508. /*!
  14509. Sets the width of the drawn bracket. The width dimension is always parallel to the key axis of
  14510. the data, or the tangent direction of the current data slope, if \ref setTangentToData is
  14511. enabled.
  14512. */
  14513. void QCPSelectionDecoratorBracket::setBracketWidth(int width)
  14514. {
  14515. mBracketWidth = width;
  14516. }
  14517. /*!
  14518. Sets the height of the drawn bracket. The height dimension is always perpendicular to the key axis
  14519. of the data, or the tangent direction of the current data slope, if \ref setTangentToData is
  14520. enabled.
  14521. */
  14522. void QCPSelectionDecoratorBracket::setBracketHeight(int height)
  14523. {
  14524. mBracketHeight = height;
  14525. }
  14526. /*!
  14527. Sets the shape that the bracket/marker will have.
  14528. \see setBracketWidth, setBracketHeight
  14529. */
  14530. void QCPSelectionDecoratorBracket::setBracketStyle(QCPSelectionDecoratorBracket::BracketStyle style)
  14531. {
  14532. mBracketStyle = style;
  14533. }
  14534. /*!
  14535. Sets whether the brackets will be rotated such that they align with the slope of the data at the
  14536. position that they appear in.
  14537. For noisy data, it might be more visually appealing to average the slope over multiple data
  14538. points. This can be configured via \ref setTangentAverage.
  14539. */
  14540. void QCPSelectionDecoratorBracket::setTangentToData(bool enabled)
  14541. {
  14542. mTangentToData = enabled;
  14543. }
  14544. /*!
  14545. Controls over how many data points the slope shall be averaged, when brackets shall be aligned
  14546. with the data (if \ref setTangentToData is true).
  14547. From the position of the bracket, \a pointCount points towards the selected data range will be
  14548. taken into account. The smallest value of \a pointCount is 1, which is effectively equivalent to
  14549. disabling \ref setTangentToData.
  14550. */
  14551. void QCPSelectionDecoratorBracket::setTangentAverage(int pointCount)
  14552. {
  14553. mTangentAverage = pointCount;
  14554. if (mTangentAverage < 1)
  14555. mTangentAverage = 1;
  14556. }
  14557. /*!
  14558. Draws the bracket shape with \a painter. The parameter \a direction is either -1 or 1 and
  14559. indicates whether the bracket shall point to the left or the right (i.e. is a closing or opening
  14560. bracket, respectively).
  14561. The passed \a painter already contains all transformations that are necessary to position and
  14562. rotate the bracket appropriately. Painting operations can be performed as if drawing upright
  14563. brackets on flat data with horizontal key axis, with (0, 0) being the center of the bracket.
  14564. If you wish to sublcass \ref QCPSelectionDecoratorBracket in order to provide custom bracket
  14565. shapes (see \ref QCPSelectionDecoratorBracket::bsUserStyle), this is the method you should
  14566. reimplement.
  14567. */
  14568. void QCPSelectionDecoratorBracket::drawBracket(QCPPainter *painter, int direction) const
  14569. {
  14570. switch (mBracketStyle)
  14571. {
  14572. case bsSquareBracket:
  14573. {
  14574. painter->drawLine(QLineF(mBracketWidth*direction, -mBracketHeight*0.5, 0, -mBracketHeight*0.5));
  14575. painter->drawLine(QLineF(mBracketWidth*direction, mBracketHeight*0.5, 0, mBracketHeight*0.5));
  14576. painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5));
  14577. break;
  14578. }
  14579. case bsHalfEllipse:
  14580. {
  14581. painter->drawArc(QRectF(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight), -90*16, -180*16*direction);
  14582. break;
  14583. }
  14584. case bsEllipse:
  14585. {
  14586. painter->drawEllipse(QRectF(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight));
  14587. break;
  14588. }
  14589. case bsPlus:
  14590. {
  14591. painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5));
  14592. painter->drawLine(QLineF(-mBracketWidth*0.5, 0, mBracketWidth*0.5, 0));
  14593. break;
  14594. }
  14595. default:
  14596. {
  14597. qDebug() << Q_FUNC_INFO << "unknown/custom bracket style can't be handeld by default implementation:" << static_cast<int>(mBracketStyle);
  14598. break;
  14599. }
  14600. }
  14601. }
  14602. /*!
  14603. Draws the bracket decoration on the data points at the begin and end of each selected data
  14604. segment given in \a seletion.
  14605. It uses the method \ref drawBracket to actually draw the shapes.
  14606. \seebaseclassmethod
  14607. */
  14608. void QCPSelectionDecoratorBracket::drawDecoration(QCPPainter *painter, QCPDataSelection selection)
  14609. {
  14610. if (!mPlottable || selection.isEmpty()) return;
  14611. if (QCPPlottableInterface1D *interface1d = mPlottable->interface1D())
  14612. {
  14613. foreach (const QCPDataRange &dataRange, selection.dataRanges())
  14614. {
  14615. // determine position and (if tangent mode is enabled) angle of brackets:
  14616. int openBracketDir = (mPlottable->keyAxis() && !mPlottable->keyAxis()->rangeReversed()) ? 1 : -1;
  14617. int closeBracketDir = -openBracketDir;
  14618. QPointF openBracketPos = getPixelCoordinates(interface1d, dataRange.begin());
  14619. QPointF closeBracketPos = getPixelCoordinates(interface1d, dataRange.end()-1);
  14620. double openBracketAngle = 0;
  14621. double closeBracketAngle = 0;
  14622. if (mTangentToData)
  14623. {
  14624. openBracketAngle = getTangentAngle(interface1d, dataRange.begin(), openBracketDir);
  14625. closeBracketAngle = getTangentAngle(interface1d, dataRange.end()-1, closeBracketDir);
  14626. }
  14627. // draw opening bracket:
  14628. QTransform oldTransform = painter->transform();
  14629. painter->setPen(mBracketPen);
  14630. painter->setBrush(mBracketBrush);
  14631. painter->translate(openBracketPos);
  14632. painter->rotate(openBracketAngle/M_PI*180.0);
  14633. drawBracket(painter, openBracketDir);
  14634. painter->setTransform(oldTransform);
  14635. // draw closing bracket:
  14636. painter->setPen(mBracketPen);
  14637. painter->setBrush(mBracketBrush);
  14638. painter->translate(closeBracketPos);
  14639. painter->rotate(closeBracketAngle/M_PI*180.0);
  14640. drawBracket(painter, closeBracketDir);
  14641. painter->setTransform(oldTransform);
  14642. }
  14643. }
  14644. }
  14645. /*! \internal
  14646. If \ref setTangentToData is enabled, brackets need to be rotated according to the data slope.
  14647. This method returns the angle in radians by which a bracket at the given \a dataIndex must be
  14648. rotated.
  14649. The parameter \a direction must be set to either -1 or 1, representing whether it is an opening
  14650. or closing bracket. Since for slope calculation multiple data points are required, this defines
  14651. the direction in which the algorithm walks, starting at \a dataIndex, to average those data
  14652. points. (see \ref setTangentToData and \ref setTangentAverage)
  14653. \a interface1d is the interface to the plottable's data which is used to query data coordinates.
  14654. */
  14655. double QCPSelectionDecoratorBracket::getTangentAngle(const QCPPlottableInterface1D *interface1d, int dataIndex, int direction) const
  14656. {
  14657. if (!interface1d || dataIndex < 0 || dataIndex >= interface1d->dataCount())
  14658. return 0;
  14659. direction = direction < 0 ? -1 : 1; // enforce direction is either -1 or 1
  14660. // how many steps we can actually go from index in the given direction without exceeding data bounds:
  14661. int averageCount;
  14662. if (direction < 0)
  14663. averageCount = qMin(mTangentAverage, dataIndex);
  14664. else
  14665. averageCount = qMin(mTangentAverage, interface1d->dataCount()-1-dataIndex);
  14666. qDebug() << averageCount;
  14667. // calculate point average of averageCount points:
  14668. QVector<QPointF> points(averageCount);
  14669. QPointF pointsAverage;
  14670. int currentIndex = dataIndex;
  14671. for (int i=0; i<averageCount; ++i)
  14672. {
  14673. points[i] = getPixelCoordinates(interface1d, currentIndex);
  14674. pointsAverage += points[i];
  14675. currentIndex += direction;
  14676. }
  14677. pointsAverage /= double(averageCount);
  14678. // calculate slope of linear regression through points:
  14679. double numSum = 0;
  14680. double denomSum = 0;
  14681. for (int i=0; i<averageCount; ++i)
  14682. {
  14683. const double dx = points.at(i).x()-pointsAverage.x();
  14684. const double dy = points.at(i).y()-pointsAverage.y();
  14685. numSum += dx*dy;
  14686. denomSum += dx*dx;
  14687. }
  14688. if (!qFuzzyIsNull(denomSum) && !qFuzzyIsNull(numSum))
  14689. {
  14690. return qAtan2(numSum, denomSum);
  14691. } else // undetermined angle, probably mTangentAverage == 1, so using only one data point
  14692. return 0;
  14693. }
  14694. /*! \internal
  14695. Returns the pixel coordinates of the data point at \a dataIndex, using \a interface1d to access
  14696. the data points.
  14697. */
  14698. QPointF QCPSelectionDecoratorBracket::getPixelCoordinates(const QCPPlottableInterface1D *interface1d, int dataIndex) const
  14699. {
  14700. QCPAxis *keyAxis = mPlottable->keyAxis();
  14701. QCPAxis *valueAxis = mPlottable->valueAxis();
  14702. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {0, 0}; }
  14703. if (keyAxis->orientation() == Qt::Horizontal)
  14704. return {keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex)), valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex))};
  14705. else
  14706. return {valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex)), keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex))};
  14707. }
  14708. /* end of 'src/selectiondecorator-bracket.cpp' */
  14709. /* including file 'src/layoutelements/layoutelement-axisrect.cpp' */
  14710. /* modified 2021-03-29T02:30:44, size 47193 */
  14711. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14712. //////////////////// QCPAxisRect
  14713. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14714. /*! \class QCPAxisRect
  14715. \brief Holds multiple axes and arranges them in a rectangular shape.
  14716. This class represents an axis rect, a rectangular area that is bounded on all sides with an
  14717. arbitrary number of axes.
  14718. Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the
  14719. layout system allows to have multiple axis rects, e.g. arranged in a grid layout
  14720. (QCustomPlot::plotLayout).
  14721. By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be
  14722. accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index.
  14723. If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be
  14724. invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref
  14725. addAxes. To remove an axis, use \ref removeAxis.
  14726. The axis rect layerable itself only draws a background pixmap or color, if specified (\ref
  14727. setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an
  14728. explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be
  14729. placed on other layers, independently of the axis rect.
  14730. Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref
  14731. insetLayout and can be used to have other layout elements (or even other layouts with multiple
  14732. elements) hovering inside the axis rect.
  14733. If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The
  14734. behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel
  14735. is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable
  14736. via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are
  14737. only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref
  14738. QCP::iRangeZoom.
  14739. \image html AxisRectSpacingOverview.png
  14740. <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed
  14741. line on the far left indicates the viewport/widget border.</center>
  14742. */
  14743. /* start documentation of inline functions */
  14744. /*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const
  14745. Returns the inset layout of this axis rect. It can be used to place other layout elements (or
  14746. even layouts with multiple other elements) inside/on top of an axis rect.
  14747. \see QCPLayoutInset
  14748. */
  14749. /*! \fn int QCPAxisRect::left() const
  14750. Returns the pixel position of the left border of this axis rect. Margins are not taken into
  14751. account here, so the returned value is with respect to the inner \ref rect.
  14752. */
  14753. /*! \fn int QCPAxisRect::right() const
  14754. Returns the pixel position of the right border of this axis rect. Margins are not taken into
  14755. account here, so the returned value is with respect to the inner \ref rect.
  14756. */
  14757. /*! \fn int QCPAxisRect::top() const
  14758. Returns the pixel position of the top border of this axis rect. Margins are not taken into
  14759. account here, so the returned value is with respect to the inner \ref rect.
  14760. */
  14761. /*! \fn int QCPAxisRect::bottom() const
  14762. Returns the pixel position of the bottom border of this axis rect. Margins are not taken into
  14763. account here, so the returned value is with respect to the inner \ref rect.
  14764. */
  14765. /*! \fn int QCPAxisRect::width() const
  14766. Returns the pixel width of this axis rect. Margins are not taken into account here, so the
  14767. returned value is with respect to the inner \ref rect.
  14768. */
  14769. /*! \fn int QCPAxisRect::height() const
  14770. Returns the pixel height of this axis rect. Margins are not taken into account here, so the
  14771. returned value is with respect to the inner \ref rect.
  14772. */
  14773. /*! \fn QSize QCPAxisRect::size() const
  14774. Returns the pixel size of this axis rect. Margins are not taken into account here, so the
  14775. returned value is with respect to the inner \ref rect.
  14776. */
  14777. /*! \fn QPoint QCPAxisRect::topLeft() const
  14778. Returns the top left corner of this axis rect in pixels. Margins are not taken into account here,
  14779. so the returned value is with respect to the inner \ref rect.
  14780. */
  14781. /*! \fn QPoint QCPAxisRect::topRight() const
  14782. Returns the top right corner of this axis rect in pixels. Margins are not taken into account
  14783. here, so the returned value is with respect to the inner \ref rect.
  14784. */
  14785. /*! \fn QPoint QCPAxisRect::bottomLeft() const
  14786. Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account
  14787. here, so the returned value is with respect to the inner \ref rect.
  14788. */
  14789. /*! \fn QPoint QCPAxisRect::bottomRight() const
  14790. Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account
  14791. here, so the returned value is with respect to the inner \ref rect.
  14792. */
  14793. /*! \fn QPoint QCPAxisRect::center() const
  14794. Returns the center of this axis rect in pixels. Margins are not taken into account here, so the
  14795. returned value is with respect to the inner \ref rect.
  14796. */
  14797. /* end documentation of inline functions */
  14798. /*!
  14799. Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four
  14800. sides, the top and right axes are set invisible initially.
  14801. */
  14802. QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) :
  14803. QCPLayoutElement(parentPlot),
  14804. mBackgroundBrush(Qt::NoBrush),
  14805. mBackgroundScaled(true),
  14806. mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
  14807. mInsetLayout(new QCPLayoutInset),
  14808. mRangeDrag(Qt::Horizontal|Qt::Vertical),
  14809. mRangeZoom(Qt::Horizontal|Qt::Vertical),
  14810. mRangeZoomFactorHorz(0.85),
  14811. mRangeZoomFactorVert(0.85),
  14812. mDragging(false)
  14813. {
  14814. mInsetLayout->initializeParentPlot(mParentPlot);
  14815. mInsetLayout->setParentLayerable(this);
  14816. mInsetLayout->setParent(this);
  14817. setMinimumSize(50, 50);
  14818. setMinimumMargins(QMargins(15, 15, 15, 15));
  14819. mAxes.insert(QCPAxis::atLeft, QList<QCPAxis*>());
  14820. mAxes.insert(QCPAxis::atRight, QList<QCPAxis*>());
  14821. mAxes.insert(QCPAxis::atTop, QList<QCPAxis*>());
  14822. mAxes.insert(QCPAxis::atBottom, QList<QCPAxis*>());
  14823. if (setupDefaultAxes)
  14824. {
  14825. QCPAxis *xAxis = addAxis(QCPAxis::atBottom);
  14826. QCPAxis *yAxis = addAxis(QCPAxis::atLeft);
  14827. QCPAxis *xAxis2 = addAxis(QCPAxis::atTop);
  14828. QCPAxis *yAxis2 = addAxis(QCPAxis::atRight);
  14829. setRangeDragAxes(xAxis, yAxis);
  14830. setRangeZoomAxes(xAxis, yAxis);
  14831. xAxis2->setVisible(false);
  14832. yAxis2->setVisible(false);
  14833. xAxis->grid()->setVisible(true);
  14834. yAxis->grid()->setVisible(true);
  14835. xAxis2->grid()->setVisible(false);
  14836. yAxis2->grid()->setVisible(false);
  14837. xAxis2->grid()->setZeroLinePen(Qt::NoPen);
  14838. yAxis2->grid()->setZeroLinePen(Qt::NoPen);
  14839. xAxis2->grid()->setVisible(false);
  14840. yAxis2->grid()->setVisible(false);
  14841. }
  14842. }
  14843. QCPAxisRect::~QCPAxisRect()
  14844. {
  14845. delete mInsetLayout;
  14846. mInsetLayout = nullptr;
  14847. foreach (QCPAxis *axis, axes())
  14848. removeAxis(axis);
  14849. }
  14850. /*!
  14851. Returns the number of axes on the axis rect side specified with \a type.
  14852. \see axis
  14853. */
  14854. int QCPAxisRect::axisCount(QCPAxis::AxisType type) const
  14855. {
  14856. return mAxes.value(type).size();
  14857. }
  14858. /*!
  14859. Returns the axis with the given \a index on the axis rect side specified with \a type.
  14860. \see axisCount, axes
  14861. */
  14862. QCPAxis *QCPAxisRect::axis(QCPAxis::AxisType type, int index) const
  14863. {
  14864. QList<QCPAxis*> ax(mAxes.value(type));
  14865. if (index >= 0 && index < ax.size())
  14866. {
  14867. return ax.at(index);
  14868. } else
  14869. {
  14870. qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index;
  14871. return nullptr;
  14872. }
  14873. }
  14874. /*!
  14875. Returns all axes on the axis rect sides specified with \a types.
  14876. \a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of
  14877. multiple sides.
  14878. \see axis
  14879. */
  14880. QList<QCPAxis*> QCPAxisRect::axes(QCPAxis::AxisTypes types) const
  14881. {
  14882. QList<QCPAxis*> result;
  14883. if (types.testFlag(QCPAxis::atLeft))
  14884. result << mAxes.value(QCPAxis::atLeft);
  14885. if (types.testFlag(QCPAxis::atRight))
  14886. result << mAxes.value(QCPAxis::atRight);
  14887. if (types.testFlag(QCPAxis::atTop))
  14888. result << mAxes.value(QCPAxis::atTop);
  14889. if (types.testFlag(QCPAxis::atBottom))
  14890. result << mAxes.value(QCPAxis::atBottom);
  14891. return result;
  14892. }
  14893. /*! \overload
  14894. Returns all axes of this axis rect.
  14895. */
  14896. QList<QCPAxis*> QCPAxisRect::axes() const
  14897. {
  14898. QList<QCPAxis*> result;
  14899. QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
  14900. while (it.hasNext())
  14901. {
  14902. it.next();
  14903. result << it.value();
  14904. }
  14905. return result;
  14906. }
  14907. /*!
  14908. Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a
  14909. new QCPAxis instance is created internally. QCustomPlot owns the returned axis, so if you want to
  14910. remove an axis, use \ref removeAxis instead of deleting it manually.
  14911. You may inject QCPAxis instances (or subclasses of QCPAxis) by setting \a axis to an axis that was
  14912. previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership
  14913. of the axis, so you may not delete it afterwards. Further, the \a axis must have been created
  14914. with this axis rect as parent and with the same axis type as specified in \a type. If this is not
  14915. the case, a debug output is generated, the axis is not added, and the method returns \c nullptr.
  14916. This method can not be used to move \a axis between axis rects. The same \a axis instance must
  14917. not be added multiple times to the same or different axis rects.
  14918. If an axis rect side already contains one or more axes, the lower and upper endings of the new
  14919. axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref
  14920. QCPLineEnding::esHalfBar.
  14921. \see addAxes, setupFullAxesBox
  14922. */
  14923. QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type, QCPAxis *axis)
  14924. {
  14925. QCPAxis *newAxis = axis;
  14926. if (!newAxis)
  14927. {
  14928. newAxis = new QCPAxis(this, type);
  14929. } else // user provided existing axis instance, do some sanity checks
  14930. {
  14931. if (newAxis->axisType() != type)
  14932. {
  14933. qDebug() << Q_FUNC_INFO << "passed axis has different axis type than specified in type parameter";
  14934. return nullptr;
  14935. }
  14936. if (newAxis->axisRect() != this)
  14937. {
  14938. qDebug() << Q_FUNC_INFO << "passed axis doesn't have this axis rect as parent axis rect";
  14939. return nullptr;
  14940. }
  14941. if (axes().contains(newAxis))
  14942. {
  14943. qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect";
  14944. return nullptr;
  14945. }
  14946. }
  14947. if (!mAxes[type].isEmpty()) // multiple axes on one side, add half-bar axis ending to additional axes with offset
  14948. {
  14949. bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom);
  14950. newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert));
  14951. newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert));
  14952. }
  14953. mAxes[type].append(newAxis);
  14954. // reset convenience axis pointers on parent QCustomPlot if they are unset:
  14955. if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this)
  14956. {
  14957. switch (type)
  14958. {
  14959. case QCPAxis::atBottom: { if (!mParentPlot->xAxis) mParentPlot->xAxis = newAxis; break; }
  14960. case QCPAxis::atLeft: { if (!mParentPlot->yAxis) mParentPlot->yAxis = newAxis; break; }
  14961. case QCPAxis::atTop: { if (!mParentPlot->xAxis2) mParentPlot->xAxis2 = newAxis; break; }
  14962. case QCPAxis::atRight: { if (!mParentPlot->yAxis2) mParentPlot->yAxis2 = newAxis; break; }
  14963. }
  14964. }
  14965. return newAxis;
  14966. }
  14967. /*!
  14968. Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an
  14969. <tt>or</tt>-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once.
  14970. Returns a list of the added axes.
  14971. \see addAxis, setupFullAxesBox
  14972. */
  14973. QList<QCPAxis*> QCPAxisRect::addAxes(QCPAxis::AxisTypes types)
  14974. {
  14975. QList<QCPAxis*> result;
  14976. if (types.testFlag(QCPAxis::atLeft))
  14977. result << addAxis(QCPAxis::atLeft);
  14978. if (types.testFlag(QCPAxis::atRight))
  14979. result << addAxis(QCPAxis::atRight);
  14980. if (types.testFlag(QCPAxis::atTop))
  14981. result << addAxis(QCPAxis::atTop);
  14982. if (types.testFlag(QCPAxis::atBottom))
  14983. result << addAxis(QCPAxis::atBottom);
  14984. return result;
  14985. }
  14986. /*!
  14987. Removes the specified \a axis from the axis rect and deletes it.
  14988. Returns true on success, i.e. if \a axis was a valid axis in this axis rect.
  14989. \see addAxis
  14990. */
  14991. bool QCPAxisRect::removeAxis(QCPAxis *axis)
  14992. {
  14993. // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers:
  14994. QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
  14995. while (it.hasNext())
  14996. {
  14997. it.next();
  14998. if (it.value().contains(axis))
  14999. {
  15000. 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)
  15001. it.value()[1]->setOffset(axis->offset());
  15002. mAxes[it.key()].removeOne(axis);
  15003. 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)
  15004. parentPlot()->axisRemoved(axis);
  15005. delete axis;
  15006. return true;
  15007. }
  15008. }
  15009. qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast<quintptr>(axis);
  15010. return false;
  15011. }
  15012. /*!
  15013. Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates.
  15014. All axes of this axis rect will have their range zoomed accordingly. If you only wish to zoom
  15015. specific axes, use the overloaded version of this method.
  15016. \see QCustomPlot::setSelectionRectMode
  15017. */
  15018. void QCPAxisRect::zoom(const QRectF &pixelRect)
  15019. {
  15020. zoom(pixelRect, axes());
  15021. }
  15022. /*! \overload
  15023. Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates.
  15024. Only the axes passed in \a affectedAxes will have their ranges zoomed accordingly.
  15025. \see QCustomPlot::setSelectionRectMode
  15026. */
  15027. void QCPAxisRect::zoom(const QRectF &pixelRect, const QList<QCPAxis*> &affectedAxes)
  15028. {
  15029. foreach (QCPAxis *axis, affectedAxes)
  15030. {
  15031. if (!axis)
  15032. {
  15033. qDebug() << Q_FUNC_INFO << "a passed axis was zero";
  15034. continue;
  15035. }
  15036. QCPRange pixelRange;
  15037. if (axis->orientation() == Qt::Horizontal)
  15038. pixelRange = QCPRange(pixelRect.left(), pixelRect.right());
  15039. else
  15040. pixelRange = QCPRange(pixelRect.top(), pixelRect.bottom());
  15041. axis->setRange(axis->pixelToCoord(pixelRange.lower), axis->pixelToCoord(pixelRange.upper));
  15042. }
  15043. }
  15044. /*!
  15045. Convenience function to create an axis on each side that doesn't have any axes yet and set their
  15046. visibility to true. Further, the top/right axes are assigned the following properties of the
  15047. bottom/left axes:
  15048. \li range (\ref QCPAxis::setRange)
  15049. \li range reversed (\ref QCPAxis::setRangeReversed)
  15050. \li scale type (\ref QCPAxis::setScaleType)
  15051. \li tick visibility (\ref QCPAxis::setTicks)
  15052. \li number format (\ref QCPAxis::setNumberFormat)
  15053. \li number precision (\ref QCPAxis::setNumberPrecision)
  15054. \li tick count of ticker (\ref QCPAxisTicker::setTickCount)
  15055. \li tick origin of ticker (\ref QCPAxisTicker::setTickOrigin)
  15056. Tick label visibility (\ref QCPAxis::setTickLabels) of the right and top axes are set to false.
  15057. If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom
  15058. and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes.
  15059. */
  15060. void QCPAxisRect::setupFullAxesBox(bool connectRanges)
  15061. {
  15062. QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2;
  15063. if (axisCount(QCPAxis::atBottom) == 0)
  15064. xAxis = addAxis(QCPAxis::atBottom);
  15065. else
  15066. xAxis = axis(QCPAxis::atBottom);
  15067. if (axisCount(QCPAxis::atLeft) == 0)
  15068. yAxis = addAxis(QCPAxis::atLeft);
  15069. else
  15070. yAxis = axis(QCPAxis::atLeft);
  15071. if (axisCount(QCPAxis::atTop) == 0)
  15072. xAxis2 = addAxis(QCPAxis::atTop);
  15073. else
  15074. xAxis2 = axis(QCPAxis::atTop);
  15075. if (axisCount(QCPAxis::atRight) == 0)
  15076. yAxis2 = addAxis(QCPAxis::atRight);
  15077. else
  15078. yAxis2 = axis(QCPAxis::atRight);
  15079. xAxis->setVisible(true);
  15080. yAxis->setVisible(true);
  15081. xAxis2->setVisible(true);
  15082. yAxis2->setVisible(true);
  15083. xAxis2->setTickLabels(false);
  15084. yAxis2->setTickLabels(false);
  15085. xAxis2->setRange(xAxis->range());
  15086. xAxis2->setRangeReversed(xAxis->rangeReversed());
  15087. xAxis2->setScaleType(xAxis->scaleType());
  15088. xAxis2->setTicks(xAxis->ticks());
  15089. xAxis2->setNumberFormat(xAxis->numberFormat());
  15090. xAxis2->setNumberPrecision(xAxis->numberPrecision());
  15091. xAxis2->ticker()->setTickCount(xAxis->ticker()->tickCount());
  15092. xAxis2->ticker()->setTickOrigin(xAxis->ticker()->tickOrigin());
  15093. yAxis2->setRange(yAxis->range());
  15094. yAxis2->setRangeReversed(yAxis->rangeReversed());
  15095. yAxis2->setScaleType(yAxis->scaleType());
  15096. yAxis2->setTicks(yAxis->ticks());
  15097. yAxis2->setNumberFormat(yAxis->numberFormat());
  15098. yAxis2->setNumberPrecision(yAxis->numberPrecision());
  15099. yAxis2->ticker()->setTickCount(yAxis->ticker()->tickCount());
  15100. yAxis2->ticker()->setTickOrigin(yAxis->ticker()->tickOrigin());
  15101. if (connectRanges)
  15102. {
  15103. connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange)));
  15104. connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange)));
  15105. }
  15106. }
  15107. /*!
  15108. Returns a list of all the plottables that are associated with this axis rect.
  15109. A plottable is considered associated with an axis rect if its key or value axis (or both) is in
  15110. this axis rect.
  15111. \see graphs, items
  15112. */
  15113. QList<QCPAbstractPlottable*> QCPAxisRect::plottables() const
  15114. {
  15115. // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries
  15116. QList<QCPAbstractPlottable*> result;
  15117. foreach (QCPAbstractPlottable *plottable, mParentPlot->mPlottables)
  15118. {
  15119. if (plottable->keyAxis()->axisRect() == this || plottable->valueAxis()->axisRect() == this)
  15120. result.append(plottable);
  15121. }
  15122. return result;
  15123. }
  15124. /*!
  15125. Returns a list of all the graphs that are associated with this axis rect.
  15126. A graph is considered associated with an axis rect if its key or value axis (or both) is in
  15127. this axis rect.
  15128. \see plottables, items
  15129. */
  15130. QList<QCPGraph*> QCPAxisRect::graphs() const
  15131. {
  15132. // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries
  15133. QList<QCPGraph*> result;
  15134. foreach (QCPGraph *graph, mParentPlot->mGraphs)
  15135. {
  15136. if (graph->keyAxis()->axisRect() == this || graph->valueAxis()->axisRect() == this)
  15137. result.append(graph);
  15138. }
  15139. return result;
  15140. }
  15141. /*!
  15142. Returns a list of all the items that are associated with this axis rect.
  15143. An item is considered associated with an axis rect if any of its positions has key or value axis
  15144. set to an axis that is in this axis rect, or if any of its positions has \ref
  15145. QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref
  15146. QCPAbstractItem::setClipAxisRect) is set to this axis rect.
  15147. \see plottables, graphs
  15148. */
  15149. QList<QCPAbstractItem *> QCPAxisRect::items() const
  15150. {
  15151. // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries
  15152. // and miss those items that have this axis rect as clipAxisRect.
  15153. QList<QCPAbstractItem*> result;
  15154. foreach (QCPAbstractItem *item, mParentPlot->mItems)
  15155. {
  15156. if (item->clipAxisRect() == this)
  15157. {
  15158. result.append(item);
  15159. continue;
  15160. }
  15161. foreach (QCPItemPosition *position, item->positions())
  15162. {
  15163. if (position->axisRect() == this ||
  15164. position->keyAxis()->axisRect() == this ||
  15165. position->valueAxis()->axisRect() == this)
  15166. {
  15167. result.append(item);
  15168. break;
  15169. }
  15170. }
  15171. }
  15172. return result;
  15173. }
  15174. /*!
  15175. This method is called automatically upon replot and doesn't need to be called by users of
  15176. QCPAxisRect.
  15177. Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
  15178. and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
  15179. QCPInsetLayout::update function.
  15180. \seebaseclassmethod
  15181. */
  15182. void QCPAxisRect::update(UpdatePhase phase)
  15183. {
  15184. QCPLayoutElement::update(phase);
  15185. switch (phase)
  15186. {
  15187. case upPreparation:
  15188. {
  15189. foreach (QCPAxis *axis, axes())
  15190. axis->setupTickVectors();
  15191. break;
  15192. }
  15193. case upLayout:
  15194. {
  15195. mInsetLayout->setOuterRect(rect());
  15196. break;
  15197. }
  15198. default: break;
  15199. }
  15200. // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout):
  15201. mInsetLayout->update(phase);
  15202. }
  15203. /* inherits documentation from base class */
  15204. QList<QCPLayoutElement*> QCPAxisRect::elements(bool recursive) const
  15205. {
  15206. QList<QCPLayoutElement*> result;
  15207. if (mInsetLayout)
  15208. {
  15209. result << mInsetLayout;
  15210. if (recursive)
  15211. result << mInsetLayout->elements(recursive);
  15212. }
  15213. return result;
  15214. }
  15215. /* inherits documentation from base class */
  15216. void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const
  15217. {
  15218. painter->setAntialiasing(false);
  15219. }
  15220. /* inherits documentation from base class */
  15221. void QCPAxisRect::draw(QCPPainter *painter)
  15222. {
  15223. drawBackground(painter);
  15224. }
  15225. /*!
  15226. Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the
  15227. axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect
  15228. backgrounds are usually drawn below everything else.
  15229. For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be
  15230. enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio
  15231. is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  15232. consider using the overloaded version of this function.
  15233. Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref
  15234. setBackground(const QBrush &brush).
  15235. \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush)
  15236. */
  15237. void QCPAxisRect::setBackground(const QPixmap &pm)
  15238. {
  15239. mBackgroundPixmap = pm;
  15240. mScaledBackgroundPixmap = QPixmap();
  15241. }
  15242. /*! \overload
  15243. Sets \a brush as the background brush. The axis rect background will be filled with this brush.
  15244. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds
  15245. are usually drawn below everything else.
  15246. The brush will be drawn before (under) any background pixmap, which may be specified with \ref
  15247. setBackground(const QPixmap &pm).
  15248. To disable drawing of a background brush, set \a brush to Qt::NoBrush.
  15249. \see setBackground(const QPixmap &pm)
  15250. */
  15251. void QCPAxisRect::setBackground(const QBrush &brush)
  15252. {
  15253. mBackgroundBrush = brush;
  15254. }
  15255. /*! \overload
  15256. Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it
  15257. shall be scaled in one call.
  15258. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  15259. */
  15260. void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
  15261. {
  15262. mBackgroundPixmap = pm;
  15263. mScaledBackgroundPixmap = QPixmap();
  15264. mBackgroundScaled = scaled;
  15265. mBackgroundScaledMode = mode;
  15266. }
  15267. /*!
  15268. Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled
  15269. is set to true, you may control whether and how the aspect ratio of the original pixmap is
  15270. preserved with \ref setBackgroundScaledMode.
  15271. Note that the scaled version of the original pixmap is buffered, so there is no performance
  15272. penalty on replots. (Except when the axis rect dimensions are changed continuously.)
  15273. \see setBackground, setBackgroundScaledMode
  15274. */
  15275. void QCPAxisRect::setBackgroundScaled(bool scaled)
  15276. {
  15277. mBackgroundScaled = scaled;
  15278. }
  15279. /*!
  15280. If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to
  15281. define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved.
  15282. \see setBackground, setBackgroundScaled
  15283. */
  15284. void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  15285. {
  15286. mBackgroundScaledMode = mode;
  15287. }
  15288. /*!
  15289. Returns the range drag axis of the \a orientation provided. If multiple axes were set, returns
  15290. the first one (use \ref rangeDragAxes to retrieve a list with all set axes).
  15291. \see setRangeDragAxes
  15292. */
  15293. QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation)
  15294. {
  15295. if (orientation == Qt::Horizontal)
  15296. return mRangeDragHorzAxis.isEmpty() ? nullptr : mRangeDragHorzAxis.first().data();
  15297. else
  15298. return mRangeDragVertAxis.isEmpty() ? nullptr : mRangeDragVertAxis.first().data();
  15299. }
  15300. /*!
  15301. Returns the range zoom axis of the \a orientation provided. If multiple axes were set, returns
  15302. the first one (use \ref rangeZoomAxes to retrieve a list with all set axes).
  15303. \see setRangeZoomAxes
  15304. */
  15305. QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation)
  15306. {
  15307. if (orientation == Qt::Horizontal)
  15308. return mRangeZoomHorzAxis.isEmpty() ? nullptr : mRangeZoomHorzAxis.first().data();
  15309. else
  15310. return mRangeZoomVertAxis.isEmpty() ? nullptr : mRangeZoomVertAxis.first().data();
  15311. }
  15312. /*!
  15313. Returns all range drag axes of the \a orientation provided.
  15314. \see rangeZoomAxis, setRangeZoomAxes
  15315. */
  15316. QList<QCPAxis*> QCPAxisRect::rangeDragAxes(Qt::Orientation orientation)
  15317. {
  15318. QList<QCPAxis*> result;
  15319. if (orientation == Qt::Horizontal)
  15320. {
  15321. foreach (QPointer<QCPAxis> axis, mRangeDragHorzAxis)
  15322. {
  15323. if (!axis.isNull())
  15324. result.append(axis.data());
  15325. }
  15326. } else
  15327. {
  15328. foreach (QPointer<QCPAxis> axis, mRangeDragVertAxis)
  15329. {
  15330. if (!axis.isNull())
  15331. result.append(axis.data());
  15332. }
  15333. }
  15334. return result;
  15335. }
  15336. /*!
  15337. Returns all range zoom axes of the \a orientation provided.
  15338. \see rangeDragAxis, setRangeDragAxes
  15339. */
  15340. QList<QCPAxis*> QCPAxisRect::rangeZoomAxes(Qt::Orientation orientation)
  15341. {
  15342. QList<QCPAxis*> result;
  15343. if (orientation == Qt::Horizontal)
  15344. {
  15345. foreach (QPointer<QCPAxis> axis, mRangeZoomHorzAxis)
  15346. {
  15347. if (!axis.isNull())
  15348. result.append(axis.data());
  15349. }
  15350. } else
  15351. {
  15352. foreach (QPointer<QCPAxis> axis, mRangeZoomVertAxis)
  15353. {
  15354. if (!axis.isNull())
  15355. result.append(axis.data());
  15356. }
  15357. }
  15358. return result;
  15359. }
  15360. /*!
  15361. Returns the range zoom factor of the \a orientation provided.
  15362. \see setRangeZoomFactor
  15363. */
  15364. double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation)
  15365. {
  15366. return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert);
  15367. }
  15368. /*!
  15369. Sets which axis orientation may be range dragged by the user with mouse interaction.
  15370. What orientation corresponds to which specific axis can be set with
  15371. \ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By
  15372. default, the horizontal axis is the bottom axis (xAxis) and the vertical axis
  15373. is the left axis (yAxis).
  15374. To disable range dragging entirely, pass \c nullptr as \a orientations or remove \ref
  15375. QCP::iRangeDrag from \ref QCustomPlot::setInteractions. To enable range dragging for both
  15376. directions, pass <tt>Qt::Horizontal | Qt::Vertical</tt> as \a orientations.
  15377. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
  15378. contains \ref QCP::iRangeDrag to enable the range dragging interaction.
  15379. \see setRangeZoom, setRangeDragAxes, QCustomPlot::setNoAntialiasingOnDrag
  15380. */
  15381. void QCPAxisRect::setRangeDrag(Qt::Orientations orientations)
  15382. {
  15383. mRangeDrag = orientations;
  15384. }
  15385. /*!
  15386. Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation
  15387. corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal,
  15388. QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical
  15389. axis is the left axis (yAxis).
  15390. To disable range zooming entirely, pass \c nullptr as \a orientations or remove \ref
  15391. QCP::iRangeZoom from \ref QCustomPlot::setInteractions. To enable range zooming for both
  15392. directions, pass <tt>Qt::Horizontal | Qt::Vertical</tt> as \a orientations.
  15393. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
  15394. contains \ref QCP::iRangeZoom to enable the range zooming interaction.
  15395. \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag
  15396. */
  15397. void QCPAxisRect::setRangeZoom(Qt::Orientations orientations)
  15398. {
  15399. mRangeZoom = orientations;
  15400. }
  15401. /*! \overload
  15402. Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging on
  15403. the QCustomPlot widget. Pass \c nullptr if no axis shall be dragged in the respective
  15404. orientation.
  15405. Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall
  15406. react to dragging interactions.
  15407. \see setRangeZoomAxes
  15408. */
  15409. void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical)
  15410. {
  15411. QList<QCPAxis*> horz, vert;
  15412. if (horizontal)
  15413. horz.append(horizontal);
  15414. if (vertical)
  15415. vert.append(vertical);
  15416. setRangeDragAxes(horz, vert);
  15417. }
  15418. /*! \overload
  15419. This method allows to set up multiple axes to react to horizontal and vertical dragging. The drag
  15420. orientation that the respective axis will react to is deduced from its orientation (\ref
  15421. QCPAxis::orientation).
  15422. In the unusual case that you wish to e.g. drag a vertically oriented axis with a horizontal drag
  15423. motion, use the overload taking two separate lists for horizontal and vertical dragging.
  15424. */
  15425. void QCPAxisRect::setRangeDragAxes(QList<QCPAxis*> axes)
  15426. {
  15427. QList<QCPAxis*> horz, vert;
  15428. foreach (QCPAxis *ax, axes)
  15429. {
  15430. if (ax->orientation() == Qt::Horizontal)
  15431. horz.append(ax);
  15432. else
  15433. vert.append(ax);
  15434. }
  15435. setRangeDragAxes(horz, vert);
  15436. }
  15437. /*! \overload
  15438. This method allows to set multiple axes up to react to horizontal and vertical dragging, and
  15439. define specifically which axis reacts to which drag orientation (irrespective of the axis
  15440. orientation).
  15441. */
  15442. void QCPAxisRect::setRangeDragAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical)
  15443. {
  15444. mRangeDragHorzAxis.clear();
  15445. foreach (QCPAxis *ax, horizontal)
  15446. {
  15447. QPointer<QCPAxis> axPointer(ax);
  15448. if (!axPointer.isNull())
  15449. mRangeDragHorzAxis.append(axPointer);
  15450. else
  15451. qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast<quintptr>(ax);
  15452. }
  15453. mRangeDragVertAxis.clear();
  15454. foreach (QCPAxis *ax, vertical)
  15455. {
  15456. QPointer<QCPAxis> axPointer(ax);
  15457. if (!axPointer.isNull())
  15458. mRangeDragVertAxis.append(axPointer);
  15459. else
  15460. qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast<quintptr>(ax);
  15461. }
  15462. }
  15463. /*!
  15464. Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on
  15465. the QCustomPlot widget. Pass \c nullptr if no axis shall be zoomed in the respective orientation.
  15466. The two axes can be zoomed with different strengths, when different factors are passed to \ref
  15467. setRangeZoomFactor(double horizontalFactor, double verticalFactor).
  15468. Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall
  15469. react to zooming interactions.
  15470. \see setRangeDragAxes
  15471. */
  15472. void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical)
  15473. {
  15474. QList<QCPAxis*> horz, vert;
  15475. if (horizontal)
  15476. horz.append(horizontal);
  15477. if (vertical)
  15478. vert.append(vertical);
  15479. setRangeZoomAxes(horz, vert);
  15480. }
  15481. /*! \overload
  15482. This method allows to set up multiple axes to react to horizontal and vertical range zooming. The
  15483. zoom orientation that the respective axis will react to is deduced from its orientation (\ref
  15484. QCPAxis::orientation).
  15485. In the unusual case that you wish to e.g. zoom a vertically oriented axis with a horizontal zoom
  15486. interaction, use the overload taking two separate lists for horizontal and vertical zooming.
  15487. */
  15488. void QCPAxisRect::setRangeZoomAxes(QList<QCPAxis*> axes)
  15489. {
  15490. QList<QCPAxis*> horz, vert;
  15491. foreach (QCPAxis *ax, axes)
  15492. {
  15493. if (ax->orientation() == Qt::Horizontal)
  15494. horz.append(ax);
  15495. else
  15496. vert.append(ax);
  15497. }
  15498. setRangeZoomAxes(horz, vert);
  15499. }
  15500. /*! \overload
  15501. This method allows to set multiple axes up to react to horizontal and vertical zooming, and
  15502. define specifically which axis reacts to which zoom orientation (irrespective of the axis
  15503. orientation).
  15504. */
  15505. void QCPAxisRect::setRangeZoomAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical)
  15506. {
  15507. mRangeZoomHorzAxis.clear();
  15508. foreach (QCPAxis *ax, horizontal)
  15509. {
  15510. QPointer<QCPAxis> axPointer(ax);
  15511. if (!axPointer.isNull())
  15512. mRangeZoomHorzAxis.append(axPointer);
  15513. else
  15514. qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast<quintptr>(ax);
  15515. }
  15516. mRangeZoomVertAxis.clear();
  15517. foreach (QCPAxis *ax, vertical)
  15518. {
  15519. QPointer<QCPAxis> axPointer(ax);
  15520. if (!axPointer.isNull())
  15521. mRangeZoomVertAxis.append(axPointer);
  15522. else
  15523. qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast<quintptr>(ax);
  15524. }
  15525. }
  15526. /*!
  15527. Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with
  15528. \ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to
  15529. let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal
  15530. and which is vertical, can be set with \ref setRangeZoomAxes.
  15531. When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user)
  15532. will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the
  15533. same scrolling direction will zoom out.
  15534. */
  15535. void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor)
  15536. {
  15537. mRangeZoomFactorHorz = horizontalFactor;
  15538. mRangeZoomFactorVert = verticalFactor;
  15539. }
  15540. /*! \overload
  15541. Sets both the horizontal and vertical zoom \a factor.
  15542. */
  15543. void QCPAxisRect::setRangeZoomFactor(double factor)
  15544. {
  15545. mRangeZoomFactorHorz = factor;
  15546. mRangeZoomFactorVert = factor;
  15547. }
  15548. /*! \internal
  15549. Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a
  15550. pixmap.
  15551. If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an
  15552. according filling inside the axis rect with the provided \a painter.
  15553. Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version
  15554. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  15555. the axis rect with the provided \a painter. The scaled version is buffered in
  15556. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  15557. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  15558. dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
  15559. set.
  15560. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  15561. */
  15562. void QCPAxisRect::drawBackground(QCPPainter *painter)
  15563. {
  15564. // draw background fill:
  15565. if (mBackgroundBrush != Qt::NoBrush)
  15566. painter->fillRect(mRect, mBackgroundBrush);
  15567. // draw background pixmap (on top of fill, if brush specified):
  15568. if (!mBackgroundPixmap.isNull())
  15569. {
  15570. if (mBackgroundScaled)
  15571. {
  15572. // check whether mScaledBackground needs to be updated:
  15573. QSizeF scaledSize(mBackgroundPixmap.size());
  15574. scaledSize.scale(mRect.size(), mBackgroundScaledMode);
  15575. if (mScaledBackgroundPixmap.size() != scaledSize)
  15576. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size().toSize(), mBackgroundScaledMode, Qt::SmoothTransformation);
  15577. painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect());
  15578. } else
  15579. {
  15580. painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()));
  15581. }
  15582. }
  15583. }
  15584. /*! \internal
  15585. This function makes sure multiple axes on the side specified with \a type don't collide, but are
  15586. distributed according to their respective space requirement (QCPAxis::calculateMargin).
  15587. It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the
  15588. one with index zero.
  15589. This function is called by \ref calculateAutoMargin.
  15590. */
  15591. void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type)
  15592. {
  15593. const QList<QCPAxis*> axesList = mAxes.value(type);
  15594. if (axesList.isEmpty())
  15595. return;
  15596. 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
  15597. for (int i=1; i<axesList.size(); ++i)
  15598. {
  15599. int offset = axesList.at(i-1)->offset() + axesList.at(i-1)->calculateMargin();
  15600. 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)
  15601. {
  15602. if (!isFirstVisible)
  15603. offset += axesList.at(i)->tickLengthIn();
  15604. isFirstVisible = false;
  15605. }
  15606. axesList.at(i)->setOffset(offset);
  15607. }
  15608. }
  15609. /* inherits documentation from base class */
  15610. double QCPAxisRect::calculateAutoMargin(QCP::MarginSide side)
  15611. {
  15612. if (!mAutoMargins.testFlag(side))
  15613. qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin";
  15614. updateAxesOffset(QCPAxis::marginSideToAxisType(side));
  15615. // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call
  15616. const QList<QCPAxis*> axesList = mAxes.value(QCPAxis::marginSideToAxisType(side));
  15617. if (!axesList.isEmpty())
  15618. return axesList.last()->offset() + axesList.last()->calculateMargin();
  15619. else
  15620. return 0;
  15621. }
  15622. /*! \internal
  15623. Reacts to a change in layout to potentially set the convenience axis pointers \ref
  15624. QCustomPlot::xAxis, \ref QCustomPlot::yAxis, etc. of the parent QCustomPlot to the respective
  15625. axes of this axis rect. This is only done if the respective convenience pointer is currently zero
  15626. and if there is no QCPAxisRect at position (0, 0) of the plot layout.
  15627. This automation makes it simpler to replace the main axis rect with a newly created one, without
  15628. the need to manually reset the convenience pointers.
  15629. */
  15630. void QCPAxisRect::layoutChanged()
  15631. {
  15632. if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this)
  15633. {
  15634. if (axisCount(QCPAxis::atBottom) > 0 && !mParentPlot->xAxis)
  15635. mParentPlot->xAxis = axis(QCPAxis::atBottom);
  15636. if (axisCount(QCPAxis::atLeft) > 0 && !mParentPlot->yAxis)
  15637. mParentPlot->yAxis = axis(QCPAxis::atLeft);
  15638. if (axisCount(QCPAxis::atTop) > 0 && !mParentPlot->xAxis2)
  15639. mParentPlot->xAxis2 = axis(QCPAxis::atTop);
  15640. if (axisCount(QCPAxis::atRight) > 0 && !mParentPlot->yAxis2)
  15641. mParentPlot->yAxis2 = axis(QCPAxis::atRight);
  15642. }
  15643. }
  15644. /*! \internal
  15645. Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
  15646. pressed, the range dragging interaction is initialized (the actual range manipulation happens in
  15647. the \ref mouseMoveEvent).
  15648. The mDragging flag is set to true and some anchor points are set that are needed to determine the
  15649. distance the mouse was dragged in the mouse move/release events later.
  15650. \see mouseMoveEvent, mouseReleaseEvent
  15651. */
  15652. void QCPAxisRect::mousePressEvent(QMouseEvent *event, const QVariant &details)
  15653. {
  15654. Q_UNUSED(details)
  15655. if (event->buttons() & Qt::LeftButton)
  15656. {
  15657. mDragging = true;
  15658. // initialize antialiasing backup in case we start dragging:
  15659. if (mParentPlot->noAntialiasingOnDrag())
  15660. {
  15661. mAADragBackup = mParentPlot->antialiasedElements();
  15662. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  15663. }
  15664. // Mouse range dragging interaction:
  15665. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  15666. {
  15667. mDragStartHorzRange.clear();
  15668. foreach (QPointer<QCPAxis> axis, mRangeDragHorzAxis)
  15669. mDragStartHorzRange.append(axis.isNull() ? QCPRange() : axis->range());
  15670. mDragStartVertRange.clear();
  15671. foreach (QPointer<QCPAxis> axis, mRangeDragVertAxis)
  15672. mDragStartVertRange.append(axis.isNull() ? QCPRange() : axis->range());
  15673. }
  15674. }
  15675. }
  15676. /*! \internal
  15677. Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a
  15678. preceding \ref mousePressEvent, the range is moved accordingly.
  15679. \see mousePressEvent, mouseReleaseEvent
  15680. */
  15681. void QCPAxisRect::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  15682. {
  15683. Q_UNUSED(startPos)
  15684. // Mouse range dragging interaction:
  15685. if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  15686. {
  15687. if (mRangeDrag.testFlag(Qt::Horizontal))
  15688. {
  15689. for (int i=0; i<mRangeDragHorzAxis.size(); ++i)
  15690. {
  15691. QCPAxis *ax = mRangeDragHorzAxis.at(i).data();
  15692. if (!ax)
  15693. continue;
  15694. if (i >= mDragStartHorzRange.size())
  15695. break;
  15696. if (ax->mScaleType == QCPAxis::stLinear)
  15697. {
  15698. double diff = ax->pixelToCoord(startPos.x()) - ax->pixelToCoord(event->pos().x());
  15699. ax->setRange(mDragStartHorzRange.at(i).lower+diff, mDragStartHorzRange.at(i).upper+diff);
  15700. } else if (ax->mScaleType == QCPAxis::stLogarithmic)
  15701. {
  15702. double diff = ax->pixelToCoord(startPos.x()) / ax->pixelToCoord(event->pos().x());
  15703. ax->setRange(mDragStartHorzRange.at(i).lower*diff, mDragStartHorzRange.at(i).upper*diff);
  15704. }
  15705. }
  15706. }
  15707. if (mRangeDrag.testFlag(Qt::Vertical))
  15708. {
  15709. for (int i=0; i<mRangeDragVertAxis.size(); ++i)
  15710. {
  15711. QCPAxis *ax = mRangeDragVertAxis.at(i).data();
  15712. if (!ax)
  15713. continue;
  15714. if (i >= mDragStartVertRange.size())
  15715. break;
  15716. if (ax->mScaleType == QCPAxis::stLinear)
  15717. {
  15718. double diff = ax->pixelToCoord(startPos.y()) - ax->pixelToCoord(event->pos().y());
  15719. ax->setRange(mDragStartVertRange.at(i).lower+diff, mDragStartVertRange.at(i).upper+diff);
  15720. } else if (ax->mScaleType == QCPAxis::stLogarithmic)
  15721. {
  15722. double diff = ax->pixelToCoord(startPos.y()) / ax->pixelToCoord(event->pos().y());
  15723. ax->setRange(mDragStartVertRange.at(i).lower*diff, mDragStartVertRange.at(i).upper*diff);
  15724. }
  15725. }
  15726. }
  15727. if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot
  15728. {
  15729. if (mParentPlot->noAntialiasingOnDrag())
  15730. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  15731. mParentPlot->replot(QCustomPlot::rpQueuedReplot);
  15732. }
  15733. }
  15734. }
  15735. /* inherits documentation from base class */
  15736. void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  15737. {
  15738. Q_UNUSED(event)
  15739. Q_UNUSED(startPos)
  15740. mDragging = false;
  15741. if (mParentPlot->noAntialiasingOnDrag())
  15742. {
  15743. mParentPlot->setAntialiasedElements(mAADragBackup);
  15744. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  15745. }
  15746. }
  15747. /*! \internal
  15748. Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
  15749. ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
  15750. the scaling operation is the current cursor position inside the axis rect. The scaling factor is
  15751. dependent on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
  15752. zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
  15753. Note, that event->angleDelta() is usually +/-120 for single rotation steps. However, if the mouse
  15754. wheel is turned rapidly, many steps may bunch up to one event, so the delta may then be multiples
  15755. of 120. This is taken into account here, by calculating \a wheelSteps and using it as exponent of
  15756. the range zoom factor. This takes care of the wheel direction automatically, by inverting the
  15757. factor, when the wheel step is negative (f^-1 = 1/f).
  15758. */
  15759. void QCPAxisRect::wheelEvent(QWheelEvent *event)
  15760. {
  15761. #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  15762. const double delta = event->delta();
  15763. #else
  15764. const double delta = event->angleDelta().y();
  15765. #endif
  15766. #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  15767. const QPointF pos = event->pos();
  15768. #else
  15769. const QPointF pos = event->position();
  15770. #endif
  15771. // Mouse range zooming interaction:
  15772. if (mParentPlot->interactions().testFlag(QCP::iRangeZoom))
  15773. {
  15774. if (mRangeZoom != 0)
  15775. {
  15776. double factor;
  15777. double wheelSteps = delta/120.0; // a single step delta is +/-120 usually
  15778. if (mRangeZoom.testFlag(Qt::Horizontal))
  15779. {
  15780. factor = qPow(mRangeZoomFactorHorz, wheelSteps);
  15781. foreach (QPointer<QCPAxis> axis, mRangeZoomHorzAxis)
  15782. {
  15783. if (!axis.isNull())
  15784. axis->scaleRange(factor, axis->pixelToCoord(pos.x()));
  15785. }
  15786. }
  15787. if (mRangeZoom.testFlag(Qt::Vertical))
  15788. {
  15789. factor = qPow(mRangeZoomFactorVert, wheelSteps);
  15790. foreach (QPointer<QCPAxis> axis, mRangeZoomVertAxis)
  15791. {
  15792. if (!axis.isNull())
  15793. axis->scaleRange(factor, axis->pixelToCoord(pos.y()));
  15794. }
  15795. }
  15796. mParentPlot->replot();
  15797. }
  15798. }
  15799. }
  15800. /* end of 'src/layoutelements/layoutelement-axisrect.cpp' */
  15801. /* including file 'src/layoutelements/layoutelement-legend.cpp' */
  15802. /* modified 2021-03-29T02:30:44, size 31762 */
  15803. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15804. //////////////////// QCPAbstractLegendItem
  15805. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15806. /*! \class QCPAbstractLegendItem
  15807. \brief The abstract base class for all entries in a QCPLegend.
  15808. It defines a very basic interface for entries in a QCPLegend. For representing plottables in the
  15809. legend, the subclass \ref QCPPlottableLegendItem is more suitable.
  15810. Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry
  15811. that's not even associated with a plottable).
  15812. You must implement the following pure virtual functions:
  15813. \li \ref draw (from QCPLayerable)
  15814. You inherit the following members you may use:
  15815. <table>
  15816. <tr>
  15817. <td>QCPLegend *\b mParentLegend</td>
  15818. <td>A pointer to the parent QCPLegend.</td>
  15819. </tr><tr>
  15820. <td>QFont \b mFont</td>
  15821. <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>
  15822. </tr>
  15823. </table>
  15824. */
  15825. /* start of documentation of signals */
  15826. /*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected)
  15827. This signal is emitted when the selection state of this legend item has changed, either by user
  15828. interaction or by a direct call to \ref setSelected.
  15829. */
  15830. /* end of documentation of signals */
  15831. /*!
  15832. Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not
  15833. cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately.
  15834. */
  15835. QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) :
  15836. QCPLayoutElement(parent->parentPlot()),
  15837. mParentLegend(parent),
  15838. mFont(parent->font()),
  15839. mTextColor(parent->textColor()),
  15840. mSelectedFont(parent->selectedFont()),
  15841. mSelectedTextColor(parent->selectedTextColor()),
  15842. mSelectable(true),
  15843. mSelected(false)
  15844. {
  15845. setLayer(QLatin1String("legend"));
  15846. setMargins(QMargins(0, 0, 0, 0));
  15847. }
  15848. /*!
  15849. Sets the default font of this specific legend item to \a font.
  15850. \see setTextColor, QCPLegend::setFont
  15851. */
  15852. void QCPAbstractLegendItem::setFont(const QFont &font)
  15853. {
  15854. mFont = font;
  15855. }
  15856. /*!
  15857. Sets the default text color of this specific legend item to \a color.
  15858. \see setFont, QCPLegend::setTextColor
  15859. */
  15860. void QCPAbstractLegendItem::setTextColor(const QColor &color)
  15861. {
  15862. mTextColor = color;
  15863. }
  15864. /*!
  15865. When this legend item is selected, \a font is used to draw generic text, instead of the normal
  15866. font set with \ref setFont.
  15867. \see setFont, QCPLegend::setSelectedFont
  15868. */
  15869. void QCPAbstractLegendItem::setSelectedFont(const QFont &font)
  15870. {
  15871. mSelectedFont = font;
  15872. }
  15873. /*!
  15874. When this legend item is selected, \a color is used to draw generic text, instead of the normal
  15875. color set with \ref setTextColor.
  15876. \see setTextColor, QCPLegend::setSelectedTextColor
  15877. */
  15878. void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color)
  15879. {
  15880. mSelectedTextColor = color;
  15881. }
  15882. /*!
  15883. Sets whether this specific legend item is selectable.
  15884. \see setSelectedParts, QCustomPlot::setInteractions
  15885. */
  15886. void QCPAbstractLegendItem::setSelectable(bool selectable)
  15887. {
  15888. if (mSelectable != selectable)
  15889. {
  15890. mSelectable = selectable;
  15891. emit selectableChanged(mSelectable);
  15892. }
  15893. }
  15894. /*!
  15895. Sets whether this specific legend item is selected.
  15896. It is possible to set the selection state of this item by calling this function directly, even if
  15897. setSelectable is set to false.
  15898. \see setSelectableParts, QCustomPlot::setInteractions
  15899. */
  15900. void QCPAbstractLegendItem::setSelected(bool selected)
  15901. {
  15902. if (mSelected != selected)
  15903. {
  15904. mSelected = selected;
  15905. emit selectionChanged(mSelected);
  15906. }
  15907. }
  15908. /* inherits documentation from base class */
  15909. double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  15910. {
  15911. Q_UNUSED(details)
  15912. if (!mParentPlot) return -1;
  15913. if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems)))
  15914. return -1;
  15915. if (mRect.contains(pos.toPoint()))
  15916. return mParentPlot->selectionTolerance()*0.99;
  15917. else
  15918. return -1;
  15919. }
  15920. /* inherits documentation from base class */
  15921. void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
  15922. {
  15923. applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems);
  15924. }
  15925. /* inherits documentation from base class */
  15926. QRectF QCPAbstractLegendItem::clipRect() const
  15927. {
  15928. return mOuterRect;
  15929. }
  15930. /* inherits documentation from base class */
  15931. void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  15932. {
  15933. Q_UNUSED(event)
  15934. Q_UNUSED(details)
  15935. if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
  15936. {
  15937. bool selBefore = mSelected;
  15938. setSelected(additive ? !mSelected : true);
  15939. if (selectionStateChanged)
  15940. *selectionStateChanged = mSelected != selBefore;
  15941. }
  15942. }
  15943. /* inherits documentation from base class */
  15944. void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged)
  15945. {
  15946. if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
  15947. {
  15948. bool selBefore = mSelected;
  15949. setSelected(false);
  15950. if (selectionStateChanged)
  15951. *selectionStateChanged = mSelected != selBefore;
  15952. }
  15953. }
  15954. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15955. //////////////////// QCPPlottableLegendItem
  15956. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15957. /*! \class QCPPlottableLegendItem
  15958. \brief A legend item representing a plottable with an icon and the plottable name.
  15959. This is the standard legend item for plottables. It displays an icon of the plottable next to the
  15960. plottable name. The icon is drawn by the respective plottable itself (\ref
  15961. QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable.
  15962. For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the
  15963. middle.
  15964. Legend items of this type are always associated with one plottable (retrievable via the
  15965. plottable() function and settable with the constructor). You may change the font of the plottable
  15966. name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref
  15967. QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding.
  15968. The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend
  15969. creates/removes legend items of this type.
  15970. Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of
  15971. QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout
  15972. interface, QCPLegend has specialized functions for handling legend items conveniently, see the
  15973. documentation of \ref QCPLegend.
  15974. */
  15975. /*!
  15976. Creates a new legend item associated with \a plottable.
  15977. Once it's created, it can be added to the legend via \ref QCPLegend::addItem.
  15978. A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref
  15979. QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend.
  15980. */
  15981. QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) :
  15982. QCPAbstractLegendItem(parent),
  15983. mPlottable(plottable)
  15984. {
  15985. setAntialiased(false);
  15986. }
  15987. /*! \internal
  15988. Returns the pen that shall be used to draw the icon border, taking into account the selection
  15989. state of this item.
  15990. */
  15991. QPen QCPPlottableLegendItem::getIconBorderPen() const
  15992. {
  15993. return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen();
  15994. }
  15995. /*! \internal
  15996. Returns the text color that shall be used to draw text, taking into account the selection state
  15997. of this item.
  15998. */
  15999. QColor QCPPlottableLegendItem::getTextColor() const
  16000. {
  16001. return mSelected ? mSelectedTextColor : mTextColor;
  16002. }
  16003. /*! \internal
  16004. Returns the font that shall be used to draw text, taking into account the selection state of this
  16005. item.
  16006. */
  16007. QFont QCPPlottableLegendItem::getFont() const
  16008. {
  16009. return mSelected ? mSelectedFont : mFont;
  16010. }
  16011. /*! \internal
  16012. Draws the item with \a painter. The size and position of the drawn legend item is defined by the
  16013. parent layout (typically a \ref QCPLegend) and the \ref minimumOuterSizeHint and \ref
  16014. maximumOuterSizeHint of this legend item.
  16015. */
  16016. void QCPPlottableLegendItem::draw(QCPPainter *painter)
  16017. {
  16018. if (!mPlottable) return;
  16019. painter->setFont(getFont());
  16020. painter->setPen(QPen(getTextColor()));
  16021. QSizeF iconSize = mParentLegend->iconSize();
  16022. QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
  16023. QRectF iconRect(mRect.topLeft(), iconSize);
  16024. int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops
  16025. painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name());
  16026. // draw icon:
  16027. painter->save();
  16028. painter->setClipRect(iconRect, Qt::IntersectClip);
  16029. mPlottable->drawLegendIcon(painter, iconRect);
  16030. painter->restore();
  16031. // draw icon border:
  16032. if (getIconBorderPen().style() != Qt::NoPen)
  16033. {
  16034. painter->setPen(getIconBorderPen());
  16035. painter->setBrush(Qt::NoBrush);
  16036. int halfPen = qCeil(painter->pen().widthF()*0.5)+1;
  16037. painter->setClipRect(mOuterRect.adjusted(-halfPen, -halfPen, halfPen, halfPen)); // extend default clip rect so thicker pens (especially during selection) are not clipped
  16038. painter->drawRect(iconRect);
  16039. }
  16040. }
  16041. /*! \internal
  16042. Calculates and returns the size of this item. This includes the icon, the text and the padding in
  16043. between.
  16044. \seebaseclassmethod
  16045. */
  16046. QSizeF QCPPlottableLegendItem::minimumOuterSizeHint() const
  16047. {
  16048. if (!mPlottable) return {};
  16049. QSizeF result(0, 0);
  16050. QRectF textRect;
  16051. QFontMetrics fontMetrics(getFont());
  16052. QSizeF iconSize = mParentLegend->iconSize();
  16053. textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
  16054. result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width());
  16055. result.setHeight(qMax(textRect.height(), iconSize.height()));
  16056. result.rwidth() += mMargins.left()+mMargins.right();
  16057. result.rheight() += mMargins.top()+mMargins.bottom();
  16058. return result;
  16059. }
  16060. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16061. //////////////////// QCPLegend
  16062. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16063. /*! \class QCPLegend
  16064. \brief Manages a legend inside a QCustomPlot.
  16065. A legend is a small box somewhere in the plot which lists plottables with their name and icon.
  16066. A legend is populated with legend items by calling \ref QCPAbstractPlottable::addToLegend on the
  16067. plottable, for which a legend item shall be created. In the case of the main legend (\ref
  16068. QCustomPlot::legend), simply adding plottables to the plot while \ref
  16069. QCustomPlot::setAutoAddPlottableToLegend is set to true (the default) creates corresponding
  16070. legend items. The legend item associated with a certain plottable can be removed with \ref
  16071. QCPAbstractPlottable::removeFromLegend. However, QCPLegend also offers an interface to add and
  16072. manipulate legend items directly: \ref item, \ref itemWithPlottable, \ref itemCount, \ref
  16073. addItem, \ref removeItem, etc.
  16074. Since \ref QCPLegend derives from \ref QCPLayoutGrid, it can be placed in any position a \ref
  16075. QCPLayoutElement may be positioned. The legend items are themselves \ref QCPLayoutElement
  16076. "QCPLayoutElements" which are placed in the grid layout of the legend. \ref QCPLegend only adds
  16077. an interface specialized for handling child elements of type \ref QCPAbstractLegendItem, as
  16078. mentioned above. In principle, any other layout elements may also be added to a legend via the
  16079. normal \ref QCPLayoutGrid interface. See the special page about \link thelayoutsystem The Layout
  16080. System\endlink for examples on how to add other elements to the legend and move it outside the axis
  16081. rect.
  16082. Use the methods \ref setFillOrder and \ref setWrap inherited from \ref QCPLayoutGrid to control
  16083. in which order (column first or row first) the legend is filled up when calling \ref addItem, and
  16084. at which column or row wrapping occurs. The default fill order for legends is \ref foRowsFirst.
  16085. By default, every QCustomPlot has one legend (\ref QCustomPlot::legend) which is placed in the
  16086. inset layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another
  16087. position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend
  16088. outside of the axis rect, place it anywhere else with the \ref QCPLayout/\ref QCPLayoutElement
  16089. interface.
  16090. */
  16091. /* start of documentation of signals */
  16092. /*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection);
  16093. This signal is emitted when the selection state of this legend has changed.
  16094. \see setSelectedParts, setSelectableParts
  16095. */
  16096. /* end of documentation of signals */
  16097. /*!
  16098. Constructs a new QCPLegend instance with default values.
  16099. Note that by default, QCustomPlot already contains a legend ready to be used as \ref
  16100. QCustomPlot::legend
  16101. */
  16102. QCPLegend::QCPLegend() :
  16103. mIconTextPadding{}
  16104. {
  16105. setFillOrder(QCPLayoutGrid::foRowsFirst);
  16106. setWrap(0);
  16107. setRowSpacing(3);
  16108. setColumnSpacing(8);
  16109. setMargins(QMargins(7, 5, 7, 4));
  16110. setAntialiased(false);
  16111. setIconSize(32, 18);
  16112. setIconTextPadding(7);
  16113. setSelectableParts(spLegendBox | spItems);
  16114. setSelectedParts(spNone);
  16115. setBorderPen(QPen(Qt::black, 0));
  16116. setSelectedBorderPen(QPen(Qt::blue, 2));
  16117. setIconBorderPen(Qt::NoPen);
  16118. setSelectedIconBorderPen(QPen(Qt::blue, 2));
  16119. setBrush(Qt::white);
  16120. setSelectedBrush(Qt::white);
  16121. setTextColor(Qt::black);
  16122. setSelectedTextColor(Qt::blue);
  16123. }
  16124. QCPLegend::~QCPLegend()
  16125. {
  16126. clearItems();
  16127. 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)
  16128. mParentPlot->legendRemoved(this);
  16129. }
  16130. /* no doc for getter, see setSelectedParts */
  16131. QCPLegend::SelectableParts QCPLegend::selectedParts() const
  16132. {
  16133. // check whether any legend elements selected, if yes, add spItems to return value
  16134. bool hasSelectedItems = false;
  16135. for (int i=0; i<itemCount(); ++i)
  16136. {
  16137. if (item(i) && item(i)->selected())
  16138. {
  16139. hasSelectedItems = true;
  16140. break;
  16141. }
  16142. }
  16143. if (hasSelectedItems)
  16144. return mSelectedParts | spItems;
  16145. else
  16146. return mSelectedParts & ~spItems;
  16147. }
  16148. /*!
  16149. Sets the pen, the border of the entire legend is drawn with.
  16150. */
  16151. void QCPLegend::setBorderPen(const QPen &pen)
  16152. {
  16153. mBorderPen = pen;
  16154. }
  16155. /*!
  16156. Sets the brush of the legend background.
  16157. */
  16158. void QCPLegend::setBrush(const QBrush &brush)
  16159. {
  16160. mBrush = brush;
  16161. }
  16162. /*!
  16163. Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will
  16164. use this font by default. However, a different font can be specified on a per-item-basis by
  16165. accessing the specific legend item.
  16166. This function will also set \a font on all already existing legend items.
  16167. \see QCPAbstractLegendItem::setFont
  16168. */
  16169. void QCPLegend::setFont(const QFont &font)
  16170. {
  16171. mFont = font;
  16172. for (int i=0; i<itemCount(); ++i)
  16173. {
  16174. if (item(i))
  16175. item(i)->setFont(mFont);
  16176. }
  16177. }
  16178. /*!
  16179. Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph)
  16180. will use this color by default. However, a different colors can be specified on a per-item-basis
  16181. by accessing the specific legend item.
  16182. This function will also set \a color on all already existing legend items.
  16183. \see QCPAbstractLegendItem::setTextColor
  16184. */
  16185. void QCPLegend::setTextColor(const QColor &color)
  16186. {
  16187. mTextColor = color;
  16188. for (int i=0; i<itemCount(); ++i)
  16189. {
  16190. if (item(i))
  16191. item(i)->setTextColor(color);
  16192. }
  16193. }
  16194. /*!
  16195. Sets the size of legend icons. Legend items that draw an icon (e.g. a visual
  16196. representation of the graph) will use this size by default.
  16197. */
  16198. void QCPLegend::setIconSize(const QSize &size)
  16199. {
  16200. mIconSize = size;
  16201. }
  16202. /*! \overload
  16203. */
  16204. void QCPLegend::setIconSize(int width, int height)
  16205. {
  16206. mIconSize.setWidth(width);
  16207. mIconSize.setHeight(height);
  16208. }
  16209. /*!
  16210. Sets the horizontal space in pixels between the legend icon and the text next to it.
  16211. Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the
  16212. name of the graph) will use this space by default.
  16213. */
  16214. void QCPLegend::setIconTextPadding(int padding)
  16215. {
  16216. mIconTextPadding = padding;
  16217. }
  16218. /*!
  16219. Sets the pen used to draw a border around each legend icon. Legend items that draw an
  16220. icon (e.g. a visual representation of the graph) will use this pen by default.
  16221. If no border is wanted, set this to \a Qt::NoPen.
  16222. */
  16223. void QCPLegend::setIconBorderPen(const QPen &pen)
  16224. {
  16225. mIconBorderPen = pen;
  16226. }
  16227. /*!
  16228. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  16229. (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.)
  16230. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  16231. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  16232. directly.
  16233. \see SelectablePart, setSelectedParts
  16234. */
  16235. void QCPLegend::setSelectableParts(const SelectableParts &selectable)
  16236. {
  16237. if (mSelectableParts != selectable)
  16238. {
  16239. mSelectableParts = selectable;
  16240. emit selectableChanged(mSelectableParts);
  16241. }
  16242. }
  16243. /*!
  16244. Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part
  16245. is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected
  16246. doesn't contain \ref spItems, those items become deselected.
  16247. The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions
  16248. contains iSelectLegend. You only need to call this function when you wish to change the selection
  16249. state manually.
  16250. This function can change the selection state of a part even when \ref setSelectableParts was set to a
  16251. value that actually excludes the part.
  16252. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  16253. Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set
  16254. before, because there's no way to specify which exact items to newly select. Do this by calling
  16255. \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select.
  16256. \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush,
  16257. setSelectedFont
  16258. */
  16259. void QCPLegend::setSelectedParts(const SelectableParts &selected)
  16260. {
  16261. SelectableParts newSelected = selected;
  16262. mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed
  16263. if (mSelectedParts != newSelected)
  16264. {
  16265. if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that)
  16266. {
  16267. qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function";
  16268. newSelected &= ~spItems;
  16269. }
  16270. if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection
  16271. {
  16272. for (int i=0; i<itemCount(); ++i)
  16273. {
  16274. if (item(i))
  16275. item(i)->setSelected(false);
  16276. }
  16277. }
  16278. mSelectedParts = newSelected;
  16279. emit selectionChanged(mSelectedParts);
  16280. }
  16281. }
  16282. /*!
  16283. When the legend box is selected, this pen is used to draw the border instead of the normal pen
  16284. set via \ref setBorderPen.
  16285. \see setSelectedParts, setSelectableParts, setSelectedBrush
  16286. */
  16287. void QCPLegend::setSelectedBorderPen(const QPen &pen)
  16288. {
  16289. mSelectedBorderPen = pen;
  16290. }
  16291. /*!
  16292. Sets the pen legend items will use to draw their icon borders, when they are selected.
  16293. \see setSelectedParts, setSelectableParts, setSelectedFont
  16294. */
  16295. void QCPLegend::setSelectedIconBorderPen(const QPen &pen)
  16296. {
  16297. mSelectedIconBorderPen = pen;
  16298. }
  16299. /*!
  16300. When the legend box is selected, this brush is used to draw the legend background instead of the normal brush
  16301. set via \ref setBrush.
  16302. \see setSelectedParts, setSelectableParts, setSelectedBorderPen
  16303. */
  16304. void QCPLegend::setSelectedBrush(const QBrush &brush)
  16305. {
  16306. mSelectedBrush = brush;
  16307. }
  16308. /*!
  16309. Sets the default font that is used by legend items when they are selected.
  16310. This function will also set \a font on all already existing legend items.
  16311. \see setFont, QCPAbstractLegendItem::setSelectedFont
  16312. */
  16313. void QCPLegend::setSelectedFont(const QFont &font)
  16314. {
  16315. mSelectedFont = font;
  16316. for (int i=0; i<itemCount(); ++i)
  16317. {
  16318. if (item(i))
  16319. item(i)->setSelectedFont(font);
  16320. }
  16321. }
  16322. /*!
  16323. Sets the default text color that is used by legend items when they are selected.
  16324. This function will also set \a color on all already existing legend items.
  16325. \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor
  16326. */
  16327. void QCPLegend::setSelectedTextColor(const QColor &color)
  16328. {
  16329. mSelectedTextColor = color;
  16330. for (int i=0; i<itemCount(); ++i)
  16331. {
  16332. if (item(i))
  16333. item(i)->setSelectedTextColor(color);
  16334. }
  16335. }
  16336. /*!
  16337. Returns the item with index \a i. If non-legend items were added to the legend, and the element
  16338. at the specified cell index is not a QCPAbstractLegendItem, returns \c nullptr.
  16339. Note that the linear index depends on the current fill order (\ref setFillOrder).
  16340. \see itemCount, addItem, itemWithPlottable
  16341. */
  16342. QCPAbstractLegendItem *QCPLegend::item(int index) const
  16343. {
  16344. return qobject_cast<QCPAbstractLegendItem*>(elementAt(index));
  16345. }
  16346. /*!
  16347. Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
  16348. If such an item isn't in the legend, returns \c nullptr.
  16349. \see hasItemWithPlottable
  16350. */
  16351. QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const
  16352. {
  16353. for (int i=0; i<itemCount(); ++i)
  16354. {
  16355. if (QCPPlottableLegendItem *pli = qobject_cast<QCPPlottableLegendItem*>(item(i)))
  16356. {
  16357. if (pli->plottable() == plottable)
  16358. return pli;
  16359. }
  16360. }
  16361. return nullptr;
  16362. }
  16363. /*!
  16364. Returns the number of items currently in the legend. It is identical to the base class
  16365. QCPLayoutGrid::elementCount(), and unlike the other "item" interface methods of QCPLegend,
  16366. doesn't only address elements which can be cast to QCPAbstractLegendItem.
  16367. Note that if empty cells are in the legend (e.g. by calling methods of the \ref QCPLayoutGrid
  16368. base class which allows creating empty cells), they are included in the returned count.
  16369. \see item
  16370. */
  16371. int QCPLegend::itemCount() const
  16372. {
  16373. return elementCount();
  16374. }
  16375. /*!
  16376. Returns whether the legend contains \a item.
  16377. \see hasItemWithPlottable
  16378. */
  16379. bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const
  16380. {
  16381. for (int i=0; i<itemCount(); ++i)
  16382. {
  16383. if (item == this->item(i))
  16384. return true;
  16385. }
  16386. return false;
  16387. }
  16388. /*!
  16389. Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
  16390. If such an item isn't in the legend, returns false.
  16391. \see itemWithPlottable
  16392. */
  16393. bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const
  16394. {
  16395. return itemWithPlottable(plottable);
  16396. }
  16397. /*!
  16398. Adds \a item to the legend, if it's not present already. The element is arranged according to the
  16399. current fill order (\ref setFillOrder) and wrapping (\ref setWrap).
  16400. Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added.
  16401. The legend takes ownership of the item.
  16402. \see removeItem, item, hasItem
  16403. */
  16404. bool QCPLegend::addItem(QCPAbstractLegendItem *item)
  16405. {
  16406. return addElement(item);
  16407. }
  16408. /*! \overload
  16409. Removes the item with the specified \a index from the legend and deletes it.
  16410. After successful removal, the legend is reordered according to the current fill order (\ref
  16411. setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item
  16412. was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid.
  16413. Returns true, if successful. Unlike \ref QCPLayoutGrid::removeAt, this method only removes
  16414. elements derived from \ref QCPAbstractLegendItem.
  16415. \see itemCount, clearItems
  16416. */
  16417. bool QCPLegend::removeItem(int index)
  16418. {
  16419. if (QCPAbstractLegendItem *ali = item(index))
  16420. {
  16421. bool success = remove(ali);
  16422. if (success)
  16423. setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering
  16424. return success;
  16425. } else
  16426. return false;
  16427. }
  16428. /*! \overload
  16429. Removes \a item from the legend and deletes it.
  16430. After successful removal, the legend is reordered according to the current fill order (\ref
  16431. setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item
  16432. was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid.
  16433. Returns true, if successful.
  16434. \see clearItems
  16435. */
  16436. bool QCPLegend::removeItem(QCPAbstractLegendItem *item)
  16437. {
  16438. bool success = remove(item);
  16439. if (success)
  16440. setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering
  16441. return success;
  16442. }
  16443. /*!
  16444. Removes all items from the legend.
  16445. */
  16446. void QCPLegend::clearItems()
  16447. {
  16448. for (int i=elementCount()-1; i>=0; --i)
  16449. {
  16450. if (item(i))
  16451. removeAt(i); // don't use removeItem() because it would unnecessarily reorder the whole legend for each item
  16452. }
  16453. setFillOrder(fillOrder(), true); // get rid of empty cells by reordering once after all items are removed
  16454. }
  16455. /*!
  16456. Returns the legend items that are currently selected. If no items are selected,
  16457. the list is empty.
  16458. \see QCPAbstractLegendItem::setSelected, setSelectable
  16459. */
  16460. QList<QCPAbstractLegendItem *> QCPLegend::selectedItems() const
  16461. {
  16462. QList<QCPAbstractLegendItem*> result;
  16463. for (int i=0; i<itemCount(); ++i)
  16464. {
  16465. if (QCPAbstractLegendItem *ali = item(i))
  16466. {
  16467. if (ali->selected())
  16468. result.append(ali);
  16469. }
  16470. }
  16471. return result;
  16472. }
  16473. /*! \internal
  16474. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  16475. before drawing main legend elements.
  16476. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  16477. This function takes into account the local setting of the antialiasing flag as well as the
  16478. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  16479. QCustomPlot::setNotAntialiasedElements.
  16480. \seebaseclassmethod
  16481. \see setAntialiased
  16482. */
  16483. void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const
  16484. {
  16485. applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend);
  16486. }
  16487. /*! \internal
  16488. Returns the pen used to paint the border of the legend, taking into account the selection state
  16489. of the legend box.
  16490. */
  16491. QPen QCPLegend::getBorderPen() const
  16492. {
  16493. return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen;
  16494. }
  16495. /*! \internal
  16496. Returns the brush used to paint the background of the legend, taking into account the selection
  16497. state of the legend box.
  16498. */
  16499. QBrush QCPLegend::getBrush() const
  16500. {
  16501. return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush;
  16502. }
  16503. /*! \internal
  16504. Draws the legend box with the provided \a painter. The individual legend items are layerables
  16505. themselves, thus are drawn independently.
  16506. */
  16507. void QCPLegend::draw(QCPPainter *painter)
  16508. {
  16509. // draw background rect:
  16510. painter->setBrush(getBrush());
  16511. painter->setPen(getBorderPen());
  16512. painter->drawRect(mOuterRect);
  16513. }
  16514. /* inherits documentation from base class */
  16515. double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  16516. {
  16517. if (!mParentPlot) return -1;
  16518. if (onlySelectable && !mSelectableParts.testFlag(spLegendBox))
  16519. return -1;
  16520. if (mOuterRect.contains(pos.toPoint()))
  16521. {
  16522. if (details) details->setValue(spLegendBox);
  16523. return mParentPlot->selectionTolerance()*0.99;
  16524. }
  16525. return -1;
  16526. }
  16527. /* inherits documentation from base class */
  16528. void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  16529. {
  16530. Q_UNUSED(event)
  16531. mSelectedParts = selectedParts(); // in case item selection has changed
  16532. if (details.value<SelectablePart>() == spLegendBox && mSelectableParts.testFlag(spLegendBox))
  16533. {
  16534. SelectableParts selBefore = mSelectedParts;
  16535. 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)
  16536. if (selectionStateChanged)
  16537. *selectionStateChanged = mSelectedParts != selBefore;
  16538. }
  16539. }
  16540. /* inherits documentation from base class */
  16541. void QCPLegend::deselectEvent(bool *selectionStateChanged)
  16542. {
  16543. mSelectedParts = selectedParts(); // in case item selection has changed
  16544. if (mSelectableParts.testFlag(spLegendBox))
  16545. {
  16546. SelectableParts selBefore = mSelectedParts;
  16547. setSelectedParts(selectedParts() & ~spLegendBox);
  16548. if (selectionStateChanged)
  16549. *selectionStateChanged = mSelectedParts != selBefore;
  16550. }
  16551. }
  16552. /* inherits documentation from base class */
  16553. QCP::Interaction QCPLegend::selectionCategory() const
  16554. {
  16555. return QCP::iSelectLegend;
  16556. }
  16557. /* inherits documentation from base class */
  16558. QCP::Interaction QCPAbstractLegendItem::selectionCategory() const
  16559. {
  16560. return QCP::iSelectLegend;
  16561. }
  16562. /* inherits documentation from base class */
  16563. void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot)
  16564. {
  16565. if (parentPlot && !parentPlot->legend)
  16566. parentPlot->legend = this;
  16567. }
  16568. /* end of 'src/layoutelements/layoutelement-legend.cpp' */
  16569. /* including file 'src/layoutelements/layoutelement-textelement.cpp' */
  16570. /* modified 2021-03-29T02:30:44, size 12925 */
  16571. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16572. //////////////////// QCPTextElement
  16573. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16574. /*! \class QCPTextElement
  16575. \brief A layout element displaying a text
  16576. The text may be specified with \ref setText, the formatting can be controlled with \ref setFont,
  16577. \ref setTextColor, and \ref setTextFlags.
  16578. A text element can be added as follows:
  16579. \snippet documentation/doc-code-snippets/mainwindow.cpp qcptextelement-creation
  16580. */
  16581. /* start documentation of signals */
  16582. /*! \fn void QCPTextElement::selectionChanged(bool selected)
  16583. This signal is emitted when the selection state has changed to \a selected, either by user
  16584. interaction or by a direct call to \ref setSelected.
  16585. \see setSelected, setSelectable
  16586. */
  16587. /*! \fn void QCPTextElement::clicked(QMouseEvent *event)
  16588. This signal is emitted when the text element is clicked.
  16589. \see doubleClicked, selectTest
  16590. */
  16591. /*! \fn void QCPTextElement::doubleClicked(QMouseEvent *event)
  16592. This signal is emitted when the text element is double clicked.
  16593. \see clicked, selectTest
  16594. */
  16595. /* end documentation of signals */
  16596. /*! \overload
  16597. Creates a new QCPTextElement instance and sets default values. The initial text is empty (\ref
  16598. setText).
  16599. */
  16600. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot) :
  16601. QCPLayoutElement(parentPlot),
  16602. mText(),
  16603. mTextFlags(Qt::AlignCenter),
  16604. mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  16605. mTextColor(Qt::black),
  16606. mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  16607. mSelectedTextColor(Qt::blue),
  16608. mSelectable(false),
  16609. mSelected(false)
  16610. {
  16611. if (parentPlot)
  16612. {
  16613. mFont = parentPlot->font();
  16614. mSelectedFont = parentPlot->font();
  16615. }
  16616. setMargins(QMargins(2, 2, 2, 2));
  16617. }
  16618. /*! \overload
  16619. Creates a new QCPTextElement instance and sets default values.
  16620. The initial text is set to \a text.
  16621. */
  16622. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text) :
  16623. QCPLayoutElement(parentPlot),
  16624. mText(text),
  16625. mTextFlags(Qt::AlignCenter),
  16626. mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  16627. mTextColor(Qt::black),
  16628. mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  16629. mSelectedTextColor(Qt::blue),
  16630. mSelectable(false),
  16631. mSelected(false)
  16632. {
  16633. if (parentPlot)
  16634. {
  16635. mFont = parentPlot->font();
  16636. mSelectedFont = parentPlot->font();
  16637. }
  16638. setMargins(QMargins(2, 2, 2, 2));
  16639. }
  16640. /*! \overload
  16641. Creates a new QCPTextElement instance and sets default values.
  16642. The initial text is set to \a text with \a pointSize.
  16643. */
  16644. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, double pointSize) :
  16645. QCPLayoutElement(parentPlot),
  16646. mText(text),
  16647. mTextFlags(Qt::AlignCenter),
  16648. mFont(QFont(QLatin1String("sans serif"), int(pointSize))), // will be taken from parentPlot if available, see below
  16649. mTextColor(Qt::black),
  16650. mSelectedFont(QFont(QLatin1String("sans serif"), int(pointSize))), // will be taken from parentPlot if available, see below
  16651. mSelectedTextColor(Qt::blue),
  16652. mSelectable(false),
  16653. mSelected(false)
  16654. {
  16655. mFont.setPointSizeF(pointSize); // set here again as floating point, because constructor above only takes integer
  16656. if (parentPlot)
  16657. {
  16658. mFont = parentPlot->font();
  16659. mFont.setPointSizeF(pointSize);
  16660. mSelectedFont = parentPlot->font();
  16661. mSelectedFont.setPointSizeF(pointSize);
  16662. }
  16663. setMargins(QMargins(2, 2, 2, 2));
  16664. }
  16665. /*! \overload
  16666. Creates a new QCPTextElement instance and sets default values.
  16667. The initial text is set to \a text with \a pointSize and the specified \a fontFamily.
  16668. */
  16669. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QString &fontFamily, double pointSize) :
  16670. QCPLayoutElement(parentPlot),
  16671. mText(text),
  16672. mTextFlags(Qt::AlignCenter),
  16673. mFont(QFont(fontFamily, int(pointSize))),
  16674. mTextColor(Qt::black),
  16675. mSelectedFont(QFont(fontFamily, int(pointSize))),
  16676. mSelectedTextColor(Qt::blue),
  16677. mSelectable(false),
  16678. mSelected(false)
  16679. {
  16680. mFont.setPointSizeF(pointSize); // set here again as floating point, because constructor above only takes integer
  16681. setMargins(QMargins(2, 2, 2, 2));
  16682. }
  16683. /*! \overload
  16684. Creates a new QCPTextElement instance and sets default values.
  16685. The initial text is set to \a text with the specified \a font.
  16686. */
  16687. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QFont &font) :
  16688. QCPLayoutElement(parentPlot),
  16689. mText(text),
  16690. mTextFlags(Qt::AlignCenter),
  16691. mFont(font),
  16692. mTextColor(Qt::black),
  16693. mSelectedFont(font),
  16694. mSelectedTextColor(Qt::blue),
  16695. mSelectable(false),
  16696. mSelected(false)
  16697. {
  16698. setMargins(QMargins(2, 2, 2, 2));
  16699. }
  16700. /*!
  16701. Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n".
  16702. \see setFont, setTextColor, setTextFlags
  16703. */
  16704. void QCPTextElement::setText(const QString &text)
  16705. {
  16706. mText = text;
  16707. }
  16708. /*!
  16709. Sets options for text alignment and wrapping behaviour. \a flags is a bitwise OR-combination of
  16710. \c Qt::AlignmentFlag and \c Qt::TextFlag enums.
  16711. Possible enums are:
  16712. - Qt::AlignLeft
  16713. - Qt::AlignRight
  16714. - Qt::AlignHCenter
  16715. - Qt::AlignJustify
  16716. - Qt::AlignTop
  16717. - Qt::AlignBottom
  16718. - Qt::AlignVCenter
  16719. - Qt::AlignCenter
  16720. - Qt::TextDontClip
  16721. - Qt::TextSingleLine
  16722. - Qt::TextExpandTabs
  16723. - Qt::TextShowMnemonic
  16724. - Qt::TextWordWrap
  16725. - Qt::TextIncludeTrailingSpaces
  16726. */
  16727. void QCPTextElement::setTextFlags(int flags)
  16728. {
  16729. mTextFlags = flags;
  16730. }
  16731. /*!
  16732. Sets the \a font of the text.
  16733. \see setTextColor, setSelectedFont
  16734. */
  16735. void QCPTextElement::setFont(const QFont &font)
  16736. {
  16737. mFont = font;
  16738. }
  16739. /*!
  16740. Sets the \a color of the text.
  16741. \see setFont, setSelectedTextColor
  16742. */
  16743. void QCPTextElement::setTextColor(const QColor &color)
  16744. {
  16745. mTextColor = color;
  16746. }
  16747. /*!
  16748. Sets the \a font of the text that will be used if the text element is selected (\ref setSelected).
  16749. \see setFont
  16750. */
  16751. void QCPTextElement::setSelectedFont(const QFont &font)
  16752. {
  16753. mSelectedFont = font;
  16754. }
  16755. /*!
  16756. Sets the \a color of the text that will be used if the text element is selected (\ref setSelected).
  16757. \see setTextColor
  16758. */
  16759. void QCPTextElement::setSelectedTextColor(const QColor &color)
  16760. {
  16761. mSelectedTextColor = color;
  16762. }
  16763. /*!
  16764. Sets whether the user may select this text element.
  16765. Note that even when \a selectable is set to <tt>false</tt>, the selection state may be changed
  16766. programmatically via \ref setSelected.
  16767. */
  16768. void QCPTextElement::setSelectable(bool selectable)
  16769. {
  16770. if (mSelectable != selectable)
  16771. {
  16772. mSelectable = selectable;
  16773. emit selectableChanged(mSelectable);
  16774. }
  16775. }
  16776. /*!
  16777. Sets the selection state of this text element to \a selected. If the selection has changed, \ref
  16778. selectionChanged is emitted.
  16779. Note that this function can change the selection state independently of the current \ref
  16780. setSelectable state.
  16781. */
  16782. void QCPTextElement::setSelected(bool selected)
  16783. {
  16784. if (mSelected != selected)
  16785. {
  16786. mSelected = selected;
  16787. emit selectionChanged(mSelected);
  16788. }
  16789. }
  16790. /* inherits documentation from base class */
  16791. void QCPTextElement::applyDefaultAntialiasingHint(QCPPainter *painter) const
  16792. {
  16793. applyAntialiasingHint(painter, mAntialiased, QCP::aeOther);
  16794. }
  16795. /* inherits documentation from base class */
  16796. void QCPTextElement::draw(QCPPainter *painter)
  16797. {
  16798. painter->setFont(mainFont());
  16799. painter->setPen(QPen(mainTextColor()));
  16800. painter->drawText(mRect, mTextFlags, mText, &mTextBoundingRect);
  16801. }
  16802. /* inherits documentation from base class */
  16803. QSizeF QCPTextElement::minimumOuterSizeHint() const
  16804. {
  16805. QFontMetrics metrics(mFont);
  16806. QSizeF result(metrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, mText).size());
  16807. result.rwidth() += mMargins.left()+mMargins.right();
  16808. result.rheight() += mMargins.top()+mMargins.bottom();
  16809. return result;
  16810. }
  16811. /* inherits documentation from base class */
  16812. QSizeF QCPTextElement::maximumOuterSizeHint() const
  16813. {
  16814. QFontMetrics metrics(mFont);
  16815. QSizeF result(metrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, mText).size());
  16816. result.setWidth(QWIDGETSIZE_MAX);
  16817. result.rheight() += mMargins.top()+mMargins.bottom();
  16818. return result;
  16819. }
  16820. /* inherits documentation from base class */
  16821. void QCPTextElement::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  16822. {
  16823. Q_UNUSED(event)
  16824. Q_UNUSED(details)
  16825. if (mSelectable)
  16826. {
  16827. bool selBefore = mSelected;
  16828. setSelected(additive ? !mSelected : true);
  16829. if (selectionStateChanged)
  16830. *selectionStateChanged = mSelected != selBefore;
  16831. }
  16832. }
  16833. /* inherits documentation from base class */
  16834. void QCPTextElement::deselectEvent(bool *selectionStateChanged)
  16835. {
  16836. if (mSelectable)
  16837. {
  16838. bool selBefore = mSelected;
  16839. setSelected(false);
  16840. if (selectionStateChanged)
  16841. *selectionStateChanged = mSelected != selBefore;
  16842. }
  16843. }
  16844. /*!
  16845. Returns 0.99*selectionTolerance (see \ref QCustomPlot::setSelectionTolerance) when \a pos is
  16846. within the bounding box of the text element's text. Note that this bounding box is updated in the
  16847. draw call.
  16848. If \a pos is outside the text's bounding box or if \a onlySelectable is true and this text
  16849. element is not selectable (\ref setSelectable), returns -1.
  16850. \seebaseclassmethod
  16851. */
  16852. double QCPTextElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  16853. {
  16854. Q_UNUSED(details)
  16855. if (onlySelectable && !mSelectable)
  16856. return -1;
  16857. if (mTextBoundingRect.contains(pos.toPoint()))
  16858. return mParentPlot->selectionTolerance()*0.99;
  16859. else
  16860. return -1;
  16861. }
  16862. /*!
  16863. Accepts the mouse event in order to emit the according click signal in the \ref
  16864. mouseReleaseEvent.
  16865. \seebaseclassmethod
  16866. */
  16867. void QCPTextElement::mousePressEvent(QMouseEvent *event, const QVariant &details)
  16868. {
  16869. Q_UNUSED(details)
  16870. event->accept();
  16871. }
  16872. /*!
  16873. Emits the \ref clicked signal if the cursor hasn't moved by more than a few pixels since the \ref
  16874. mousePressEvent.
  16875. \seebaseclassmethod
  16876. */
  16877. void QCPTextElement::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  16878. {
  16879. if ((QPointF(event->pos())-startPos).manhattanLength() <= 3)
  16880. emit clicked(event);
  16881. }
  16882. /*!
  16883. Emits the \ref doubleClicked signal.
  16884. \seebaseclassmethod
  16885. */
  16886. void QCPTextElement::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details)
  16887. {
  16888. Q_UNUSED(details)
  16889. emit doubleClicked(event);
  16890. }
  16891. /*! \internal
  16892. Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to
  16893. <tt>true</tt>, else mFont is returned.
  16894. */
  16895. QFont QCPTextElement::mainFont() const
  16896. {
  16897. return mSelected ? mSelectedFont : mFont;
  16898. }
  16899. /*! \internal
  16900. Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to
  16901. <tt>true</tt>, else mTextColor is returned.
  16902. */
  16903. QColor QCPTextElement::mainTextColor() const
  16904. {
  16905. return mSelected ? mSelectedTextColor : mTextColor;
  16906. }
  16907. /* end of 'src/layoutelements/layoutelement-textelement.cpp' */
  16908. /* including file 'src/layoutelements/layoutelement-colorscale.cpp' */
  16909. /* modified 2021-03-29T02:30:44, size 26531 */
  16910. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16911. //////////////////// QCPColorScale
  16912. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16913. /*! \class QCPColorScale
  16914. \brief A color scale for use with color coding data such as QCPColorMap
  16915. This layout element can be placed on the plot to correlate a color gradient with data values. It
  16916. is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps".
  16917. \image html QCPColorScale.png
  16918. The color scale can be either horizontal or vertical, as shown in the image above. The
  16919. orientation and the side where the numbers appear is controlled with \ref setType.
  16920. Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are
  16921. connected, they share their gradient, data range and data scale type (\ref setGradient, \ref
  16922. setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color
  16923. scale, to make them all synchronize these properties.
  16924. To have finer control over the number display and axis behaviour, you can directly access the
  16925. \ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if
  16926. you want to change the number of automatically generated ticks, call
  16927. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-tickcount
  16928. Placing a color scale next to the main axis rect works like with any other layout element:
  16929. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-creation
  16930. In this case we have placed it to the right of the default axis rect, so it wasn't necessary to
  16931. call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color
  16932. scale can be set with \ref setLabel.
  16933. For optimum appearance (like in the image above), it may be desirable to line up the axis rect and
  16934. the borders of the color scale. Use a \ref QCPMarginGroup to achieve this:
  16935. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-margingroup
  16936. Color scales are initialized with a non-zero minimum top and bottom margin (\ref
  16937. setMinimumMargins), because vertical color scales are most common and the minimum top/bottom
  16938. margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a
  16939. horizontal color scale by setting \ref setType to \ref QCPAxis::atBottom or \ref QCPAxis::atTop, you
  16940. might want to also change the minimum margins accordingly, e.g. <tt>setMinimumMargins(QMargins(6, 0, 6, 0))</tt>.
  16941. */
  16942. /* start documentation of inline functions */
  16943. /*! \fn QCPAxis *QCPColorScale::axis() const
  16944. Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the
  16945. appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its
  16946. interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref
  16947. setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref
  16948. QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on
  16949. the QCPColorScale or on its QCPAxis.
  16950. If the type of the color scale is changed with \ref setType, the axis returned by this method
  16951. will change, too, to either the left, right, bottom or top axis, depending on which type was set.
  16952. */
  16953. /* end documentation of signals */
  16954. /* start documentation of signals */
  16955. /*! \fn void QCPColorScale::dataRangeChanged(const QCPRange &newRange);
  16956. This signal is emitted when the data range changes.
  16957. \see setDataRange
  16958. */
  16959. /*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
  16960. This signal is emitted when the data scale type changes.
  16961. \see setDataScaleType
  16962. */
  16963. /*! \fn void QCPColorScale::gradientChanged(const QCPColorGradient &newGradient);
  16964. This signal is emitted when the gradient changes.
  16965. \see setGradient
  16966. */
  16967. /* end documentation of signals */
  16968. /*!
  16969. Constructs a new QCPColorScale.
  16970. */
  16971. QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) :
  16972. QCPLayoutElement(parentPlot),
  16973. mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight
  16974. mDataScaleType(QCPAxis::stLinear),
  16975. mGradient(QCPColorGradient::gpCold),
  16976. mBarWidth(20),
  16977. mAxisRect(new QCPColorScaleAxisRectPrivate(this))
  16978. {
  16979. 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)
  16980. setType(QCPAxis::atRight);
  16981. setDataRange(QCPRange(0, 6));
  16982. }
  16983. QCPColorScale::~QCPColorScale()
  16984. {
  16985. delete mAxisRect;
  16986. }
  16987. /* undocumented getter */
  16988. QString QCPColorScale::label() const
  16989. {
  16990. if (!mColorAxis)
  16991. {
  16992. qDebug() << Q_FUNC_INFO << "internal color axis undefined";
  16993. return QString();
  16994. }
  16995. return mColorAxis.data()->label();
  16996. }
  16997. /* undocumented getter */
  16998. bool QCPColorScale::rangeDrag() const
  16999. {
  17000. if (!mAxisRect)
  17001. {
  17002. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17003. return false;
  17004. }
  17005. return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) &&
  17006. mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) &&
  17007. mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
  17008. }
  17009. /* undocumented getter */
  17010. bool QCPColorScale::rangeZoom() const
  17011. {
  17012. if (!mAxisRect)
  17013. {
  17014. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17015. return false;
  17016. }
  17017. return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) &&
  17018. mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) &&
  17019. mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
  17020. }
  17021. /*!
  17022. Sets at which side of the color scale the axis is placed, and thus also its orientation.
  17023. Note that after setting \a type to a different value, the axis returned by \ref axis() will
  17024. be a different one. The new axis will adopt the following properties from the previous axis: The
  17025. range, scale type, label and ticker (the latter will be shared and not copied).
  17026. */
  17027. void QCPColorScale::setType(QCPAxis::AxisType type)
  17028. {
  17029. if (!mAxisRect)
  17030. {
  17031. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17032. return;
  17033. }
  17034. if (mType != type)
  17035. {
  17036. mType = type;
  17037. QCPRange rangeTransfer(0, 6);
  17038. QString labelTransfer;
  17039. QSharedPointer<QCPAxisTicker> tickerTransfer;
  17040. // transfer/revert some settings on old axis if it exists:
  17041. bool doTransfer = !mColorAxis.isNull();
  17042. if (doTransfer)
  17043. {
  17044. rangeTransfer = mColorAxis.data()->range();
  17045. labelTransfer = mColorAxis.data()->label();
  17046. tickerTransfer = mColorAxis.data()->ticker();
  17047. mColorAxis.data()->setLabel(QString());
  17048. disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  17049. disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  17050. }
  17051. const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop;
  17052. foreach (QCPAxis::AxisType atype, allAxisTypes)
  17053. {
  17054. mAxisRect.data()->axis(atype)->setTicks(atype == mType);
  17055. mAxisRect.data()->axis(atype)->setTickLabels(atype== mType);
  17056. }
  17057. // set new mColorAxis pointer:
  17058. mColorAxis = mAxisRect.data()->axis(mType);
  17059. // transfer settings to new axis:
  17060. if (doTransfer)
  17061. {
  17062. 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)
  17063. mColorAxis.data()->setLabel(labelTransfer);
  17064. mColorAxis.data()->setTicker(tickerTransfer);
  17065. }
  17066. connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  17067. connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  17068. mAxisRect.data()->setRangeDragAxes(QList<QCPAxis*>() << mColorAxis.data());
  17069. }
  17070. }
  17071. /*!
  17072. Sets the range spanned by the color gradient and that is shown by the axis in the color scale.
  17073. It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is
  17074. also equivalent to directly accessing the \ref axis and setting its range with \ref
  17075. QCPAxis::setRange.
  17076. \see setDataScaleType, setGradient, rescaleDataRange
  17077. */
  17078. void QCPColorScale::setDataRange(const QCPRange &dataRange)
  17079. {
  17080. if (!qFuzzyCompare(mDataRange.lower, dataRange.lower) || !qFuzzyCompare(mDataRange.upper, dataRange.upper))
  17081. {
  17082. mDataRange = dataRange;
  17083. if (mColorAxis)
  17084. mColorAxis.data()->setRange(mDataRange);
  17085. emit dataRangeChanged(mDataRange);
  17086. }
  17087. }
  17088. /*!
  17089. Sets the scale type of the color scale, i.e. whether values are associated with colors linearly
  17090. or logarithmically.
  17091. It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is
  17092. also equivalent to directly accessing the \ref axis and setting its scale type with \ref
  17093. QCPAxis::setScaleType.
  17094. Note that this method controls the coordinate transformation. For logarithmic scales, you will
  17095. likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting
  17096. the color scale's \ref axis ticker to an instance of \ref QCPAxisTickerLog :
  17097. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-colorscale
  17098. See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick
  17099. creation.
  17100. \see setDataRange, setGradient
  17101. */
  17102. void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType)
  17103. {
  17104. if (mDataScaleType != scaleType)
  17105. {
  17106. mDataScaleType = scaleType;
  17107. if (mColorAxis)
  17108. mColorAxis.data()->setScaleType(mDataScaleType);
  17109. if (mDataScaleType == QCPAxis::stLogarithmic)
  17110. setDataRange(mDataRange.sanitizedForLogScale());
  17111. emit dataScaleTypeChanged(mDataScaleType);
  17112. }
  17113. }
  17114. /*!
  17115. Sets the color gradient that will be used to represent data values.
  17116. It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps.
  17117. \see setDataRange, setDataScaleType
  17118. */
  17119. void QCPColorScale::setGradient(const QCPColorGradient &gradient)
  17120. {
  17121. if (mGradient != gradient)
  17122. {
  17123. mGradient = gradient;
  17124. if (mAxisRect)
  17125. mAxisRect.data()->mGradientImageInvalidated = true;
  17126. emit gradientChanged(mGradient);
  17127. }
  17128. }
  17129. /*!
  17130. Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on
  17131. the internal \ref axis.
  17132. */
  17133. void QCPColorScale::setLabel(const QString &str)
  17134. {
  17135. if (!mColorAxis)
  17136. {
  17137. qDebug() << Q_FUNC_INFO << "internal color axis undefined";
  17138. return;
  17139. }
  17140. mColorAxis.data()->setLabel(str);
  17141. }
  17142. /*!
  17143. Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed
  17144. will have.
  17145. */
  17146. void QCPColorScale::setBarWidth(int width)
  17147. {
  17148. mBarWidth = width;
  17149. }
  17150. /*!
  17151. Sets whether the user can drag the data range (\ref setDataRange).
  17152. Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref
  17153. QCustomPlot::setInteractions) to allow range dragging.
  17154. */
  17155. void QCPColorScale::setRangeDrag(bool enabled)
  17156. {
  17157. if (!mAxisRect)
  17158. {
  17159. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17160. return;
  17161. }
  17162. if (enabled)
  17163. {
  17164. mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType));
  17165. } else
  17166. {
  17167. #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0)
  17168. mAxisRect.data()->setRangeDrag(nullptr);
  17169. #else
  17170. mAxisRect.data()->setRangeDrag({});
  17171. #endif
  17172. }
  17173. }
  17174. /*!
  17175. Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel.
  17176. Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref
  17177. QCustomPlot::setInteractions) to allow range dragging.
  17178. */
  17179. void QCPColorScale::setRangeZoom(bool enabled)
  17180. {
  17181. if (!mAxisRect)
  17182. {
  17183. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17184. return;
  17185. }
  17186. if (enabled)
  17187. {
  17188. mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType));
  17189. } else
  17190. {
  17191. #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0)
  17192. mAxisRect.data()->setRangeDrag(nullptr);
  17193. #else
  17194. mAxisRect.data()->setRangeZoom({});
  17195. #endif
  17196. }
  17197. }
  17198. /*!
  17199. Returns a list of all the color maps associated with this color scale.
  17200. */
  17201. QList<QCPColorMap*> QCPColorScale::colorMaps() const
  17202. {
  17203. QList<QCPColorMap*> result;
  17204. for (int i=0; i<mParentPlot->plottableCount(); ++i)
  17205. {
  17206. if (QCPColorMap *cm = qobject_cast<QCPColorMap*>(mParentPlot->plottable(i)))
  17207. if (cm->colorScale() == this)
  17208. result.append(cm);
  17209. }
  17210. return result;
  17211. }
  17212. /*!
  17213. Changes the data range such that all color maps associated with this color scale are fully mapped
  17214. to the gradient in the data dimension.
  17215. \see setDataRange
  17216. */
  17217. void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps)
  17218. {
  17219. QList<QCPColorMap*> maps = colorMaps();
  17220. QCPRange newRange;
  17221. bool haveRange = false;
  17222. QCP::SignDomain sign = QCP::sdBoth;
  17223. if (mDataScaleType == QCPAxis::stLogarithmic)
  17224. sign = (mDataRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  17225. foreach (QCPColorMap *map, maps)
  17226. {
  17227. if (!map->realVisibility() && onlyVisibleMaps)
  17228. continue;
  17229. QCPRange mapRange;
  17230. if (map->colorScale() == this)
  17231. {
  17232. bool currentFoundRange = true;
  17233. mapRange = map->data()->dataBounds();
  17234. if (sign == QCP::sdPositive)
  17235. {
  17236. if (mapRange.lower <= 0 && mapRange.upper > 0)
  17237. mapRange.lower = mapRange.upper*1e-3;
  17238. else if (mapRange.lower <= 0 && mapRange.upper <= 0)
  17239. currentFoundRange = false;
  17240. } else if (sign == QCP::sdNegative)
  17241. {
  17242. if (mapRange.upper >= 0 && mapRange.lower < 0)
  17243. mapRange.upper = mapRange.lower*1e-3;
  17244. else if (mapRange.upper >= 0 && mapRange.lower >= 0)
  17245. currentFoundRange = false;
  17246. }
  17247. if (currentFoundRange)
  17248. {
  17249. if (!haveRange)
  17250. newRange = mapRange;
  17251. else
  17252. newRange.expand(mapRange);
  17253. haveRange = true;
  17254. }
  17255. }
  17256. }
  17257. if (haveRange)
  17258. {
  17259. 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
  17260. {
  17261. 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
  17262. if (mDataScaleType == QCPAxis::stLinear)
  17263. {
  17264. newRange.lower = center-mDataRange.size()/2.0;
  17265. newRange.upper = center+mDataRange.size()/2.0;
  17266. } else // mScaleType == stLogarithmic
  17267. {
  17268. newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower);
  17269. newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower);
  17270. }
  17271. }
  17272. setDataRange(newRange);
  17273. }
  17274. }
  17275. /* inherits documentation from base class */
  17276. void QCPColorScale::update(UpdatePhase phase)
  17277. {
  17278. QCPLayoutElement::update(phase);
  17279. if (!mAxisRect)
  17280. {
  17281. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17282. return;
  17283. }
  17284. mAxisRect.data()->update(phase);
  17285. switch (phase)
  17286. {
  17287. case upMargins:
  17288. {
  17289. if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop)
  17290. {
  17291. setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom());
  17292. setMinimumSize(0, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom());
  17293. } else
  17294. {
  17295. setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), QWIDGETSIZE_MAX);
  17296. setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), 0);
  17297. }
  17298. break;
  17299. }
  17300. case upLayout:
  17301. {
  17302. mAxisRect.data()->setOuterRect(rect());
  17303. break;
  17304. }
  17305. default: break;
  17306. }
  17307. }
  17308. /* inherits documentation from base class */
  17309. void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const
  17310. {
  17311. painter->setAntialiasing(false);
  17312. }
  17313. /* inherits documentation from base class */
  17314. void QCPColorScale::mousePressEvent(QMouseEvent *event, const QVariant &details)
  17315. {
  17316. if (!mAxisRect)
  17317. {
  17318. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17319. return;
  17320. }
  17321. mAxisRect.data()->mousePressEvent(event, details);
  17322. }
  17323. /* inherits documentation from base class */
  17324. void QCPColorScale::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  17325. {
  17326. if (!mAxisRect)
  17327. {
  17328. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17329. return;
  17330. }
  17331. mAxisRect.data()->mouseMoveEvent(event, startPos);
  17332. }
  17333. /* inherits documentation from base class */
  17334. void QCPColorScale::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  17335. {
  17336. if (!mAxisRect)
  17337. {
  17338. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17339. return;
  17340. }
  17341. mAxisRect.data()->mouseReleaseEvent(event, startPos);
  17342. }
  17343. /* inherits documentation from base class */
  17344. void QCPColorScale::wheelEvent(QWheelEvent *event)
  17345. {
  17346. if (!mAxisRect)
  17347. {
  17348. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17349. return;
  17350. }
  17351. mAxisRect.data()->wheelEvent(event);
  17352. }
  17353. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17354. //////////////////// QCPColorScaleAxisRectPrivate
  17355. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17356. /*! \class QCPColorScaleAxisRectPrivate
  17357. \internal
  17358. \brief An axis rect subclass for use in a QCPColorScale
  17359. This is a private class and not part of the public QCustomPlot interface.
  17360. It provides the axis rect functionality for the QCPColorScale class.
  17361. */
  17362. /*!
  17363. Creates a new instance, as a child of \a parentColorScale.
  17364. */
  17365. QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) :
  17366. QCPAxisRect(parentColorScale->parentPlot(), true),
  17367. mParentColorScale(parentColorScale),
  17368. mGradientImageInvalidated(true)
  17369. {
  17370. setParentLayerable(parentColorScale);
  17371. setMinimumMargins(QMargins(0, 0, 0, 0));
  17372. const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
  17373. foreach (QCPAxis::AxisType type, allAxisTypes)
  17374. {
  17375. axis(type)->setVisible(true);
  17376. axis(type)->grid()->setVisible(false);
  17377. axis(type)->setPadding(0);
  17378. connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts)));
  17379. connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts)));
  17380. }
  17381. connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange)));
  17382. connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange)));
  17383. connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange)));
  17384. connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange)));
  17385. connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType)));
  17386. connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType)));
  17387. connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType)));
  17388. connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType)));
  17389. // make layer transfers of color scale transfer to axis rect and axes
  17390. // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect:
  17391. connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*)));
  17392. foreach (QCPAxis::AxisType type, allAxisTypes)
  17393. connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*)));
  17394. }
  17395. /*! \internal
  17396. Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws
  17397. it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation.
  17398. \seebaseclassmethod
  17399. */
  17400. void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter)
  17401. {
  17402. if (mGradientImageInvalidated)
  17403. updateGradientImage();
  17404. bool mirrorHorz = false;
  17405. bool mirrorVert = false;
  17406. if (mParentColorScale->mColorAxis)
  17407. {
  17408. mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop);
  17409. mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight);
  17410. }
  17411. painter->drawImage(rect().adjusted(0, -1, 0, -1), mGradientImage.mirrored(mirrorHorz, mirrorVert));
  17412. QCPAxisRect::draw(painter);
  17413. }
  17414. /*! \internal
  17415. Uses the current gradient of the parent \ref QCPColorScale (specified in the constructor) to
  17416. generate a gradient image. This gradient image will be used in the \ref draw method.
  17417. */
  17418. void QCPColorScaleAxisRectPrivate::updateGradientImage()
  17419. {
  17420. if (rect().isEmpty())
  17421. return;
  17422. const QImage::Format format = QImage::Format_ARGB32_Premultiplied;
  17423. int n = mParentColorScale->mGradient.levelCount();
  17424. int w, h;
  17425. QVector<double> data(n);
  17426. for (int i=0; i<n; ++i)
  17427. data[i] = i;
  17428. if (mParentColorScale->mType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop)
  17429. {
  17430. w = n;
  17431. h = rect().height();
  17432. mGradientImage = QImage(w, h, format);
  17433. QVector<QRgb*> pixels;
  17434. for (int y=0; y<h; ++y)
  17435. pixels.append(reinterpret_cast<QRgb*>(mGradientImage.scanLine(y)));
  17436. mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n);
  17437. for (int y=1; y<h; ++y)
  17438. memcpy(pixels.at(y), pixels.first(), size_t(n)*sizeof(QRgb));
  17439. } else
  17440. {
  17441. w = rect().width();
  17442. h = n;
  17443. mGradientImage = QImage(w, h, format);
  17444. for (int y=0; y<h; ++y)
  17445. {
  17446. QRgb *pixels = reinterpret_cast<QRgb*>(mGradientImage.scanLine(y));
  17447. const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1));
  17448. for (int x=0; x<w; ++x)
  17449. pixels[x] = lineColor;
  17450. }
  17451. }
  17452. mGradientImageInvalidated = false;
  17453. }
  17454. /*! \internal
  17455. This slot is connected to the selectionChanged signals of the four axes in the constructor. It
  17456. synchronizes the selection state of the axes.
  17457. */
  17458. void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts selectedParts)
  17459. {
  17460. // axis bases of four axes shall always (de-)selected synchronously:
  17461. const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
  17462. foreach (QCPAxis::AxisType type, allAxisTypes)
  17463. {
  17464. if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
  17465. if (senderAxis->axisType() == type)
  17466. continue;
  17467. if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
  17468. {
  17469. if (selectedParts.testFlag(QCPAxis::spAxis))
  17470. axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis);
  17471. else
  17472. axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis);
  17473. }
  17474. }
  17475. }
  17476. /*! \internal
  17477. This slot is connected to the selectableChanged signals of the four axes in the constructor. It
  17478. synchronizes the selectability of the axes.
  17479. */
  17480. void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts)
  17481. {
  17482. // synchronize axis base selectability:
  17483. const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
  17484. foreach (QCPAxis::AxisType type, allAxisTypes)
  17485. {
  17486. if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
  17487. if (senderAxis->axisType() == type)
  17488. continue;
  17489. if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
  17490. {
  17491. if (selectableParts.testFlag(QCPAxis::spAxis))
  17492. axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis);
  17493. else
  17494. axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis);
  17495. }
  17496. }
  17497. }
  17498. /* end of 'src/layoutelements/layoutelement-colorscale.cpp' */
  17499. /* including file 'src/plottables/plottable-graph.cpp' */
  17500. /* modified 2021-03-29T02:30:44, size 74518 */
  17501. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17502. //////////////////// QCPGraphData
  17503. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17504. /*! \class QCPGraphData
  17505. \brief Holds the data of one single data point for QCPGraph.
  17506. The stored data is:
  17507. \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
  17508. \li \a value: coordinate on the value axis of this data point (this is the \a mainValue)
  17509. The container for storing multiple data points is \ref QCPGraphDataContainer. It is a typedef for
  17510. \ref QCPDataContainer with \ref QCPGraphData as the DataType template parameter. See the
  17511. documentation there for an explanation regarding the data type's generic methods.
  17512. \see QCPGraphDataContainer
  17513. */
  17514. /* start documentation of inline functions */
  17515. /*! \fn double QCPGraphData::sortKey() const
  17516. Returns the \a key member of this data point.
  17517. For a general explanation of what this method is good for in the context of the data container,
  17518. see the documentation of \ref QCPDataContainer.
  17519. */
  17520. /*! \fn static QCPGraphData QCPGraphData::fromSortKey(double sortKey)
  17521. Returns a data point with the specified \a sortKey. All other members are set to zero.
  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 static bool QCPGraphData::sortKeyIsMainKey()
  17526. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  17527. this method returns true.
  17528. For a general explanation of what this method is good for in the context of the data container,
  17529. see the documentation of \ref QCPDataContainer.
  17530. */
  17531. /*! \fn double QCPGraphData::mainKey() const
  17532. Returns the \a key member of this data point.
  17533. For a general explanation of what this method is good for in the context of the data container,
  17534. see the documentation of \ref QCPDataContainer.
  17535. */
  17536. /*! \fn double QCPGraphData::mainValue() const
  17537. Returns the \a value 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 QCPRange QCPGraphData::valueRange() const
  17542. Returns a QCPRange with both lower and upper boundary set to \a value 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. /* end documentation of inline functions */
  17547. /*!
  17548. Constructs a data point with key and value set to zero.
  17549. */
  17550. QCPGraphData::QCPGraphData() :
  17551. key(0),
  17552. value(0)
  17553. {
  17554. }
  17555. /*!
  17556. Constructs a data point with the specified \a key and \a value.
  17557. */
  17558. QCPGraphData::QCPGraphData(double key, double value) :
  17559. key(key),
  17560. value(value)
  17561. {
  17562. }
  17563. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17564. //////////////////// QCPGraph
  17565. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17566. /*! \class QCPGraph
  17567. \brief A plottable representing a graph in a plot.
  17568. \image html QCPGraph.png
  17569. Usually you create new graphs by calling QCustomPlot::addGraph. The resulting instance can be
  17570. accessed via QCustomPlot::graph.
  17571. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
  17572. also access and modify the data via the \ref data method, which returns a pointer to the internal
  17573. \ref QCPGraphDataContainer.
  17574. Graphs are used to display single-valued data. Single-valued means that there should only be one
  17575. data point per unique key coordinate. In other words, the graph can't have \a loops. If you do
  17576. want to plot non-single-valued curves, rather use the QCPCurve plottable.
  17577. Gaps in the graph line can be created by adding data points with NaN as value
  17578. (<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
  17579. separated.
  17580. \section qcpgraph-appearance Changing the appearance
  17581. The appearance of the graph is mainly determined by the line style, scatter style, brush and pen
  17582. of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen).
  17583. \subsection filling Filling under or between graphs
  17584. QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to
  17585. the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill,
  17586. just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent.
  17587. By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill
  17588. between this graph and another one, call \ref setChannelFillGraph with the other graph as
  17589. parameter.
  17590. \see QCustomPlot::addGraph, QCustomPlot::graph
  17591. */
  17592. /* start of documentation of inline functions */
  17593. /*! \fn QSharedPointer<QCPGraphDataContainer> QCPGraph::data() const
  17594. Returns a shared pointer to the internal data storage of type \ref QCPGraphDataContainer. You may
  17595. use it to directly manipulate the data, which may be more convenient and faster than using the
  17596. regular \ref setData or \ref addData methods.
  17597. */
  17598. /* end of documentation of inline functions */
  17599. /*!
  17600. Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  17601. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  17602. the same orientation. If either of these restrictions is violated, a corresponding message is
  17603. printed to the debug output (qDebug), the construction is not aborted, though.
  17604. The created QCPGraph is automatically registered with the QCustomPlot instance inferred from \a
  17605. keyAxis. This QCustomPlot instance takes ownership of the QCPGraph, so do not delete it manually
  17606. but use QCustomPlot::removePlottable() instead.
  17607. To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function.
  17608. */
  17609. QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  17610. QCPAbstractPlottable1D<QCPGraphData>(keyAxis, valueAxis),
  17611. mLineStyle{},
  17612. mScatterSkip{},
  17613. mAdaptiveSampling{}
  17614. {
  17615. // special handling for QCPGraphs to maintain the simple graph interface:
  17616. mParentPlot->registerGraph(this);
  17617. setPen(QPen(Qt::blue, 0));
  17618. setBrush(Qt::NoBrush);
  17619. setLineStyle(lsLine);
  17620. setScatterSkip(0);
  17621. setChannelFillGraph(nullptr);
  17622. setAdaptiveSampling(true);
  17623. }
  17624. QCPGraph::~QCPGraph()
  17625. {
  17626. }
  17627. /*! \overload
  17628. Replaces the current data container with the provided \a data container.
  17629. Since a QSharedPointer is used, multiple QCPGraphs may share the same data container safely.
  17630. Modifying the data in the container will then affect all graphs that share the container. Sharing
  17631. can be achieved by simply exchanging the data containers wrapped in shared pointers:
  17632. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-1
  17633. If you do not wish to share containers, but create a copy from an existing container, rather use
  17634. the \ref QCPDataContainer<DataType>::set method on the graph's data container directly:
  17635. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-2
  17636. \see addData
  17637. */
  17638. void QCPGraph::setData(QSharedPointer<QCPGraphDataContainer> data)
  17639. {
  17640. mDataContainer = data;
  17641. }
  17642. /*! \overload
  17643. Replaces the current data with the provided points in \a keys and \a values. The provided
  17644. vectors should have equal length. Else, the number of added points will be the size of the
  17645. smallest vector.
  17646. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  17647. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  17648. \see addData
  17649. */
  17650. void QCPGraph::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  17651. {
  17652. mDataContainer->clear();
  17653. addData(keys, values, alreadySorted);
  17654. }
  17655. /*!
  17656. Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
  17657. \ref lsNone and \ref setScatterStyle to the desired scatter style.
  17658. \see setScatterStyle
  17659. */
  17660. void QCPGraph::setLineStyle(LineStyle ls)
  17661. {
  17662. mLineStyle = ls;
  17663. }
  17664. /*!
  17665. Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points
  17666. are drawn (e.g. for line-only-plots with appropriate line style).
  17667. \see QCPScatterStyle, setLineStyle
  17668. */
  17669. void QCPGraph::setScatterStyle(const QCPScatterStyle &style)
  17670. {
  17671. mScatterStyle = style;
  17672. }
  17673. /*!
  17674. If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of
  17675. scatter points are skipped/not drawn after every drawn scatter point.
  17676. This can be used to make the data appear sparser while for example still having a smooth line,
  17677. and to improve performance for very high density plots.
  17678. If \a skip is set to 0 (default), all scatter points are drawn.
  17679. \see setScatterStyle
  17680. */
  17681. void QCPGraph::setScatterSkip(int skip)
  17682. {
  17683. mScatterSkip = qMax(0, skip);
  17684. }
  17685. /*!
  17686. Sets the target graph for filling the area between this graph and \a targetGraph with the current
  17687. brush (\ref setBrush).
  17688. When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To
  17689. disable any filling, set the brush to Qt::NoBrush.
  17690. \see setBrush
  17691. */
  17692. void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph)
  17693. {
  17694. // prevent setting channel target to this graph itself:
  17695. if (targetGraph == this)
  17696. {
  17697. qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself";
  17698. mChannelFillGraph = nullptr;
  17699. return;
  17700. }
  17701. // prevent setting channel target to a graph not in the plot:
  17702. if (targetGraph && targetGraph->mParentPlot != mParentPlot)
  17703. {
  17704. qDebug() << Q_FUNC_INFO << "targetGraph not in same plot";
  17705. mChannelFillGraph = nullptr;
  17706. return;
  17707. }
  17708. mChannelFillGraph = targetGraph;
  17709. }
  17710. /*!
  17711. Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive
  17712. sampling technique can drastically improve the replot performance for graphs with a larger number
  17713. of points (e.g. above 10,000), without notably changing the appearance of the graph.
  17714. By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive
  17715. sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no
  17716. disadvantage in almost all cases.
  17717. \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling"
  17718. As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are
  17719. reproduced reliably, as well as the overall shape of the data set. The replot time reduces
  17720. dramatically though. This allows QCustomPlot to display large amounts of data in realtime.
  17721. \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling"
  17722. Care must be taken when using high-density scatter plots in combination with adaptive sampling.
  17723. The adaptive sampling algorithm treats scatter plots more carefully than line plots which still
  17724. gives a significant reduction of replot times, but not quite as much as for line plots. This is
  17725. because scatter plots inherently need more data points to be preserved in order to still resemble
  17726. the original, non-adaptive-sampling plot. As shown above, the results still aren't quite
  17727. identical, as banding occurs for the outer data points. This is in fact intentional, such that
  17728. the boundaries of the data cloud stay visible to the viewer. How strong the banding appears,
  17729. depends on the point density, i.e. the number of points in the plot.
  17730. For some situations with scatter plots it might thus be desirable to manually turn adaptive
  17731. sampling off. For example, when saving the plot to disk. This can be achieved by setting \a
  17732. enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled
  17733. back to true afterwards.
  17734. */
  17735. void QCPGraph::setAdaptiveSampling(bool enabled)
  17736. {
  17737. mAdaptiveSampling = enabled;
  17738. }
  17739. /*! \overload
  17740. Adds the provided points in \a keys and \a values to the current data. The provided vectors
  17741. should have equal length. Else, the number of added points will be the size of the smallest
  17742. vector.
  17743. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  17744. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  17745. Alternatively, you can also access and modify the data directly via the \ref data method, which
  17746. returns a pointer to the internal data container.
  17747. */
  17748. void QCPGraph::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  17749. {
  17750. if (keys.size() != values.size())
  17751. qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
  17752. const int n = qMin(keys.size(), values.size());
  17753. QVector<QCPGraphData> tempData(n);
  17754. QVector<QCPGraphData>::iterator it = tempData.begin();
  17755. const QVector<QCPGraphData>::iterator itEnd = tempData.end();
  17756. int i = 0;
  17757. while (it != itEnd)
  17758. {
  17759. it->key = keys[i];
  17760. it->value = values[i];
  17761. ++it;
  17762. ++i;
  17763. }
  17764. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  17765. }
  17766. /*! \overload
  17767. Adds the provided data point as \a key and \a value to the current data.
  17768. Alternatively, you can also access and modify the data directly via the \ref data method, which
  17769. returns a pointer to the internal data container.
  17770. */
  17771. void QCPGraph::addData(double key, double value)
  17772. {
  17773. mDataContainer->add(QCPGraphData(key, value));
  17774. }
  17775. /*!
  17776. Implements a selectTest specific to this plottable's point geometry.
  17777. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  17778. point to \a pos.
  17779. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  17780. */
  17781. double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  17782. {
  17783. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  17784. return -1;
  17785. if (!mKeyAxis || !mValueAxis)
  17786. return -1;
  17787. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  17788. {
  17789. QCPGraphDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  17790. double result = pointDistance(pos, closestDataPoint);
  17791. if (details)
  17792. {
  17793. int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
  17794. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  17795. }
  17796. return result;
  17797. } else
  17798. return -1;
  17799. }
  17800. /* inherits documentation from base class */
  17801. QCPRange QCPGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  17802. {
  17803. return mDataContainer->keyRange(foundRange, inSignDomain);
  17804. }
  17805. /* inherits documentation from base class */
  17806. QCPRange QCPGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  17807. {
  17808. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  17809. }
  17810. /* inherits documentation from base class */
  17811. void QCPGraph::draw(QCPPainter *painter)
  17812. {
  17813. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  17814. if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
  17815. if (mLineStyle == lsNone && mScatterStyle.isNone()) return;
  17816. QVector<QPointF> lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments
  17817. // loop over and draw segments of unselected/selected data:
  17818. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  17819. getDataSegments(selectedSegments, unselectedSegments);
  17820. allSegments << unselectedSegments << selectedSegments;
  17821. for (int i=0; i<allSegments.size(); ++i)
  17822. {
  17823. bool isSelectedSegment = i >= unselectedSegments.size();
  17824. // get line pixel points appropriate to line style:
  17825. 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)
  17826. getLines(&lines, lineDataRange);
  17827. // check data validity if flag set:
  17828. #ifdef QCUSTOMPLOT_CHECK_DATA
  17829. QCPGraphDataContainer::const_iterator it;
  17830. for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  17831. {
  17832. if (QCP::isInvalidData(it->key, it->value))
  17833. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
  17834. }
  17835. #endif
  17836. // draw fill of graph:
  17837. if (isSelectedSegment && mSelectionDecorator)
  17838. mSelectionDecorator->applyBrush(painter);
  17839. else
  17840. painter->setBrush(mBrush);
  17841. painter->setPen(Qt::NoPen);
  17842. drawFill(painter, &lines);
  17843. // draw line:
  17844. if (mLineStyle != lsNone)
  17845. {
  17846. if (isSelectedSegment && mSelectionDecorator)
  17847. mSelectionDecorator->applyPen(painter);
  17848. else
  17849. painter->setPen(mPen);
  17850. painter->setBrush(Qt::NoBrush);
  17851. if (mLineStyle == lsImpulse)
  17852. drawImpulsePlot(painter, lines);
  17853. else
  17854. drawLinePlot(painter, lines); // also step plots can be drawn as a line plot
  17855. }
  17856. // draw scatters:
  17857. QCPScatterStyle finalScatterStyle = mScatterStyle;
  17858. if (isSelectedSegment && mSelectionDecorator)
  17859. finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
  17860. if (!finalScatterStyle.isNone())
  17861. {
  17862. getScatters(&scatters, allSegments.at(i));
  17863. drawScatterPlot(painter, scatters, finalScatterStyle);
  17864. }
  17865. }
  17866. // draw other selection decoration that isn't just line/scatter pens and brushes:
  17867. if (mSelectionDecorator)
  17868. mSelectionDecorator->drawDecoration(painter, selection());
  17869. }
  17870. /* inherits documentation from base class */
  17871. void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  17872. {
  17873. // draw fill:
  17874. if (mBrush.style() != Qt::NoBrush)
  17875. {
  17876. applyFillAntialiasingHint(painter);
  17877. painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
  17878. }
  17879. // draw line vertically centered:
  17880. if (mLineStyle != lsNone)
  17881. {
  17882. applyDefaultAntialiasingHint(painter);
  17883. painter->setPen(mPen);
  17884. 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
  17885. }
  17886. // draw scatter symbol:
  17887. if (!mScatterStyle.isNone())
  17888. {
  17889. applyScattersAntialiasingHint(painter);
  17890. // scale scatter pixmap if it's too large to fit in legend icon rect:
  17891. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
  17892. {
  17893. QCPScatterStyle scaledStyle(mScatterStyle);
  17894. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  17895. scaledStyle.applyTo(painter, mPen);
  17896. scaledStyle.drawShape(painter, QRectF(rect).center());
  17897. } else
  17898. {
  17899. mScatterStyle.applyTo(painter, mPen);
  17900. mScatterStyle.drawShape(painter, QRectF(rect).center());
  17901. }
  17902. }
  17903. }
  17904. /*! \internal
  17905. This method retrieves an optimized set of data points via \ref getOptimizedLineData, and branches
  17906. out to the line style specific functions such as \ref dataToLines, \ref dataToStepLeftLines, etc.
  17907. according to the line style of the graph.
  17908. \a lines will be filled with points in pixel coordinates, that can be drawn with the according
  17909. draw functions like \ref drawLinePlot and \ref drawImpulsePlot. The points returned in \a lines
  17910. aren't necessarily the original data points. For example, step line styles require additional
  17911. points to form the steps when drawn. If the line style of the graph is \ref lsNone, the \a
  17912. lines vector will be empty.
  17913. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  17914. conversion. In this function, the specified range may exceed the total data bounds without harm:
  17915. a correspondingly trimmed data range will be used. This takes the burden off the user of this
  17916. function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
  17917. getDataSegments.
  17918. \see getScatters
  17919. */
  17920. void QCPGraph::getLines(QVector<QPointF> *lines, const QCPDataRange &dataRange) const
  17921. {
  17922. if (!lines) return;
  17923. QCPGraphDataContainer::const_iterator begin, end;
  17924. getVisibleDataBounds(begin, end, dataRange);
  17925. if (begin == end)
  17926. {
  17927. lines->clear();
  17928. return;
  17929. }
  17930. QVector<QCPGraphData> lineData;
  17931. if (mLineStyle != lsNone)
  17932. getOptimizedLineData(&lineData, begin, end);
  17933. if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in lineData (significantly simplifies following processing)
  17934. std::reverse(lineData.begin(), lineData.end());
  17935. switch (mLineStyle)
  17936. {
  17937. case lsNone: lines->clear(); break;
  17938. case lsLine: *lines = dataToLines(lineData); break;
  17939. case lsStepLeft: *lines = dataToStepLeftLines(lineData); break;
  17940. case lsStepRight: *lines = dataToStepRightLines(lineData); break;
  17941. case lsStepCenter: *lines = dataToStepCenterLines(lineData); break;
  17942. case lsImpulse: *lines = dataToImpulseLines(lineData); break;
  17943. }
  17944. }
  17945. /*! \internal
  17946. This method retrieves an optimized set of data points via \ref getOptimizedScatterData and then
  17947. converts them to pixel coordinates. The resulting points are returned in \a scatters, and can be
  17948. passed to \ref drawScatterPlot.
  17949. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  17950. conversion. In this function, the specified range may exceed the total data bounds without harm:
  17951. a correspondingly trimmed data range will be used. This takes the burden off the user of this
  17952. function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
  17953. getDataSegments.
  17954. */
  17955. void QCPGraph::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange) const
  17956. {
  17957. if (!scatters) return;
  17958. QCPAxis *keyAxis = mKeyAxis.data();
  17959. QCPAxis *valueAxis = mValueAxis.data();
  17960. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; scatters->clear(); return; }
  17961. QCPGraphDataContainer::const_iterator begin, end;
  17962. getVisibleDataBounds(begin, end, dataRange);
  17963. if (begin == end)
  17964. {
  17965. scatters->clear();
  17966. return;
  17967. }
  17968. QVector<QCPGraphData> data;
  17969. getOptimizedScatterData(&data, begin, end);
  17970. if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in data (significantly simplifies following processing)
  17971. std::reverse(data.begin(), data.end());
  17972. scatters->resize(data.size());
  17973. if (keyAxis->orientation() == Qt::Vertical)
  17974. {
  17975. for (int i=0; i<data.size(); ++i)
  17976. {
  17977. if (!qIsNaN(data.at(i).value))
  17978. {
  17979. (*scatters)[i].setX(valueAxis->coordToPixel(data.at(i).value));
  17980. (*scatters)[i].setY(keyAxis->coordToPixel(data.at(i).key));
  17981. }
  17982. }
  17983. } else
  17984. {
  17985. for (int i=0; i<data.size(); ++i)
  17986. {
  17987. if (!qIsNaN(data.at(i).value))
  17988. {
  17989. (*scatters)[i].setX(keyAxis->coordToPixel(data.at(i).key));
  17990. (*scatters)[i].setY(valueAxis->coordToPixel(data.at(i).value));
  17991. }
  17992. }
  17993. }
  17994. }
  17995. /*! \internal
  17996. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  17997. coordinate points which are suitable for drawing the line style \ref lsLine.
  17998. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  17999. getLines if the line style is set accordingly.
  18000. \see dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
  18001. */
  18002. QVector<QPointF> QCPGraph::dataToLines(const QVector<QCPGraphData> &data) const
  18003. {
  18004. QVector<QPointF> result;
  18005. QCPAxis *keyAxis = mKeyAxis.data();
  18006. QCPAxis *valueAxis = mValueAxis.data();
  18007. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  18008. result.resize(data.size());
  18009. // transform data points to pixels:
  18010. if (keyAxis->orientation() == Qt::Vertical)
  18011. {
  18012. for (int i=0; i<data.size(); ++i)
  18013. {
  18014. result[i].setX(valueAxis->coordToPixel(data.at(i).value));
  18015. result[i].setY(keyAxis->coordToPixel(data.at(i).key));
  18016. }
  18017. } else // key axis is horizontal
  18018. {
  18019. for (int i=0; i<data.size(); ++i)
  18020. {
  18021. result[i].setX(keyAxis->coordToPixel(data.at(i).key));
  18022. result[i].setY(valueAxis->coordToPixel(data.at(i).value));
  18023. }
  18024. }
  18025. return result;
  18026. }
  18027. /*! \internal
  18028. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  18029. coordinate points which are suitable for drawing the line style \ref lsStepLeft.
  18030. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  18031. getLines if the line style is set accordingly.
  18032. \see dataToLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
  18033. */
  18034. QVector<QPointF> QCPGraph::dataToStepLeftLines(const QVector<QCPGraphData> &data) const
  18035. {
  18036. QVector<QPointF> result;
  18037. QCPAxis *keyAxis = mKeyAxis.data();
  18038. QCPAxis *valueAxis = mValueAxis.data();
  18039. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  18040. result.resize(data.size()*2);
  18041. // calculate steps from data and transform to pixel coordinates:
  18042. if (keyAxis->orientation() == Qt::Vertical)
  18043. {
  18044. double lastValue = valueAxis->coordToPixel(data.first().value);
  18045. for (int i=0; i<data.size(); ++i)
  18046. {
  18047. const double key = keyAxis->coordToPixel(data.at(i).key);
  18048. result[i*2+0].setX(lastValue);
  18049. result[i*2+0].setY(key);
  18050. lastValue = valueAxis->coordToPixel(data.at(i).value);
  18051. result[i*2+1].setX(lastValue);
  18052. result[i*2+1].setY(key);
  18053. }
  18054. } else // key axis is horizontal
  18055. {
  18056. double lastValue = valueAxis->coordToPixel(data.first().value);
  18057. for (int i=0; i<data.size(); ++i)
  18058. {
  18059. const double key = keyAxis->coordToPixel(data.at(i).key);
  18060. result[i*2+0].setX(key);
  18061. result[i*2+0].setY(lastValue);
  18062. lastValue = valueAxis->coordToPixel(data.at(i).value);
  18063. result[i*2+1].setX(key);
  18064. result[i*2+1].setY(lastValue);
  18065. }
  18066. }
  18067. return result;
  18068. }
  18069. /*! \internal
  18070. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  18071. coordinate points which are suitable for drawing the line style \ref lsStepRight.
  18072. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  18073. getLines if the line style is set accordingly.
  18074. \see dataToLines, dataToStepLeftLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
  18075. */
  18076. QVector<QPointF> QCPGraph::dataToStepRightLines(const QVector<QCPGraphData> &data) const
  18077. {
  18078. QVector<QPointF> result;
  18079. QCPAxis *keyAxis = mKeyAxis.data();
  18080. QCPAxis *valueAxis = mValueAxis.data();
  18081. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  18082. result.resize(data.size()*2);
  18083. // calculate steps from data and transform to pixel coordinates:
  18084. if (keyAxis->orientation() == Qt::Vertical)
  18085. {
  18086. double lastKey = keyAxis->coordToPixel(data.first().key);
  18087. for (int i=0; i<data.size(); ++i)
  18088. {
  18089. const double value = valueAxis->coordToPixel(data.at(i).value);
  18090. result[i*2+0].setX(value);
  18091. result[i*2+0].setY(lastKey);
  18092. lastKey = keyAxis->coordToPixel(data.at(i).key);
  18093. result[i*2+1].setX(value);
  18094. result[i*2+1].setY(lastKey);
  18095. }
  18096. } else // key axis is horizontal
  18097. {
  18098. double lastKey = keyAxis->coordToPixel(data.first().key);
  18099. for (int i=0; i<data.size(); ++i)
  18100. {
  18101. const double value = valueAxis->coordToPixel(data.at(i).value);
  18102. result[i*2+0].setX(lastKey);
  18103. result[i*2+0].setY(value);
  18104. lastKey = keyAxis->coordToPixel(data.at(i).key);
  18105. result[i*2+1].setX(lastKey);
  18106. result[i*2+1].setY(value);
  18107. }
  18108. }
  18109. return result;
  18110. }
  18111. /*! \internal
  18112. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  18113. coordinate points which are suitable for drawing the line style \ref lsStepCenter.
  18114. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  18115. getLines if the line style is set accordingly.
  18116. \see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToImpulseLines, getLines, drawLinePlot
  18117. */
  18118. QVector<QPointF> QCPGraph::dataToStepCenterLines(const QVector<QCPGraphData> &data) const
  18119. {
  18120. QVector<QPointF> result;
  18121. QCPAxis *keyAxis = mKeyAxis.data();
  18122. QCPAxis *valueAxis = mValueAxis.data();
  18123. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  18124. result.resize(data.size()*2);
  18125. // calculate steps from data and transform to pixel coordinates:
  18126. if (keyAxis->orientation() == Qt::Vertical)
  18127. {
  18128. double lastKey = keyAxis->coordToPixel(data.first().key);
  18129. double lastValue = valueAxis->coordToPixel(data.first().value);
  18130. result[0].setX(lastValue);
  18131. result[0].setY(lastKey);
  18132. for (int i=1; i<data.size(); ++i)
  18133. {
  18134. const double key = (keyAxis->coordToPixel(data.at(i).key)+lastKey)*0.5;
  18135. result[i*2-1].setX(lastValue);
  18136. result[i*2-1].setY(key);
  18137. lastValue = valueAxis->coordToPixel(data.at(i).value);
  18138. lastKey = keyAxis->coordToPixel(data.at(i).key);
  18139. result[i*2+0].setX(lastValue);
  18140. result[i*2+0].setY(key);
  18141. }
  18142. result[data.size()*2-1].setX(lastValue);
  18143. result[data.size()*2-1].setY(lastKey);
  18144. } else // key axis is horizontal
  18145. {
  18146. double lastKey = keyAxis->coordToPixel(data.first().key);
  18147. double lastValue = valueAxis->coordToPixel(data.first().value);
  18148. result[0].setX(lastKey);
  18149. result[0].setY(lastValue);
  18150. for (int i=1; i<data.size(); ++i)
  18151. {
  18152. const double key = (keyAxis->coordToPixel(data.at(i).key)+lastKey)*0.5;
  18153. result[i*2-1].setX(key);
  18154. result[i*2-1].setY(lastValue);
  18155. lastValue = valueAxis->coordToPixel(data.at(i).value);
  18156. lastKey = keyAxis->coordToPixel(data.at(i).key);
  18157. result[i*2+0].setX(key);
  18158. result[i*2+0].setY(lastValue);
  18159. }
  18160. result[data.size()*2-1].setX(lastKey);
  18161. result[data.size()*2-1].setY(lastValue);
  18162. }
  18163. return result;
  18164. }
  18165. /*! \internal
  18166. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  18167. coordinate points which are suitable for drawing the line style \ref lsImpulse.
  18168. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  18169. getLines if the line style is set accordingly.
  18170. \see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, getLines, drawImpulsePlot
  18171. */
  18172. QVector<QPointF> QCPGraph::dataToImpulseLines(const QVector<QCPGraphData> &data) const
  18173. {
  18174. QVector<QPointF> result;
  18175. QCPAxis *keyAxis = mKeyAxis.data();
  18176. QCPAxis *valueAxis = mValueAxis.data();
  18177. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  18178. result.resize(data.size()*2);
  18179. // transform data points to pixels:
  18180. if (keyAxis->orientation() == Qt::Vertical)
  18181. {
  18182. for (int i=0; i<data.size(); ++i)
  18183. {
  18184. const double key = keyAxis->coordToPixel(data.at(i).key);
  18185. result[i*2+0].setX(valueAxis->coordToPixel(0));
  18186. result[i*2+0].setY(key);
  18187. result[i*2+1].setX(valueAxis->coordToPixel(data.at(i).value));
  18188. result[i*2+1].setY(key);
  18189. }
  18190. } else // key axis is horizontal
  18191. {
  18192. for (int i=0; i<data.size(); ++i)
  18193. {
  18194. const double key = keyAxis->coordToPixel(data.at(i).key);
  18195. result[i*2+0].setX(key);
  18196. result[i*2+0].setY(valueAxis->coordToPixel(0));
  18197. result[i*2+1].setX(key);
  18198. result[i*2+1].setY(valueAxis->coordToPixel(data.at(i).value));
  18199. }
  18200. }
  18201. return result;
  18202. }
  18203. /*! \internal
  18204. Draws the fill of the graph using the specified \a painter, with the currently set brush.
  18205. Depending on whether a normal fill or a channel fill (\ref setChannelFillGraph) is needed, \ref
  18206. getFillPolygon or \ref getChannelFillPolygon are used to find the according fill polygons.
  18207. In order to handle NaN Data points correctly (the fill needs to be split into disjoint areas),
  18208. this method first determines a list of non-NaN segments with \ref getNonNanSegments, on which to
  18209. operate. In the channel fill case, \ref getOverlappingSegments is used to consolidate the non-NaN
  18210. segments of the two involved graphs, before passing the overlapping pairs to \ref
  18211. getChannelFillPolygon.
  18212. Pass the points of this graph's line as \a lines, in pixel coordinates.
  18213. \see drawLinePlot, drawImpulsePlot, drawScatterPlot
  18214. */
  18215. void QCPGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lines) const
  18216. {
  18217. if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot
  18218. if (painter->brush().style() == Qt::NoBrush || painter->brush().color().alpha() == 0) return;
  18219. applyFillAntialiasingHint(painter);
  18220. const QVector<QCPDataRange> segments = getNonNanSegments(lines, keyAxis()->orientation());
  18221. if (!mChannelFillGraph)
  18222. {
  18223. // draw base fill under graph, fill goes all the way to the zero-value-line:
  18224. foreach (QCPDataRange segment, segments)
  18225. painter->drawPolygon(getFillPolygon(lines, segment));
  18226. } else
  18227. {
  18228. // draw fill between this graph and mChannelFillGraph:
  18229. QVector<QPointF> otherLines;
  18230. mChannelFillGraph->getLines(&otherLines, QCPDataRange(0, mChannelFillGraph->dataCount()));
  18231. if (!otherLines.isEmpty())
  18232. {
  18233. QVector<QCPDataRange> otherSegments = getNonNanSegments(&otherLines, mChannelFillGraph->keyAxis()->orientation());
  18234. QVector<QPair<QCPDataRange, QCPDataRange> > segmentPairs = getOverlappingSegments(segments, lines, otherSegments, &otherLines);
  18235. for (int i=0; i<segmentPairs.size(); ++i)
  18236. painter->drawPolygon(getChannelFillPolygon(lines, segmentPairs.at(i).first, &otherLines, segmentPairs.at(i).second));
  18237. }
  18238. }
  18239. }
  18240. /*! \internal
  18241. Draws scatter symbols at every point passed in \a scatters, given in pixel coordinates. The
  18242. scatters will be drawn with \a painter and have the appearance as specified in \a style.
  18243. \see drawLinePlot, drawImpulsePlot
  18244. */
  18245. void QCPGraph::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &scatters, const QCPScatterStyle &style) const
  18246. {
  18247. applyScattersAntialiasingHint(painter);
  18248. style.applyTo(painter, mPen);
  18249. foreach (const QPointF &scatter, scatters)
  18250. style.drawShape(painter, scatter.x(), scatter.y());
  18251. }
  18252. /*! \internal
  18253. Draws lines between the points in \a lines, given in pixel coordinates.
  18254. \see drawScatterPlot, drawImpulsePlot, QCPAbstractPlottable1D::drawPolyline
  18255. */
  18256. void QCPGraph::drawLinePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
  18257. {
  18258. if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
  18259. {
  18260. applyDefaultAntialiasingHint(painter);
  18261. drawPolyline(painter, lines);
  18262. }
  18263. }
  18264. /*! \internal
  18265. Draws impulses from the provided data, i.e. it connects all line pairs in \a lines, given in
  18266. pixel coordinates. The \a lines necessary for impulses are generated by \ref dataToImpulseLines
  18267. from the regular graph data points.
  18268. \see drawLinePlot, drawScatterPlot
  18269. */
  18270. void QCPGraph::drawImpulsePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
  18271. {
  18272. if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
  18273. {
  18274. applyDefaultAntialiasingHint(painter);
  18275. QPen oldPen = painter->pen();
  18276. QPen newPen = painter->pen();
  18277. newPen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line
  18278. painter->setPen(newPen);
  18279. painter->drawLines(lines);
  18280. painter->setPen(oldPen);
  18281. }
  18282. }
  18283. /*! \internal
  18284. Returns via \a lineData the data points that need to be visualized for this graph when plotting
  18285. graph lines, taking into consideration the currently visible axis ranges and, if \ref
  18286. setAdaptiveSampling is enabled, local point densities. The considered data can be restricted
  18287. further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref
  18288. getDataSegments).
  18289. This method is used by \ref getLines to retrieve the basic working set of data.
  18290. \see getOptimizedScatterData
  18291. */
  18292. void QCPGraph::getOptimizedLineData(QVector<QCPGraphData> *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const
  18293. {
  18294. if (!lineData) return;
  18295. QCPAxis *keyAxis = mKeyAxis.data();
  18296. QCPAxis *valueAxis = mValueAxis.data();
  18297. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  18298. if (begin == end) return;
  18299. int dataCount = int(end-begin);
  18300. int maxCount = (std::numeric_limits<int>::max)();
  18301. if (mAdaptiveSampling)
  18302. {
  18303. double keyPixelSpan = qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key));
  18304. if (2*keyPixelSpan+2 < static_cast<double>((std::numeric_limits<int>::max)()))
  18305. maxCount = int(2*keyPixelSpan+2);
  18306. }
  18307. if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
  18308. {
  18309. QCPGraphDataContainer::const_iterator it = begin;
  18310. double minValue = it->value;
  18311. double maxValue = it->value;
  18312. QCPGraphDataContainer::const_iterator currentIntervalFirstPoint = it;
  18313. int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction
  18314. int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
  18315. double currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(begin->key)+reversedRound));
  18316. double lastIntervalEndKey = currentIntervalStartKey;
  18317. double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
  18318. bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
  18319. int intervalDataCount = 1;
  18320. ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect
  18321. while (it != end)
  18322. {
  18323. if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary
  18324. {
  18325. if (it->value < minValue)
  18326. minValue = it->value;
  18327. else if (it->value > maxValue)
  18328. maxValue = it->value;
  18329. ++intervalDataCount;
  18330. } else // new pixel interval started
  18331. {
  18332. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
  18333. {
  18334. if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point
  18335. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value));
  18336. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
  18337. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
  18338. 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
  18339. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.8, (it-1)->value));
  18340. } else
  18341. lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value));
  18342. lastIntervalEndKey = (it-1)->key;
  18343. minValue = it->value;
  18344. maxValue = it->value;
  18345. currentIntervalFirstPoint = it;
  18346. currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(it->key)+reversedRound));
  18347. if (keyEpsilonVariable)
  18348. keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
  18349. intervalDataCount = 1;
  18350. }
  18351. ++it;
  18352. }
  18353. // handle last interval:
  18354. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
  18355. {
  18356. if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point
  18357. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value));
  18358. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
  18359. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
  18360. } else
  18361. lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value));
  18362. } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output
  18363. {
  18364. lineData->resize(dataCount);
  18365. std::copy(begin, end, lineData->begin());
  18366. }
  18367. }
  18368. /*! \internal
  18369. Returns via \a scatterData the data points that need to be visualized for this graph when
  18370. plotting scatter points, taking into consideration the currently visible axis ranges and, if \ref
  18371. setAdaptiveSampling is enabled, local point densities. The considered data can be restricted
  18372. further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref
  18373. getDataSegments).
  18374. This method is used by \ref getScatters to retrieve the basic working set of data.
  18375. \see getOptimizedLineData
  18376. */
  18377. void QCPGraph::getOptimizedScatterData(QVector<QCPGraphData> *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const
  18378. {
  18379. if (!scatterData) return;
  18380. QCPAxis *keyAxis = mKeyAxis.data();
  18381. QCPAxis *valueAxis = mValueAxis.data();
  18382. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  18383. const int scatterModulo = mScatterSkip+1;
  18384. const bool doScatterSkip = mScatterSkip > 0;
  18385. int beginIndex = int(begin-mDataContainer->constBegin());
  18386. int endIndex = int(end-mDataContainer->constBegin());
  18387. while (doScatterSkip && begin != end && beginIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter
  18388. {
  18389. ++beginIndex;
  18390. ++begin;
  18391. }
  18392. if (begin == end) return;
  18393. int dataCount = int(end-begin);
  18394. int maxCount = (std::numeric_limits<int>::max)();
  18395. if (mAdaptiveSampling)
  18396. {
  18397. int keyPixelSpan = int(qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key)));
  18398. maxCount = 2*keyPixelSpan+2;
  18399. }
  18400. if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
  18401. {
  18402. double valueMaxRange = valueAxis->range().upper;
  18403. double valueMinRange = valueAxis->range().lower;
  18404. QCPGraphDataContainer::const_iterator it = begin;
  18405. int itIndex = int(beginIndex);
  18406. double minValue = it->value;
  18407. double maxValue = it->value;
  18408. QCPGraphDataContainer::const_iterator minValueIt = it;
  18409. QCPGraphDataContainer::const_iterator maxValueIt = it;
  18410. QCPGraphDataContainer::const_iterator currentIntervalStart = it;
  18411. int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction
  18412. int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
  18413. double currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(begin->key)+reversedRound));
  18414. double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
  18415. bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
  18416. int intervalDataCount = 1;
  18417. // advance iterator to second (non-skipped) data point because adaptive sampling works in 1 point retrospect:
  18418. if (!doScatterSkip)
  18419. ++it;
  18420. else
  18421. {
  18422. itIndex += scatterModulo;
  18423. if (itIndex < endIndex) // make sure we didn't jump over end
  18424. it += scatterModulo;
  18425. else
  18426. {
  18427. it = end;
  18428. itIndex = endIndex;
  18429. }
  18430. }
  18431. // main loop over data points:
  18432. while (it != end)
  18433. {
  18434. if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary
  18435. {
  18436. if (it->value < minValue && it->value > valueMinRange && it->value < valueMaxRange)
  18437. {
  18438. minValue = it->value;
  18439. minValueIt = it;
  18440. } else if (it->value > maxValue && it->value > valueMinRange && it->value < valueMaxRange)
  18441. {
  18442. maxValue = it->value;
  18443. maxValueIt = it;
  18444. }
  18445. ++intervalDataCount;
  18446. } else // new pixel started
  18447. {
  18448. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
  18449. {
  18450. // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
  18451. double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
  18452. int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
  18453. QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart;
  18454. int c = 0;
  18455. while (intervalIt != it)
  18456. {
  18457. if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange)
  18458. scatterData->append(*intervalIt);
  18459. ++c;
  18460. if (!doScatterSkip)
  18461. ++intervalIt;
  18462. else
  18463. intervalIt += scatterModulo; // since we know indices of "currentIntervalStart", "intervalIt" and "it" are multiples of scatterModulo, we can't accidentally jump over "it" here
  18464. }
  18465. } else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange)
  18466. scatterData->append(*currentIntervalStart);
  18467. minValue = it->value;
  18468. maxValue = it->value;
  18469. currentIntervalStart = it;
  18470. currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(it->key)+reversedRound));
  18471. if (keyEpsilonVariable)
  18472. keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
  18473. intervalDataCount = 1;
  18474. }
  18475. // advance to next data point:
  18476. if (!doScatterSkip)
  18477. ++it;
  18478. else
  18479. {
  18480. itIndex += scatterModulo;
  18481. if (itIndex < endIndex) // make sure we didn't jump over end
  18482. it += scatterModulo;
  18483. else
  18484. {
  18485. it = end;
  18486. itIndex = endIndex;
  18487. }
  18488. }
  18489. }
  18490. // handle last interval:
  18491. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
  18492. {
  18493. // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
  18494. double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
  18495. int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
  18496. QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart;
  18497. int intervalItIndex = int(intervalIt-mDataContainer->constBegin());
  18498. int c = 0;
  18499. while (intervalIt != it)
  18500. {
  18501. if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange)
  18502. scatterData->append(*intervalIt);
  18503. ++c;
  18504. if (!doScatterSkip)
  18505. ++intervalIt;
  18506. 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:
  18507. {
  18508. intervalItIndex += scatterModulo;
  18509. if (intervalItIndex < itIndex)
  18510. intervalIt += scatterModulo;
  18511. else
  18512. {
  18513. intervalIt = it;
  18514. intervalItIndex = itIndex;
  18515. }
  18516. }
  18517. }
  18518. } else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange)
  18519. scatterData->append(*currentIntervalStart);
  18520. } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output
  18521. {
  18522. QCPGraphDataContainer::const_iterator it = begin;
  18523. int itIndex = beginIndex;
  18524. scatterData->reserve(dataCount);
  18525. while (it != end)
  18526. {
  18527. scatterData->append(*it);
  18528. // advance to next data point:
  18529. if (!doScatterSkip)
  18530. ++it;
  18531. else
  18532. {
  18533. itIndex += scatterModulo;
  18534. if (itIndex < endIndex)
  18535. it += scatterModulo;
  18536. else
  18537. {
  18538. it = end;
  18539. itIndex = endIndex;
  18540. }
  18541. }
  18542. }
  18543. }
  18544. }
  18545. /*!
  18546. This method outputs the currently visible data range via \a begin and \a end. The returned range
  18547. will also never exceed \a rangeRestriction.
  18548. This method takes into account that the drawing of data lines at the axis rect border always
  18549. requires the points just outside the visible axis range. So \a begin and \a end may actually
  18550. indicate a range that contains one additional data point to the left and right of the visible
  18551. axis range.
  18552. */
  18553. void QCPGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
  18554. {
  18555. if (rangeRestriction.isEmpty())
  18556. {
  18557. end = mDataContainer->constEnd();
  18558. begin = end;
  18559. } else
  18560. {
  18561. QCPAxis *keyAxis = mKeyAxis.data();
  18562. QCPAxis *valueAxis = mValueAxis.data();
  18563. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  18564. // get visible data range:
  18565. begin = mDataContainer->findBegin(keyAxis->range().lower);
  18566. end = mDataContainer->findEnd(keyAxis->range().upper);
  18567. // limit lower/upperEnd to rangeRestriction:
  18568. mDataContainer->limitIteratorsToDataRange(begin, end, rangeRestriction); // this also ensures rangeRestriction outside data bounds doesn't break anything
  18569. }
  18570. }
  18571. /*! \internal
  18572. This method goes through the passed points in \a lineData and returns a list of the segments
  18573. which don't contain NaN data points.
  18574. \a keyOrientation defines whether the \a x or \a y member of the passed QPointF is used to check
  18575. for NaN. If \a keyOrientation is \c Qt::Horizontal, the \a y member is checked, if it is \c
  18576. Qt::Vertical, the \a x member is checked.
  18577. \see getOverlappingSegments, drawFill
  18578. */
  18579. QVector<QCPDataRange> QCPGraph::getNonNanSegments(const QVector<QPointF> *lineData, Qt::Orientation keyOrientation) const
  18580. {
  18581. QVector<QCPDataRange> result;
  18582. const int n = lineData->size();
  18583. QCPDataRange currentSegment(-1, -1);
  18584. int i = 0;
  18585. if (keyOrientation == Qt::Horizontal)
  18586. {
  18587. while (i < n)
  18588. {
  18589. while (i < n && qIsNaN(lineData->at(i).y())) // seek next non-NaN data point
  18590. ++i;
  18591. if (i == n)
  18592. break;
  18593. currentSegment.setBegin(i++);
  18594. while (i < n && !qIsNaN(lineData->at(i).y())) // seek next NaN data point or end of data
  18595. ++i;
  18596. currentSegment.setEnd(i++);
  18597. result.append(currentSegment);
  18598. }
  18599. } else // keyOrientation == Qt::Vertical
  18600. {
  18601. while (i < n)
  18602. {
  18603. while (i < n && qIsNaN(lineData->at(i).x())) // seek next non-NaN data point
  18604. ++i;
  18605. if (i == n)
  18606. break;
  18607. currentSegment.setBegin(i++);
  18608. while (i < n && !qIsNaN(lineData->at(i).x())) // seek next NaN data point or end of data
  18609. ++i;
  18610. currentSegment.setEnd(i++);
  18611. result.append(currentSegment);
  18612. }
  18613. }
  18614. return result;
  18615. }
  18616. /*! \internal
  18617. This method takes two segment lists (e.g. created by \ref getNonNanSegments) \a thisSegments and
  18618. \a otherSegments, and their associated point data \a thisData and \a otherData.
  18619. It returns all pairs of segments (the first from \a thisSegments, the second from \a
  18620. otherSegments), which overlap in plot coordinates.
  18621. This method is useful in the case of a channel fill between two graphs, when only those non-NaN
  18622. segments which actually overlap in their key coordinate shall be considered for drawing a channel
  18623. fill polygon.
  18624. It is assumed that the passed segments in \a thisSegments are ordered ascending by index, and
  18625. that the segments don't overlap themselves. The same is assumed for the segments in \a
  18626. otherSegments. This is fulfilled when the segments are obtained via \ref getNonNanSegments.
  18627. \see getNonNanSegments, segmentsIntersect, drawFill, getChannelFillPolygon
  18628. */
  18629. QVector<QPair<QCPDataRange, QCPDataRange> > QCPGraph::getOverlappingSegments(QVector<QCPDataRange> thisSegments, const QVector<QPointF> *thisData, QVector<QCPDataRange> otherSegments, const QVector<QPointF> *otherData) const
  18630. {
  18631. QVector<QPair<QCPDataRange, QCPDataRange> > result;
  18632. if (thisData->isEmpty() || otherData->isEmpty() || thisSegments.isEmpty() || otherSegments.isEmpty())
  18633. return result;
  18634. int thisIndex = 0;
  18635. int otherIndex = 0;
  18636. const bool verticalKey = mKeyAxis->orientation() == Qt::Vertical;
  18637. while (thisIndex < thisSegments.size() && otherIndex < otherSegments.size())
  18638. {
  18639. if (thisSegments.at(thisIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow
  18640. {
  18641. ++thisIndex;
  18642. continue;
  18643. }
  18644. if (otherSegments.at(otherIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow
  18645. {
  18646. ++otherIndex;
  18647. continue;
  18648. }
  18649. double thisLower, thisUpper, otherLower, otherUpper;
  18650. if (!verticalKey)
  18651. {
  18652. thisLower = thisData->at(thisSegments.at(thisIndex).begin()).x();
  18653. thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).x();
  18654. otherLower = otherData->at(otherSegments.at(otherIndex).begin()).x();
  18655. otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).x();
  18656. } else
  18657. {
  18658. thisLower = thisData->at(thisSegments.at(thisIndex).begin()).y();
  18659. thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).y();
  18660. otherLower = otherData->at(otherSegments.at(otherIndex).begin()).y();
  18661. otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).y();
  18662. }
  18663. int bPrecedence;
  18664. if (segmentsIntersect(thisLower, thisUpper, otherLower, otherUpper, bPrecedence))
  18665. result.append(QPair<QCPDataRange, QCPDataRange>(thisSegments.at(thisIndex), otherSegments.at(otherIndex)));
  18666. if (bPrecedence <= 0) // otherSegment doesn't reach as far as thisSegment, so continue with next otherSegment, keeping current thisSegment
  18667. ++otherIndex;
  18668. else // otherSegment reaches further than thisSegment, so continue with next thisSegment, keeping current otherSegment
  18669. ++thisIndex;
  18670. }
  18671. return result;
  18672. }
  18673. /*! \internal
  18674. Returns whether the segments defined by the coordinates (aLower, aUpper) and (bLower, bUpper)
  18675. have overlap.
  18676. The output parameter \a bPrecedence indicates whether the \a b segment reaches farther than the
  18677. \a a segment or not. If \a bPrecedence returns 1, segment \a b reaches the farthest to higher
  18678. coordinates (i.e. bUpper > aUpper). If it returns -1, segment \a a reaches the farthest. Only if
  18679. both segment's upper bounds are identical, 0 is returned as \a bPrecedence.
  18680. It is assumed that the lower bounds always have smaller or equal values than the upper bounds.
  18681. \see getOverlappingSegments
  18682. */
  18683. bool QCPGraph::segmentsIntersect(double aLower, double aUpper, double bLower, double bUpper, int &bPrecedence) const
  18684. {
  18685. bPrecedence = 0;
  18686. if (aLower > bUpper)
  18687. {
  18688. bPrecedence = -1;
  18689. return false;
  18690. } else if (bLower > aUpper)
  18691. {
  18692. bPrecedence = 1;
  18693. return false;
  18694. } else
  18695. {
  18696. if (aUpper > bUpper)
  18697. bPrecedence = -1;
  18698. else if (aUpper < bUpper)
  18699. bPrecedence = 1;
  18700. return true;
  18701. }
  18702. }
  18703. /*! \internal
  18704. Returns the point which closes the fill polygon on the zero-value-line parallel to the key axis.
  18705. The logarithmic axis scale case is a bit special, since the zero-value-line in pixel coordinates
  18706. is in positive or negative infinity. So this case is handled separately by just closing the fill
  18707. polygon on the axis which lies in the direction towards the zero value.
  18708. \a matchingDataPoint will provide the key (in pixels) of the returned point. Depending on whether
  18709. the key axis of this graph is horizontal or vertical, \a matchingDataPoint will provide the x or
  18710. y value of the returned point, respectively.
  18711. */
  18712. QPointF QCPGraph::getFillBasePoint(QPointF matchingDataPoint) const
  18713. {
  18714. QCPAxis *keyAxis = mKeyAxis.data();
  18715. QCPAxis *valueAxis = mValueAxis.data();
  18716. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
  18717. QPointF result;
  18718. if (valueAxis->scaleType() == QCPAxis::stLinear)
  18719. {
  18720. if (keyAxis->orientation() == Qt::Horizontal)
  18721. {
  18722. result.setX(matchingDataPoint.x());
  18723. result.setY(valueAxis->coordToPixel(0));
  18724. } else // keyAxis->orientation() == Qt::Vertical
  18725. {
  18726. result.setX(valueAxis->coordToPixel(0));
  18727. result.setY(matchingDataPoint.y());
  18728. }
  18729. } else // valueAxis->mScaleType == QCPAxis::stLogarithmic
  18730. {
  18731. // In logarithmic scaling we can't just draw to value 0 so we just fill all the way
  18732. // to the axis which is in the direction towards 0
  18733. if (keyAxis->orientation() == Qt::Vertical)
  18734. {
  18735. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
  18736. (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
  18737. result.setX(keyAxis->axisRect()->right());
  18738. else
  18739. result.setX(keyAxis->axisRect()->left());
  18740. result.setY(matchingDataPoint.y());
  18741. } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom)
  18742. {
  18743. result.setX(matchingDataPoint.x());
  18744. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
  18745. (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
  18746. result.setY(keyAxis->axisRect()->top());
  18747. else
  18748. result.setY(keyAxis->axisRect()->bottom());
  18749. }
  18750. }
  18751. return result;
  18752. }
  18753. /*! \internal
  18754. Returns the polygon needed for drawing normal fills between this graph and the key axis.
  18755. Pass the graph's data points (in pixel coordinates) as \a lineData, and specify the \a segment
  18756. which shall be used for the fill. The collection of \a lineData points described by \a segment
  18757. must not contain NaN data points (see \ref getNonNanSegments).
  18758. The returned fill polygon will be closed at the key axis (the zero-value line) for linear value
  18759. axes. For logarithmic value axes the polygon will reach just beyond the corresponding axis rect
  18760. side (see \ref getFillBasePoint).
  18761. For increased performance (due to implicit sharing), keep the returned QPolygonF const.
  18762. \see drawFill, getNonNanSegments
  18763. */
  18764. const QPolygonF QCPGraph::getFillPolygon(const QVector<QPointF> *lineData, QCPDataRange segment) const
  18765. {
  18766. if (segment.size() < 2)
  18767. return QPolygonF();
  18768. QPolygonF result(segment.size()+2);
  18769. result[0] = getFillBasePoint(lineData->at(segment.begin()));
  18770. std::copy(lineData->constBegin()+segment.begin(), lineData->constBegin()+segment.end(), result.begin()+1);
  18771. result[result.size()-1] = getFillBasePoint(lineData->at(segment.end()-1));
  18772. return result;
  18773. }
  18774. /*! \internal
  18775. Returns the polygon needed for drawing (partial) channel fills between this graph and the graph
  18776. specified by \ref setChannelFillGraph.
  18777. The data points of this graph are passed as pixel coordinates via \a thisData, the data of the
  18778. other graph as \a otherData. The returned polygon will be calculated for the specified data
  18779. segments \a thisSegment and \a otherSegment, pertaining to the respective \a thisData and \a
  18780. otherData, respectively.
  18781. The passed \a thisSegment and \a otherSegment should correspond to the segment pairs returned by
  18782. \ref getOverlappingSegments, to make sure only segments that actually have key coordinate overlap
  18783. need to be processed here.
  18784. For increased performance due to implicit sharing, keep the returned QPolygonF const.
  18785. \see drawFill, getOverlappingSegments, getNonNanSegments
  18786. */
  18787. const QPolygonF QCPGraph::getChannelFillPolygon(const QVector<QPointF> *thisData, QCPDataRange thisSegment, const QVector<QPointF> *otherData, QCPDataRange otherSegment) const
  18788. {
  18789. if (!mChannelFillGraph)
  18790. return QPolygonF();
  18791. QCPAxis *keyAxis = mKeyAxis.data();
  18792. QCPAxis *valueAxis = mValueAxis.data();
  18793. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); }
  18794. if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); }
  18795. if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation())
  18796. 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)
  18797. if (thisData->isEmpty()) return QPolygonF();
  18798. QVector<QPointF> thisSegmentData(thisSegment.size());
  18799. QVector<QPointF> otherSegmentData(otherSegment.size());
  18800. std::copy(thisData->constBegin()+thisSegment.begin(), thisData->constBegin()+thisSegment.end(), thisSegmentData.begin());
  18801. std::copy(otherData->constBegin()+otherSegment.begin(), otherData->constBegin()+otherSegment.end(), otherSegmentData.begin());
  18802. // pointers to be able to swap them, depending which data range needs cropping:
  18803. QVector<QPointF> *staticData = &thisSegmentData;
  18804. QVector<QPointF> *croppedData = &otherSegmentData;
  18805. // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType):
  18806. if (keyAxis->orientation() == Qt::Horizontal)
  18807. {
  18808. // x is key
  18809. // crop lower bound:
  18810. if (staticData->first().x() < croppedData->first().x()) // other one must be cropped
  18811. qSwap(staticData, croppedData);
  18812. const int lowBound = findIndexBelowX(croppedData, staticData->first().x());
  18813. if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
  18814. croppedData->remove(0, lowBound);
  18815. // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation:
  18816. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18817. double slope;
  18818. if (!qFuzzyCompare(croppedData->at(1).x(), croppedData->at(0).x()))
  18819. slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x());
  18820. else
  18821. slope = 0;
  18822. (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x()));
  18823. (*croppedData)[0].setX(staticData->first().x());
  18824. // crop upper bound:
  18825. if (staticData->last().x() > croppedData->last().x()) // other one must be cropped
  18826. qSwap(staticData, croppedData);
  18827. int highBound = findIndexAboveX(croppedData, staticData->last().x());
  18828. if (highBound == -1) return QPolygonF(); // key ranges have no overlap
  18829. croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
  18830. // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation:
  18831. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18832. const int li = croppedData->size()-1; // last index
  18833. if (!qFuzzyCompare(croppedData->at(li).x(), croppedData->at(li-1).x()))
  18834. slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x());
  18835. else
  18836. slope = 0;
  18837. (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x()));
  18838. (*croppedData)[li].setX(staticData->last().x());
  18839. } else // mKeyAxis->orientation() == Qt::Vertical
  18840. {
  18841. // y is key
  18842. // crop lower bound:
  18843. if (staticData->first().y() < croppedData->first().y()) // other one must be cropped
  18844. qSwap(staticData, croppedData);
  18845. int lowBound = findIndexBelowY(croppedData, staticData->first().y());
  18846. if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
  18847. croppedData->remove(0, lowBound);
  18848. // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation:
  18849. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18850. double slope;
  18851. if (!qFuzzyCompare(croppedData->at(1).y(), croppedData->at(0).y())) // avoid division by zero in step plots
  18852. slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y());
  18853. else
  18854. slope = 0;
  18855. (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y()));
  18856. (*croppedData)[0].setY(staticData->first().y());
  18857. // crop upper bound:
  18858. if (staticData->last().y() > croppedData->last().y()) // other one must be cropped
  18859. qSwap(staticData, croppedData);
  18860. int highBound = findIndexAboveY(croppedData, staticData->last().y());
  18861. if (highBound == -1) return QPolygonF(); // key ranges have no overlap
  18862. croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
  18863. // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation:
  18864. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18865. int li = croppedData->size()-1; // last index
  18866. if (!qFuzzyCompare(croppedData->at(li).y(), croppedData->at(li-1).y())) // avoid division by zero in step plots
  18867. slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y());
  18868. else
  18869. slope = 0;
  18870. (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y()));
  18871. (*croppedData)[li].setY(staticData->last().y());
  18872. }
  18873. // return joined:
  18874. for (int i=otherSegmentData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted
  18875. thisSegmentData << otherSegmentData.at(i);
  18876. return QPolygonF(thisSegmentData);
  18877. }
  18878. /*! \internal
  18879. Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in
  18880. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  18881. axis is horizontal.
  18882. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  18883. */
  18884. int QCPGraph::findIndexAboveX(const QVector<QPointF> *data, double x) const
  18885. {
  18886. for (int i=data->size()-1; i>=0; --i)
  18887. {
  18888. if (data->at(i).x() < x)
  18889. {
  18890. if (i<data->size()-1)
  18891. return i+1;
  18892. else
  18893. return data->size()-1;
  18894. }
  18895. }
  18896. return -1;
  18897. }
  18898. /*! \internal
  18899. Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in
  18900. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  18901. axis is horizontal.
  18902. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  18903. */
  18904. int QCPGraph::findIndexBelowX(const QVector<QPointF> *data, double x) const
  18905. {
  18906. for (int i=0; i<data->size(); ++i)
  18907. {
  18908. if (data->at(i).x() > x)
  18909. {
  18910. if (i>0)
  18911. return i-1;
  18912. else
  18913. return 0;
  18914. }
  18915. }
  18916. return -1;
  18917. }
  18918. /*! \internal
  18919. Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in
  18920. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  18921. axis is vertical.
  18922. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  18923. */
  18924. int QCPGraph::findIndexAboveY(const QVector<QPointF> *data, double y) const
  18925. {
  18926. for (int i=data->size()-1; i>=0; --i)
  18927. {
  18928. if (data->at(i).y() < y)
  18929. {
  18930. if (i<data->size()-1)
  18931. return i+1;
  18932. else
  18933. return data->size()-1;
  18934. }
  18935. }
  18936. return -1;
  18937. }
  18938. /*! \internal
  18939. Calculates the minimum distance in pixels the graph's representation has from the given \a
  18940. pixelPoint. This is used to determine whether the graph was clicked or not, e.g. in \ref
  18941. selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that if
  18942. the graph has a line representation, the returned distance may be smaller than the distance to
  18943. the \a closestData point, since the distance to the graph line is also taken into account.
  18944. If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape
  18945. is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns -1.0.
  18946. */
  18947. double QCPGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const
  18948. {
  18949. closestData = mDataContainer->constEnd();
  18950. if (mDataContainer->isEmpty())
  18951. return -1.0;
  18952. if (mLineStyle == lsNone && mScatterStyle.isNone())
  18953. return -1.0;
  18954. // calculate minimum distances to graph data points and find closestData iterator:
  18955. double minDistSqr = (std::numeric_limits<double>::max)();
  18956. // determine which key range comes into question, taking selection tolerance around pos into account:
  18957. double posKeyMin, posKeyMax, dummy;
  18958. pixelsToCoords(pixelPoint-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy);
  18959. pixelsToCoords(pixelPoint+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy);
  18960. if (posKeyMin > posKeyMax)
  18961. qSwap(posKeyMin, posKeyMax);
  18962. // iterate over found data points and then choose the one with the shortest distance to pos:
  18963. QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true);
  18964. QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true);
  18965. for (QCPGraphDataContainer::const_iterator it=begin; it!=end; ++it)
  18966. {
  18967. const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
  18968. if (currentDistSqr < minDistSqr)
  18969. {
  18970. minDistSqr = currentDistSqr;
  18971. closestData = it;
  18972. }
  18973. }
  18974. // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point):
  18975. if (mLineStyle != lsNone)
  18976. {
  18977. // line displayed, calculate distance to line segments:
  18978. QVector<QPointF> lineData;
  18979. 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
  18980. QCPVector2D p(pixelPoint);
  18981. const int step = mLineStyle==lsImpulse ? 2 : 1; // impulse plot differs from other line styles in that the lineData points are only pairwise connected
  18982. for (int i=0; i<lineData.size()-1; i+=step)
  18983. {
  18984. const double currentDistSqr = p.distanceSquaredToLine(lineData.at(i), lineData.at(i+1));
  18985. if (currentDistSqr < minDistSqr)
  18986. minDistSqr = currentDistSqr;
  18987. }
  18988. }
  18989. return qSqrt(minDistSqr);
  18990. }
  18991. /*! \internal
  18992. Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in
  18993. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  18994. axis is vertical.
  18995. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  18996. */
  18997. int QCPGraph::findIndexBelowY(const QVector<QPointF> *data, double y) const
  18998. {
  18999. for (int i=0; i<data->size(); ++i)
  19000. {
  19001. if (data->at(i).y() > y)
  19002. {
  19003. if (i>0)
  19004. return i-1;
  19005. else
  19006. return 0;
  19007. }
  19008. }
  19009. return -1;
  19010. }
  19011. /* end of 'src/plottables/plottable-graph.cpp' */
  19012. /* including file 'src/plottables/plottable-curve.cpp' */
  19013. /* modified 2021-03-29T02:30:44, size 63851 */
  19014. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19015. //////////////////// QCPCurveData
  19016. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19017. /*! \class QCPCurveData
  19018. \brief Holds the data of one single data point for QCPCurve.
  19019. The stored data is:
  19020. \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)
  19021. \li \a key: coordinate on the key axis of this curve point (this is the \a mainKey)
  19022. \li \a value: coordinate on the value axis of this curve point (this is the \a mainValue)
  19023. The container for storing multiple data points is \ref QCPCurveDataContainer. It is a typedef for
  19024. \ref QCPDataContainer with \ref QCPCurveData as the DataType template parameter. See the
  19025. documentation there for an explanation regarding the data type's generic methods.
  19026. \see QCPCurveDataContainer
  19027. */
  19028. /* start documentation of inline functions */
  19029. /*! \fn double QCPCurveData::sortKey() const
  19030. Returns the \a t member of this data point.
  19031. For a general explanation of what this method is good for in the context of the data container,
  19032. see the documentation of \ref QCPDataContainer.
  19033. */
  19034. /*! \fn static QCPCurveData QCPCurveData::fromSortKey(double sortKey)
  19035. Returns a data point with the specified \a sortKey (assigned to the data point's \a t member).
  19036. All other members are set to zero.
  19037. For a general explanation of what this method is good for in the context of the data container,
  19038. see the documentation of \ref QCPDataContainer.
  19039. */
  19040. /*! \fn static static bool QCPCurveData::sortKeyIsMainKey()
  19041. Since the member \a key is the data point key coordinate and the member \a t is the data ordering
  19042. parameter, this method returns false.
  19043. For a general explanation of what this method is good for in the context of the data container,
  19044. see the documentation of \ref QCPDataContainer.
  19045. */
  19046. /*! \fn double QCPCurveData::mainKey() const
  19047. Returns the \a key member of this data point.
  19048. For a general explanation of what this method is good for in the context of the data container,
  19049. see the documentation of \ref QCPDataContainer.
  19050. */
  19051. /*! \fn double QCPCurveData::mainValue() const
  19052. Returns the \a value member of this data point.
  19053. For a general explanation of what this method is good for in the context of the data container,
  19054. see the documentation of \ref QCPDataContainer.
  19055. */
  19056. /*! \fn QCPRange QCPCurveData::valueRange() const
  19057. Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
  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. /* end documentation of inline functions */
  19062. /*!
  19063. Constructs a curve data point with t, key and value set to zero.
  19064. */
  19065. QCPCurveData::QCPCurveData() :
  19066. t(0),
  19067. key(0),
  19068. value(0)
  19069. {
  19070. }
  19071. /*!
  19072. Constructs a curve data point with the specified \a t, \a key and \a value.
  19073. */
  19074. QCPCurveData::QCPCurveData(double t, double key, double value) :
  19075. t(t),
  19076. key(key),
  19077. value(value)
  19078. {
  19079. }
  19080. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19081. //////////////////// QCPCurve
  19082. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19083. /*! \class QCPCurve
  19084. \brief A plottable representing a parametric curve in a plot.
  19085. \image html QCPCurve.png
  19086. Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate,
  19087. so their visual representation can have \a loops. This is realized by introducing a third
  19088. coordinate \a t, which defines the order of the points described by the other two coordinates \a
  19089. x and \a y.
  19090. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
  19091. also access and modify the curve's data via the \ref data method, which returns a pointer to the
  19092. internal \ref QCPCurveDataContainer.
  19093. Gaps in the curve can be created by adding data points with NaN as key and value
  19094. (<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
  19095. separated.
  19096. \section qcpcurve-appearance Changing the appearance
  19097. The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush).
  19098. \section qcpcurve-usage Usage
  19099. Like all data representing objects in QCustomPlot, the QCPCurve is a plottable
  19100. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  19101. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  19102. Usually, you first create an instance:
  19103. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-1
  19104. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  19105. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  19106. The newly created plottable can be modified, e.g.:
  19107. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-2
  19108. */
  19109. /* start of documentation of inline functions */
  19110. /*! \fn QSharedPointer<QCPCurveDataContainer> QCPCurve::data() const
  19111. Returns a shared pointer to the internal data storage of type \ref QCPCurveDataContainer. You may
  19112. use it to directly manipulate the data, which may be more convenient and faster than using the
  19113. regular \ref setData or \ref addData methods.
  19114. */
  19115. /* end of documentation of inline functions */
  19116. /*!
  19117. Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  19118. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  19119. the same orientation. If either of these restrictions is violated, a corresponding message is
  19120. printed to the debug output (qDebug), the construction is not aborted, though.
  19121. The created QCPCurve is automatically registered with the QCustomPlot instance inferred from \a
  19122. keyAxis. This QCustomPlot instance takes ownership of the QCPCurve, so do not delete it manually
  19123. but use QCustomPlot::removePlottable() instead.
  19124. */
  19125. QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  19126. QCPAbstractPlottable1D<QCPCurveData>(keyAxis, valueAxis),
  19127. mScatterSkip{},
  19128. mLineStyle{}
  19129. {
  19130. // modify inherited properties from abstract plottable:
  19131. setPen(QPen(Qt::blue, 0));
  19132. setBrush(Qt::NoBrush);
  19133. setScatterStyle(QCPScatterStyle());
  19134. setLineStyle(lsLine);
  19135. setScatterSkip(0);
  19136. }
  19137. QCPCurve::~QCPCurve()
  19138. {
  19139. }
  19140. /*! \overload
  19141. Replaces the current data container with the provided \a data container.
  19142. Since a QSharedPointer is used, multiple QCPCurves may share the same data container safely.
  19143. Modifying the data in the container will then affect all curves that share the container. Sharing
  19144. can be achieved by simply exchanging the data containers wrapped in shared pointers:
  19145. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-1
  19146. If you do not wish to share containers, but create a copy from an existing container, rather use
  19147. the \ref QCPDataContainer<DataType>::set method on the curve's data container directly:
  19148. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-2
  19149. \see addData
  19150. */
  19151. void QCPCurve::setData(QSharedPointer<QCPCurveDataContainer> data)
  19152. {
  19153. mDataContainer = data;
  19154. }
  19155. /*! \overload
  19156. Replaces the current data with the provided points in \a t, \a keys and \a values. The provided
  19157. vectors should have equal length. Else, the number of added points will be the size of the
  19158. smallest vector.
  19159. If you can guarantee that the passed data points are sorted by \a t in ascending order, you can
  19160. set \a alreadySorted to true, to improve performance by saving a sorting run.
  19161. \see addData
  19162. */
  19163. void QCPCurve::setData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  19164. {
  19165. mDataContainer->clear();
  19166. addData(t, keys, values, alreadySorted);
  19167. }
  19168. /*! \overload
  19169. Replaces the current data with the provided points in \a keys and \a values. The provided vectors
  19170. should have equal length. Else, the number of added points will be the size of the smallest
  19171. vector.
  19172. The t parameter of each data point will be set to the integer index of the respective key/value
  19173. pair.
  19174. \see addData
  19175. */
  19176. void QCPCurve::setData(const QVector<double> &keys, const QVector<double> &values)
  19177. {
  19178. mDataContainer->clear();
  19179. addData(keys, values);
  19180. }
  19181. /*!
  19182. Sets the visual appearance of single data points in the plot. If set to \ref
  19183. QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate
  19184. line style).
  19185. \see QCPScatterStyle, setLineStyle
  19186. */
  19187. void QCPCurve::setScatterStyle(const QCPScatterStyle &style)
  19188. {
  19189. mScatterStyle = style;
  19190. }
  19191. /*!
  19192. If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of
  19193. scatter points are skipped/not drawn after every drawn scatter point.
  19194. This can be used to make the data appear sparser while for example still having a smooth line,
  19195. and to improve performance for very high density plots.
  19196. If \a skip is set to 0 (default), all scatter points are drawn.
  19197. \see setScatterStyle
  19198. */
  19199. void QCPCurve::setScatterSkip(int skip)
  19200. {
  19201. mScatterSkip = qMax(0, skip);
  19202. }
  19203. /*!
  19204. Sets how the single data points are connected in the plot or how they are represented visually
  19205. apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref
  19206. setScatterStyle to the desired scatter style.
  19207. \see setScatterStyle
  19208. */
  19209. void QCPCurve::setLineStyle(QCPCurve::LineStyle style)
  19210. {
  19211. mLineStyle = style;
  19212. }
  19213. /*! \overload
  19214. Adds the provided points in \a t, \a keys and \a values to the current data. The provided vectors
  19215. should have equal length. Else, the number of added points will be the size of the smallest
  19216. vector.
  19217. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  19218. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  19219. Alternatively, you can also access and modify the data directly via the \ref data method, which
  19220. returns a pointer to the internal data container.
  19221. */
  19222. void QCPCurve::addData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  19223. {
  19224. if (t.size() != keys.size() || t.size() != values.size())
  19225. qDebug() << Q_FUNC_INFO << "ts, keys and values have different sizes:" << t.size() << keys.size() << values.size();
  19226. const int n = qMin(qMin(t.size(), keys.size()), values.size());
  19227. QVector<QCPCurveData> tempData(n);
  19228. QVector<QCPCurveData>::iterator it = tempData.begin();
  19229. const QVector<QCPCurveData>::iterator itEnd = tempData.end();
  19230. int i = 0;
  19231. while (it != itEnd)
  19232. {
  19233. it->t = t[i];
  19234. it->key = keys[i];
  19235. it->value = values[i];
  19236. ++it;
  19237. ++i;
  19238. }
  19239. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  19240. }
  19241. /*! \overload
  19242. Adds the provided points in \a keys and \a values to the current data. The provided vectors
  19243. should have equal length. Else, the number of added points will be the size of the smallest
  19244. vector.
  19245. The t parameter of each data point will be set to the integer index of the respective key/value
  19246. pair.
  19247. Alternatively, you can also access and modify the data directly via the \ref data method, which
  19248. returns a pointer to the internal data container.
  19249. */
  19250. void QCPCurve::addData(const QVector<double> &keys, const QVector<double> &values)
  19251. {
  19252. if (keys.size() != values.size())
  19253. qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
  19254. const int n = qMin(keys.size(), values.size());
  19255. double tStart;
  19256. if (!mDataContainer->isEmpty())
  19257. tStart = (mDataContainer->constEnd()-1)->t + 1.0;
  19258. else
  19259. tStart = 0;
  19260. QVector<QCPCurveData> tempData(n);
  19261. QVector<QCPCurveData>::iterator it = tempData.begin();
  19262. const QVector<QCPCurveData>::iterator itEnd = tempData.end();
  19263. int i = 0;
  19264. while (it != itEnd)
  19265. {
  19266. it->t = tStart + i;
  19267. it->key = keys[i];
  19268. it->value = values[i];
  19269. ++it;
  19270. ++i;
  19271. }
  19272. mDataContainer->add(tempData, true); // don't modify tempData beyond this to prevent copy on write
  19273. }
  19274. /*! \overload
  19275. Adds the provided data point as \a t, \a key and \a value to the current data.
  19276. Alternatively, you can also access and modify the data directly via the \ref data method, which
  19277. returns a pointer to the internal data container.
  19278. */
  19279. void QCPCurve::addData(double t, double key, double value)
  19280. {
  19281. mDataContainer->add(QCPCurveData(t, key, value));
  19282. }
  19283. /*! \overload
  19284. Adds the provided data point as \a key and \a value to the current data.
  19285. The t parameter is generated automatically by increments of 1 for each point, starting at the
  19286. highest t of previously existing data or 0, if the curve data is empty.
  19287. Alternatively, you can also access and modify the data directly via the \ref data method, which
  19288. returns a pointer to the internal data container.
  19289. */
  19290. void QCPCurve::addData(double key, double value)
  19291. {
  19292. if (!mDataContainer->isEmpty())
  19293. mDataContainer->add(QCPCurveData((mDataContainer->constEnd()-1)->t + 1.0, key, value));
  19294. else
  19295. mDataContainer->add(QCPCurveData(0.0, key, value));
  19296. }
  19297. /*!
  19298. Implements a selectTest specific to this plottable's point geometry.
  19299. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  19300. point to \a pos.
  19301. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  19302. */
  19303. double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  19304. {
  19305. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  19306. return -1;
  19307. if (!mKeyAxis || !mValueAxis)
  19308. return -1;
  19309. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  19310. {
  19311. QCPCurveDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  19312. double result = pointDistance(pos, closestDataPoint);
  19313. if (details)
  19314. {
  19315. int pointIndex = int( closestDataPoint-mDataContainer->constBegin() );
  19316. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  19317. }
  19318. return result;
  19319. } else
  19320. return -1;
  19321. }
  19322. /* inherits documentation from base class */
  19323. QCPRange QCPCurve::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  19324. {
  19325. return mDataContainer->keyRange(foundRange, inSignDomain);
  19326. }
  19327. /* inherits documentation from base class */
  19328. QCPRange QCPCurve::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  19329. {
  19330. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  19331. }
  19332. /* inherits documentation from base class */
  19333. void QCPCurve::draw(QCPPainter *painter)
  19334. {
  19335. if (mDataContainer->isEmpty()) return;
  19336. // allocate line vector:
  19337. QVector<QPointF> lines, scatters;
  19338. // loop over and draw segments of unselected/selected data:
  19339. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  19340. getDataSegments(selectedSegments, unselectedSegments);
  19341. allSegments << unselectedSegments << selectedSegments;
  19342. for (int i=0; i<allSegments.size(); ++i)
  19343. {
  19344. bool isSelectedSegment = i >= unselectedSegments.size();
  19345. // fill with curve data:
  19346. QPen finalCurvePen = mPen; // determine the final pen already here, because the line optimization depends on its stroke width
  19347. if (isSelectedSegment && mSelectionDecorator)
  19348. finalCurvePen = mSelectionDecorator->pen();
  19349. 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)
  19350. getCurveLines(&lines, lineDataRange, finalCurvePen.widthF());
  19351. // check data validity if flag set:
  19352. #ifdef QCUSTOMPLOT_CHECK_DATA
  19353. for (QCPCurveDataContainer::const_iterator it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  19354. {
  19355. if (QCP::isInvalidData(it->t) ||
  19356. QCP::isInvalidData(it->key, it->value))
  19357. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
  19358. }
  19359. #endif
  19360. // draw curve fill:
  19361. applyFillAntialiasingHint(painter);
  19362. if (isSelectedSegment && mSelectionDecorator)
  19363. mSelectionDecorator->applyBrush(painter);
  19364. else
  19365. painter->setBrush(mBrush);
  19366. painter->setPen(Qt::NoPen);
  19367. if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0)
  19368. painter->drawPolygon(QPolygonF(lines));
  19369. // draw curve line:
  19370. if (mLineStyle != lsNone)
  19371. {
  19372. painter->setPen(finalCurvePen);
  19373. painter->setBrush(Qt::NoBrush);
  19374. drawCurveLine(painter, lines);
  19375. }
  19376. // draw scatters:
  19377. QCPScatterStyle finalScatterStyle = mScatterStyle;
  19378. if (isSelectedSegment && mSelectionDecorator)
  19379. finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
  19380. if (!finalScatterStyle.isNone())
  19381. {
  19382. getScatters(&scatters, allSegments.at(i), finalScatterStyle.size());
  19383. drawScatterPlot(painter, scatters, finalScatterStyle);
  19384. }
  19385. }
  19386. // draw other selection decoration that isn't just line/scatter pens and brushes:
  19387. if (mSelectionDecorator)
  19388. mSelectionDecorator->drawDecoration(painter, selection());
  19389. }
  19390. /* inherits documentation from base class */
  19391. void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  19392. {
  19393. // draw fill:
  19394. if (mBrush.style() != Qt::NoBrush)
  19395. {
  19396. applyFillAntialiasingHint(painter);
  19397. painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
  19398. }
  19399. // draw line vertically centered:
  19400. if (mLineStyle != lsNone)
  19401. {
  19402. applyDefaultAntialiasingHint(painter);
  19403. painter->setPen(mPen);
  19404. 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
  19405. }
  19406. // draw scatter symbol:
  19407. if (!mScatterStyle.isNone())
  19408. {
  19409. applyScattersAntialiasingHint(painter);
  19410. // scale scatter pixmap if it's too large to fit in legend icon rect:
  19411. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
  19412. {
  19413. QCPScatterStyle scaledStyle(mScatterStyle);
  19414. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  19415. scaledStyle.applyTo(painter, mPen);
  19416. scaledStyle.drawShape(painter, QRectF(rect).center());
  19417. } else
  19418. {
  19419. mScatterStyle.applyTo(painter, mPen);
  19420. mScatterStyle.drawShape(painter, QRectF(rect).center());
  19421. }
  19422. }
  19423. }
  19424. /*! \internal
  19425. Draws lines between the points in \a lines, given in pixel coordinates.
  19426. \see drawScatterPlot, getCurveLines
  19427. */
  19428. void QCPCurve::drawCurveLine(QCPPainter *painter, const QVector<QPointF> &lines) const
  19429. {
  19430. if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
  19431. {
  19432. applyDefaultAntialiasingHint(painter);
  19433. drawPolyline(painter, lines);
  19434. }
  19435. }
  19436. /*! \internal
  19437. Draws scatter symbols at every point passed in \a points, given in pixel coordinates. The
  19438. scatters will be drawn with \a painter and have the appearance as specified in \a style.
  19439. \see drawCurveLine, getCurveLines
  19440. */
  19441. void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &points, const QCPScatterStyle &style) const
  19442. {
  19443. // draw scatter point symbols:
  19444. applyScattersAntialiasingHint(painter);
  19445. style.applyTo(painter, mPen);
  19446. foreach (const QPointF &point, points)
  19447. if (!qIsNaN(point.x()) && !qIsNaN(point.y()))
  19448. style.drawShape(painter, point);
  19449. }
  19450. /*! \internal
  19451. Called by \ref draw to generate points in pixel coordinates which represent the line of the
  19452. curve.
  19453. Line segments that aren't visible in the current axis rect are handled in an optimized way. They
  19454. are projected onto a rectangle slightly larger than the visible axis rect and simplified
  19455. regarding point count. The algorithm makes sure to preserve appearance of lines and fills inside
  19456. the visible axis rect by generating new temporary points on the outer rect if necessary.
  19457. \a lines will be filled with points in pixel coordinates, that can be drawn with \ref
  19458. drawCurveLine.
  19459. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  19460. conversion. In this function, the specified range may exceed the total data bounds without harm:
  19461. a correspondingly trimmed data range will be used. This takes the burden off the user of this
  19462. function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
  19463. getDataSegments.
  19464. \a penWidth specifies the pen width that will be used to later draw the lines generated by this
  19465. function. This is needed here to calculate an accordingly wider margin around the axis rect when
  19466. performing the line optimization.
  19467. Methods that are also involved in the algorithm are: \ref getRegion, \ref getOptimizedPoint, \ref
  19468. getOptimizedCornerPoints \ref mayTraverse, \ref getTraverse, \ref getTraverseCornerPoints.
  19469. \see drawCurveLine, drawScatterPlot
  19470. */
  19471. void QCPCurve::getCurveLines(QVector<QPointF> *lines, const QCPDataRange &dataRange, double penWidth) const
  19472. {
  19473. if (!lines) return;
  19474. lines->clear();
  19475. QCPAxis *keyAxis = mKeyAxis.data();
  19476. QCPAxis *valueAxis = mValueAxis.data();
  19477. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  19478. // add margins to rect to compensate for stroke width
  19479. const double strokeMargin = qMax(qreal(1.0), qreal(penWidth*0.75)); // stroke radius + 50% safety
  19480. const double keyMin = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().lower)-strokeMargin*keyAxis->pixelOrientation());
  19481. const double keyMax = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().upper)+strokeMargin*keyAxis->pixelOrientation());
  19482. const double valueMin = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().lower)-strokeMargin*valueAxis->pixelOrientation());
  19483. const double valueMax = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().upper)+strokeMargin*valueAxis->pixelOrientation());
  19484. QCPCurveDataContainer::const_iterator itBegin = mDataContainer->constBegin();
  19485. QCPCurveDataContainer::const_iterator itEnd = mDataContainer->constEnd();
  19486. mDataContainer->limitIteratorsToDataRange(itBegin, itEnd, dataRange);
  19487. if (itBegin == itEnd)
  19488. return;
  19489. QCPCurveDataContainer::const_iterator it = itBegin;
  19490. QCPCurveDataContainer::const_iterator prevIt = itEnd-1;
  19491. int prevRegion = getRegion(prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin);
  19492. 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)
  19493. while (it != itEnd)
  19494. {
  19495. const int currentRegion = getRegion(it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  19496. if (currentRegion != prevRegion) // changed region, possibly need to add some optimized edge points or original points if entering R
  19497. {
  19498. if (currentRegion != 5) // segment doesn't end in R, so it's a candidate for removal
  19499. {
  19500. QPointF crossA, crossB;
  19501. if (prevRegion == 5) // we're coming from R, so add this point optimized
  19502. {
  19503. lines->append(getOptimizedPoint(currentRegion, it->key, it->value, prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin));
  19504. // 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
  19505. *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  19506. } else if (mayTraverse(prevRegion, currentRegion) &&
  19507. getTraverse(prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin, crossA, crossB))
  19508. {
  19509. // add the two cross points optimized if segment crosses R and if segment isn't virtual zeroth segment between last and first curve point:
  19510. QVector<QPointF> beforeTraverseCornerPoints, afterTraverseCornerPoints;
  19511. getTraverseCornerPoints(prevRegion, currentRegion, keyMin, valueMax, keyMax, valueMin, beforeTraverseCornerPoints, afterTraverseCornerPoints);
  19512. if (it != itBegin)
  19513. {
  19514. *lines << beforeTraverseCornerPoints;
  19515. lines->append(crossA);
  19516. lines->append(crossB);
  19517. *lines << afterTraverseCornerPoints;
  19518. } else
  19519. {
  19520. lines->append(crossB);
  19521. *lines << afterTraverseCornerPoints;
  19522. trailingPoints << beforeTraverseCornerPoints << crossA ;
  19523. }
  19524. } 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)
  19525. {
  19526. *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  19527. }
  19528. } else // segment does end in R, so we add previous point optimized and this point at original position
  19529. {
  19530. 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
  19531. trailingPoints << getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  19532. else
  19533. lines->append(getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin));
  19534. lines->append(coordsToPixels(it->key, it->value));
  19535. }
  19536. } else // region didn't change
  19537. {
  19538. if (currentRegion == 5) // still in R, keep adding original points
  19539. {
  19540. lines->append(coordsToPixels(it->key, it->value));
  19541. } else // still outside R, no need to add anything
  19542. {
  19543. // see how this is not doing anything? That's the main optimization...
  19544. }
  19545. }
  19546. prevIt = it;
  19547. prevRegion = currentRegion;
  19548. ++it;
  19549. }
  19550. *lines << trailingPoints;
  19551. }
  19552. /*! \internal
  19553. Called by \ref draw to generate points in pixel coordinates which represent the scatters of the
  19554. curve. If a scatter skip is configured (\ref setScatterSkip), the returned points are accordingly
  19555. sparser.
  19556. Scatters that aren't visible in the current axis rect are optimized away.
  19557. \a scatters will be filled with points in pixel coordinates, that can be drawn with \ref
  19558. drawScatterPlot.
  19559. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  19560. conversion.
  19561. \a scatterWidth specifies the scatter width that will be used to later draw the scatters at pixel
  19562. coordinates generated by this function. This is needed here to calculate an accordingly wider
  19563. margin around the axis rect when performing the data point reduction.
  19564. \see draw, drawScatterPlot
  19565. */
  19566. void QCPCurve::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange, double scatterWidth) const
  19567. {
  19568. if (!scatters) return;
  19569. scatters->clear();
  19570. QCPAxis *keyAxis = mKeyAxis.data();
  19571. QCPAxis *valueAxis = mValueAxis.data();
  19572. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  19573. QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin();
  19574. QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd();
  19575. mDataContainer->limitIteratorsToDataRange(begin, end, dataRange);
  19576. if (begin == end)
  19577. return;
  19578. const int scatterModulo = mScatterSkip+1;
  19579. const bool doScatterSkip = mScatterSkip > 0;
  19580. int endIndex = int( end-mDataContainer->constBegin() );
  19581. QCPRange keyRange = keyAxis->range();
  19582. QCPRange valueRange = valueAxis->range();
  19583. // extend range to include width of scatter symbols:
  19584. keyRange.lower = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.lower)-scatterWidth*keyAxis->pixelOrientation());
  19585. keyRange.upper = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.upper)+scatterWidth*keyAxis->pixelOrientation());
  19586. valueRange.lower = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.lower)-scatterWidth*valueAxis->pixelOrientation());
  19587. valueRange.upper = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.upper)+scatterWidth*valueAxis->pixelOrientation());
  19588. QCPCurveDataContainer::const_iterator it = begin;
  19589. int itIndex = int( begin-mDataContainer->constBegin() );
  19590. while (doScatterSkip && it != end && itIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter
  19591. {
  19592. ++itIndex;
  19593. ++it;
  19594. }
  19595. if (keyAxis->orientation() == Qt::Vertical)
  19596. {
  19597. while (it != end)
  19598. {
  19599. if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value))
  19600. scatters->append(QPointF(valueAxis->coordToPixel(it->value), keyAxis->coordToPixel(it->key)));
  19601. // advance iterator to next (non-skipped) data point:
  19602. if (!doScatterSkip)
  19603. ++it;
  19604. else
  19605. {
  19606. itIndex += scatterModulo;
  19607. if (itIndex < endIndex) // make sure we didn't jump over end
  19608. it += scatterModulo;
  19609. else
  19610. {
  19611. it = end;
  19612. itIndex = endIndex;
  19613. }
  19614. }
  19615. }
  19616. } else
  19617. {
  19618. while (it != end)
  19619. {
  19620. if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value))
  19621. scatters->append(QPointF(keyAxis->coordToPixel(it->key), valueAxis->coordToPixel(it->value)));
  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. }
  19638. }
  19639. /*! \internal
  19640. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19641. It returns the region of the given point (\a key, \a value) with respect to a rectangle defined
  19642. by \a keyMin, \a keyMax, \a valueMin, and \a valueMax.
  19643. The regions are enumerated from top to bottom (\a valueMin to \a valueMax) and left to right (\a
  19644. keyMin to \a keyMax):
  19645. <table style="width:10em; text-align:center">
  19646. <tr><td>1</td><td>4</td><td>7</td></tr>
  19647. <tr><td>2</td><td style="border:1px solid black">5</td><td>8</td></tr>
  19648. <tr><td>3</td><td>6</td><td>9</td></tr>
  19649. </table>
  19650. With the rectangle being region 5, and the outer regions extending infinitely outwards. In the
  19651. curve optimization algorithm, region 5 is considered to be the visible portion of the plot.
  19652. */
  19653. int QCPCurve::getRegion(double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
  19654. {
  19655. if (key < keyMin) // region 123
  19656. {
  19657. if (value > valueMax)
  19658. return 1;
  19659. else if (value < valueMin)
  19660. return 3;
  19661. else
  19662. return 2;
  19663. } else if (key > keyMax) // region 789
  19664. {
  19665. if (value > valueMax)
  19666. return 7;
  19667. else if (value < valueMin)
  19668. return 9;
  19669. else
  19670. return 8;
  19671. } else // region 456
  19672. {
  19673. if (value > valueMax)
  19674. return 4;
  19675. else if (value < valueMin)
  19676. return 6;
  19677. else
  19678. return 5;
  19679. }
  19680. }
  19681. /*! \internal
  19682. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19683. This method is used in case the current segment passes from inside the visible rect (region 5,
  19684. see \ref getRegion) to any of the outer regions (\a otherRegion). The current segment is given by
  19685. the line connecting (\a key, \a value) with (\a otherKey, \a otherValue).
  19686. It returns the intersection point of the segment with the border of region 5.
  19687. For this function it doesn't matter whether (\a key, \a value) is the point inside region 5 or
  19688. whether it's (\a otherKey, \a otherValue), i.e. whether the segment is coming from region 5 or
  19689. leaving it. It is important though that \a otherRegion correctly identifies the other region not
  19690. equal to 5.
  19691. */
  19692. QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
  19693. {
  19694. // The intersection point interpolation here is done in pixel coordinates, so we don't need to
  19695. // differentiate between different axis scale types. Note that the nomenclature
  19696. // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be
  19697. // different in pixel coordinates (horz/vert key axes, reversed ranges)
  19698. const double keyMinPx = mKeyAxis->coordToPixel(keyMin);
  19699. const double keyMaxPx = mKeyAxis->coordToPixel(keyMax);
  19700. const double valueMinPx = mValueAxis->coordToPixel(valueMin);
  19701. const double valueMaxPx = mValueAxis->coordToPixel(valueMax);
  19702. const double otherValuePx = mValueAxis->coordToPixel(otherValue);
  19703. const double valuePx = mValueAxis->coordToPixel(value);
  19704. const double otherKeyPx = mKeyAxis->coordToPixel(otherKey);
  19705. const double keyPx = mKeyAxis->coordToPixel(key);
  19706. double intersectKeyPx = keyMinPx; // initial key just a fail-safe
  19707. double intersectValuePx = valueMinPx; // initial value just a fail-safe
  19708. switch (otherRegion)
  19709. {
  19710. case 1: // top and left edge
  19711. {
  19712. intersectValuePx = valueMaxPx;
  19713. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19714. 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)
  19715. {
  19716. intersectKeyPx = keyMinPx;
  19717. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19718. }
  19719. break;
  19720. }
  19721. case 2: // left edge
  19722. {
  19723. intersectKeyPx = keyMinPx;
  19724. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19725. break;
  19726. }
  19727. case 3: // bottom and left edge
  19728. {
  19729. intersectValuePx = valueMinPx;
  19730. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19731. 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)
  19732. {
  19733. intersectKeyPx = keyMinPx;
  19734. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19735. }
  19736. break;
  19737. }
  19738. case 4: // top edge
  19739. {
  19740. intersectValuePx = valueMaxPx;
  19741. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19742. break;
  19743. }
  19744. case 5:
  19745. {
  19746. break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table
  19747. }
  19748. case 6: // bottom edge
  19749. {
  19750. intersectValuePx = valueMinPx;
  19751. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19752. break;
  19753. }
  19754. case 7: // top and right edge
  19755. {
  19756. intersectValuePx = valueMaxPx;
  19757. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19758. 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)
  19759. {
  19760. intersectKeyPx = keyMaxPx;
  19761. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19762. }
  19763. break;
  19764. }
  19765. case 8: // right edge
  19766. {
  19767. intersectKeyPx = keyMaxPx;
  19768. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19769. break;
  19770. }
  19771. case 9: // bottom and right edge
  19772. {
  19773. intersectValuePx = valueMinPx;
  19774. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19775. 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)
  19776. {
  19777. intersectKeyPx = keyMaxPx;
  19778. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19779. }
  19780. break;
  19781. }
  19782. }
  19783. if (mKeyAxis->orientation() == Qt::Horizontal)
  19784. return {intersectKeyPx, intersectValuePx};
  19785. else
  19786. return {intersectValuePx, intersectKeyPx};
  19787. }
  19788. /*! \internal
  19789. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19790. In situations where a single segment skips over multiple regions it might become necessary to add
  19791. extra points at the corners of region 5 (see \ref getRegion) such that the optimized segment
  19792. doesn't unintentionally cut through the visible area of the axis rect and create plot artifacts.
  19793. This method provides these points that must be added, assuming the original segment doesn't
  19794. start, end, or traverse region 5. (Corner points where region 5 is traversed are calculated by
  19795. \ref getTraverseCornerPoints.)
  19796. For example, consider a segment which directly goes from region 4 to 2 but originally is far out
  19797. to the top left such that it doesn't cross region 5. Naively optimizing these points by
  19798. projecting them on the top and left borders of region 5 will create a segment that surely crosses
  19799. 5, creating a visual artifact in the plot. This method prevents this by providing extra points at
  19800. the top left corner, making the optimized curve correctly pass from region 4 to 1 to 2 without
  19801. traversing 5.
  19802. */
  19803. 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
  19804. {
  19805. QVector<QPointF> result;
  19806. switch (prevRegion)
  19807. {
  19808. case 1:
  19809. {
  19810. switch (currentRegion)
  19811. {
  19812. case 2: { result << coordsToPixels(keyMin, valueMax); break; }
  19813. case 4: { result << coordsToPixels(keyMin, valueMax); break; }
  19814. case 3: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); break; }
  19815. case 7: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); break; }
  19816. case 6: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19817. case 8: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19818. 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
  19819. if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R
  19820. { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); }
  19821. else
  19822. { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); }
  19823. break;
  19824. }
  19825. }
  19826. break;
  19827. }
  19828. case 2:
  19829. {
  19830. switch (currentRegion)
  19831. {
  19832. case 1: { result << coordsToPixels(keyMin, valueMax); break; }
  19833. case 3: { result << coordsToPixels(keyMin, valueMin); break; }
  19834. case 4: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19835. case 6: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19836. case 7: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; }
  19837. case 9: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; }
  19838. }
  19839. break;
  19840. }
  19841. case 3:
  19842. {
  19843. switch (currentRegion)
  19844. {
  19845. case 2: { result << coordsToPixels(keyMin, valueMin); break; }
  19846. case 6: { result << coordsToPixels(keyMin, valueMin); break; }
  19847. case 1: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); break; }
  19848. case 9: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); break; }
  19849. case 4: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19850. case 8: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19851. 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
  19852. if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R
  19853. { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); }
  19854. else
  19855. { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); }
  19856. break;
  19857. }
  19858. }
  19859. break;
  19860. }
  19861. case 4:
  19862. {
  19863. switch (currentRegion)
  19864. {
  19865. case 1: { result << coordsToPixels(keyMin, valueMax); break; }
  19866. case 7: { result << coordsToPixels(keyMax, valueMax); break; }
  19867. case 2: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19868. case 8: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19869. case 3: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; }
  19870. case 9: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; }
  19871. }
  19872. break;
  19873. }
  19874. case 5:
  19875. {
  19876. switch (currentRegion)
  19877. {
  19878. case 1: { result << coordsToPixels(keyMin, valueMax); break; }
  19879. case 7: { result << coordsToPixels(keyMax, valueMax); break; }
  19880. case 9: { result << coordsToPixels(keyMax, valueMin); break; }
  19881. case 3: { result << coordsToPixels(keyMin, valueMin); break; }
  19882. }
  19883. break;
  19884. }
  19885. case 6:
  19886. {
  19887. switch (currentRegion)
  19888. {
  19889. case 3: { result << coordsToPixels(keyMin, valueMin); break; }
  19890. case 9: { result << coordsToPixels(keyMax, valueMin); break; }
  19891. case 2: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19892. case 8: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19893. case 1: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; }
  19894. case 7: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; }
  19895. }
  19896. break;
  19897. }
  19898. case 7:
  19899. {
  19900. switch (currentRegion)
  19901. {
  19902. case 4: { result << coordsToPixels(keyMax, valueMax); break; }
  19903. case 8: { result << coordsToPixels(keyMax, valueMax); break; }
  19904. case 1: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); break; }
  19905. case 9: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); break; }
  19906. case 2: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19907. case 6: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19908. 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
  19909. if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R
  19910. { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); }
  19911. else
  19912. { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); }
  19913. break;
  19914. }
  19915. }
  19916. break;
  19917. }
  19918. case 8:
  19919. {
  19920. switch (currentRegion)
  19921. {
  19922. case 7: { result << coordsToPixels(keyMax, valueMax); break; }
  19923. case 9: { result << coordsToPixels(keyMax, valueMin); break; }
  19924. case 4: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19925. case 6: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19926. case 1: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; }
  19927. case 3: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; }
  19928. }
  19929. break;
  19930. }
  19931. case 9:
  19932. {
  19933. switch (currentRegion)
  19934. {
  19935. case 6: { result << coordsToPixels(keyMax, valueMin); break; }
  19936. case 8: { result << coordsToPixels(keyMax, valueMin); break; }
  19937. case 3: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); break; }
  19938. case 7: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); break; }
  19939. case 2: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19940. case 4: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19941. 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
  19942. if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R
  19943. { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); }
  19944. else
  19945. { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); }
  19946. break;
  19947. }
  19948. }
  19949. break;
  19950. }
  19951. }
  19952. return result;
  19953. }
  19954. /*! \internal
  19955. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19956. This method returns whether a segment going from \a prevRegion to \a currentRegion (see \ref
  19957. getRegion) may traverse the visible region 5. This function assumes that neither \a prevRegion
  19958. nor \a currentRegion is 5 itself.
  19959. If this method returns false, the segment for sure doesn't pass region 5. If it returns true, the
  19960. segment may or may not pass region 5 and a more fine-grained calculation must be used (\ref
  19961. getTraverse).
  19962. */
  19963. bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const
  19964. {
  19965. switch (prevRegion)
  19966. {
  19967. case 1:
  19968. {
  19969. switch (currentRegion)
  19970. {
  19971. case 4:
  19972. case 7:
  19973. case 2:
  19974. case 3: return false;
  19975. default: return true;
  19976. }
  19977. }
  19978. case 2:
  19979. {
  19980. switch (currentRegion)
  19981. {
  19982. case 1:
  19983. case 3: return false;
  19984. default: return true;
  19985. }
  19986. }
  19987. case 3:
  19988. {
  19989. switch (currentRegion)
  19990. {
  19991. case 1:
  19992. case 2:
  19993. case 6:
  19994. case 9: return false;
  19995. default: return true;
  19996. }
  19997. }
  19998. case 4:
  19999. {
  20000. switch (currentRegion)
  20001. {
  20002. case 1:
  20003. case 7: return false;
  20004. default: return true;
  20005. }
  20006. }
  20007. case 5: return false; // should never occur
  20008. case 6:
  20009. {
  20010. switch (currentRegion)
  20011. {
  20012. case 3:
  20013. case 9: return false;
  20014. default: return true;
  20015. }
  20016. }
  20017. case 7:
  20018. {
  20019. switch (currentRegion)
  20020. {
  20021. case 1:
  20022. case 4:
  20023. case 8:
  20024. case 9: return false;
  20025. default: return true;
  20026. }
  20027. }
  20028. case 8:
  20029. {
  20030. switch (currentRegion)
  20031. {
  20032. case 7:
  20033. case 9: return false;
  20034. default: return true;
  20035. }
  20036. }
  20037. case 9:
  20038. {
  20039. switch (currentRegion)
  20040. {
  20041. case 3:
  20042. case 6:
  20043. case 8:
  20044. case 7: return false;
  20045. default: return true;
  20046. }
  20047. }
  20048. default: return true;
  20049. }
  20050. }
  20051. /*! \internal
  20052. This function is part of the curve optimization algorithm of \ref getCurveLines.
  20053. This method assumes that the \ref mayTraverse test has returned true, so there is a chance the
  20054. segment defined by (\a prevKey, \a prevValue) and (\a key, \a value) goes through the visible
  20055. region 5.
  20056. The return value of this method indicates whether the segment actually traverses region 5 or not.
  20057. If the segment traverses 5, the output parameters \a crossA and \a crossB indicate the entry and
  20058. exit points of region 5. They will become the optimized points for that segment.
  20059. */
  20060. bool QCPCurve::getTraverse(double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin, QPointF &crossA, QPointF &crossB) const
  20061. {
  20062. // The intersection point interpolation here is done in pixel coordinates, so we don't need to
  20063. // differentiate between different axis scale types. Note that the nomenclature
  20064. // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be
  20065. // different in pixel coordinates (horz/vert key axes, reversed ranges)
  20066. QList<QPointF> intersections;
  20067. const double valueMinPx = mValueAxis->coordToPixel(valueMin);
  20068. const double valueMaxPx = mValueAxis->coordToPixel(valueMax);
  20069. const double keyMinPx = mKeyAxis->coordToPixel(keyMin);
  20070. const double keyMaxPx = mKeyAxis->coordToPixel(keyMax);
  20071. const double keyPx = mKeyAxis->coordToPixel(key);
  20072. const double valuePx = mValueAxis->coordToPixel(value);
  20073. const double prevKeyPx = mKeyAxis->coordToPixel(prevKey);
  20074. const double prevValuePx = mValueAxis->coordToPixel(prevValue);
  20075. if (qFuzzyIsNull(keyPx-prevKeyPx)) // line is parallel to value axis
  20076. {
  20077. // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here
  20078. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMinPx) : QPointF(valueMinPx, keyPx)); // direction will be taken care of at end of method
  20079. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMaxPx) : QPointF(valueMaxPx, keyPx));
  20080. } else if (qFuzzyIsNull(valuePx-prevValuePx)) // line is parallel to key axis
  20081. {
  20082. // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here
  20083. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, valuePx) : QPointF(valuePx, keyMinPx)); // direction will be taken care of at end of method
  20084. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, valuePx) : QPointF(valuePx, keyMaxPx));
  20085. } else // line is skewed
  20086. {
  20087. double gamma;
  20088. double keyPerValuePx = (keyPx-prevKeyPx)/(valuePx-prevValuePx);
  20089. // check top of rect:
  20090. gamma = prevKeyPx + (valueMaxPx-prevValuePx)*keyPerValuePx;
  20091. if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed
  20092. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMaxPx) : QPointF(valueMaxPx, gamma));
  20093. // check bottom of rect:
  20094. gamma = prevKeyPx + (valueMinPx-prevValuePx)*keyPerValuePx;
  20095. if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed
  20096. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMinPx) : QPointF(valueMinPx, gamma));
  20097. const double valuePerKeyPx = 1.0/keyPerValuePx;
  20098. // check left of rect:
  20099. gamma = prevValuePx + (keyMinPx-prevKeyPx)*valuePerKeyPx;
  20100. if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed
  20101. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, gamma) : QPointF(gamma, keyMinPx));
  20102. // check right of rect:
  20103. gamma = prevValuePx + (keyMaxPx-prevKeyPx)*valuePerKeyPx;
  20104. if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed
  20105. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, gamma) : QPointF(gamma, keyMaxPx));
  20106. }
  20107. // handle cases where found points isn't exactly 2:
  20108. if (intersections.size() > 2)
  20109. {
  20110. // line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between:
  20111. double distSqrMax = 0;
  20112. QPointF pv1, pv2;
  20113. for (int i=0; i<intersections.size()-1; ++i)
  20114. {
  20115. for (int k=i+1; k<intersections.size(); ++k)
  20116. {
  20117. QPointF distPoint = intersections.at(i)-intersections.at(k);
  20118. double distSqr = distPoint.x()*distPoint.x()+distPoint.y()+distPoint.y();
  20119. if (distSqr > distSqrMax)
  20120. {
  20121. pv1 = intersections.at(i);
  20122. pv2 = intersections.at(k);
  20123. distSqrMax = distSqr;
  20124. }
  20125. }
  20126. }
  20127. intersections = QList<QPointF>() << pv1 << pv2;
  20128. } else if (intersections.size() != 2)
  20129. {
  20130. // one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment
  20131. return false;
  20132. }
  20133. // possibly re-sort points so optimized point segment has same direction as original segment:
  20134. double xDelta = keyPx-prevKeyPx;
  20135. double yDelta = valuePx-prevValuePx;
  20136. if (mKeyAxis->orientation() != Qt::Horizontal)
  20137. qSwap(xDelta, yDelta);
  20138. 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
  20139. intersections.move(0, 1);
  20140. crossA = intersections.at(0);
  20141. crossB = intersections.at(1);
  20142. return true;
  20143. }
  20144. /*! \internal
  20145. This function is part of the curve optimization algorithm of \ref getCurveLines.
  20146. This method assumes that the \ref getTraverse test has returned true, so the segment definitely
  20147. traverses the visible region 5 when going from \a prevRegion to \a currentRegion.
  20148. In certain situations it is not sufficient to merely generate the entry and exit points of the
  20149. segment into/out of region 5, as \ref getTraverse provides. It may happen that a single segment, in
  20150. addition to traversing region 5, skips another region outside of region 5, which makes it
  20151. necessary to add an optimized corner point there (very similar to the job \ref
  20152. getOptimizedCornerPoints does for segments that are completely in outside regions and don't
  20153. traverse 5).
  20154. As an example, consider a segment going from region 1 to region 6, traversing the lower left
  20155. corner of region 5. In this configuration, the segment additionally crosses the border between
  20156. region 1 and 2 before entering region 5. This makes it necessary to add an additional point in
  20157. the top left corner, before adding the optimized traverse points. So in this case, the output
  20158. parameter \a beforeTraverse will contain the top left corner point, and \a afterTraverse will be
  20159. empty.
  20160. In some cases, such as when going from region 1 to 9, it may even be necessary to add additional
  20161. corner points before and after the traverse. Then both \a beforeTraverse and \a afterTraverse
  20162. return the respective corner points.
  20163. */
  20164. void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double keyMin, double valueMax, double keyMax, double valueMin, QVector<QPointF> &beforeTraverse, QVector<QPointF> &afterTraverse) const
  20165. {
  20166. switch (prevRegion)
  20167. {
  20168. case 1:
  20169. {
  20170. switch (currentRegion)
  20171. {
  20172. case 6: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; }
  20173. case 9: { beforeTraverse << coordsToPixels(keyMin, valueMax); afterTraverse << coordsToPixels(keyMax, valueMin); break; }
  20174. case 8: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; }
  20175. }
  20176. break;
  20177. }
  20178. case 2:
  20179. {
  20180. switch (currentRegion)
  20181. {
  20182. case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; }
  20183. case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; }
  20184. }
  20185. break;
  20186. }
  20187. case 3:
  20188. {
  20189. switch (currentRegion)
  20190. {
  20191. case 4: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; }
  20192. case 7: { beforeTraverse << coordsToPixels(keyMin, valueMin); afterTraverse << coordsToPixels(keyMax, valueMax); break; }
  20193. case 8: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; }
  20194. }
  20195. break;
  20196. }
  20197. case 4:
  20198. {
  20199. switch (currentRegion)
  20200. {
  20201. case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; }
  20202. case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; }
  20203. }
  20204. break;
  20205. }
  20206. case 5: { break; } // shouldn't happen because this method only handles full traverses
  20207. case 6:
  20208. {
  20209. switch (currentRegion)
  20210. {
  20211. case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; }
  20212. case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; }
  20213. }
  20214. break;
  20215. }
  20216. case 7:
  20217. {
  20218. switch (currentRegion)
  20219. {
  20220. case 2: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; }
  20221. case 3: { beforeTraverse << coordsToPixels(keyMax, valueMax); afterTraverse << coordsToPixels(keyMin, valueMin); break; }
  20222. case 6: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; }
  20223. }
  20224. break;
  20225. }
  20226. case 8:
  20227. {
  20228. switch (currentRegion)
  20229. {
  20230. case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; }
  20231. case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; }
  20232. }
  20233. break;
  20234. }
  20235. case 9:
  20236. {
  20237. switch (currentRegion)
  20238. {
  20239. case 2: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; }
  20240. case 1: { beforeTraverse << coordsToPixels(keyMax, valueMin); afterTraverse << coordsToPixels(keyMin, valueMax); break; }
  20241. case 4: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; }
  20242. }
  20243. break;
  20244. }
  20245. }
  20246. }
  20247. /*! \internal
  20248. Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a
  20249. pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in
  20250. \ref selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that
  20251. if the curve has a line representation, the returned distance may be smaller than the distance to
  20252. the \a closestData point, since the distance to the curve line is also taken into account.
  20253. If either the curve has no data or if the line style is \ref lsNone and the scatter style's shape
  20254. is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the curve), returns
  20255. -1.0.
  20256. */
  20257. double QCPCurve::pointDistance(const QPointF &pixelPoint, QCPCurveDataContainer::const_iterator &closestData) const
  20258. {
  20259. closestData = mDataContainer->constEnd();
  20260. if (mDataContainer->isEmpty())
  20261. return -1.0;
  20262. if (mLineStyle == lsNone && mScatterStyle.isNone())
  20263. return -1.0;
  20264. if (mDataContainer->size() == 1)
  20265. {
  20266. QPointF dataPoint = coordsToPixels(mDataContainer->constBegin()->key, mDataContainer->constBegin()->value);
  20267. closestData = mDataContainer->constBegin();
  20268. return QCPVector2D(dataPoint-pixelPoint).length();
  20269. }
  20270. // calculate minimum distances to curve data points and find closestData iterator:
  20271. double minDistSqr = (std::numeric_limits<double>::max)();
  20272. // iterate over found data points and then choose the one with the shortest distance to pos:
  20273. QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin();
  20274. QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd();
  20275. for (QCPCurveDataContainer::const_iterator it=begin; it!=end; ++it)
  20276. {
  20277. const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
  20278. if (currentDistSqr < minDistSqr)
  20279. {
  20280. minDistSqr = currentDistSqr;
  20281. closestData = it;
  20282. }
  20283. }
  20284. // calculate distance to line if there is one (if so, will probably be smaller than distance to closest data point):
  20285. if (mLineStyle != lsNone)
  20286. {
  20287. QVector<QPointF> lines;
  20288. 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
  20289. for (int i=0; i<lines.size()-1; ++i)
  20290. {
  20291. double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(lines.at(i), lines.at(i+1));
  20292. if (currentDistSqr < minDistSqr)
  20293. minDistSqr = currentDistSqr;
  20294. }
  20295. }
  20296. return qSqrt(minDistSqr);
  20297. }
  20298. /* end of 'src/plottables/plottable-curve.cpp' */
  20299. /* including file 'src/plottables/plottable-bars.cpp' */
  20300. /* modified 2021-03-29T02:30:44, size 43907 */
  20301. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20302. //////////////////// QCPBarsGroup
  20303. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20304. /*! \class QCPBarsGroup
  20305. \brief Groups multiple QCPBars together so they appear side by side
  20306. \image html QCPBarsGroup.png
  20307. When showing multiple QCPBars in one plot which have bars at identical keys, it may be desirable
  20308. to have them appearing next to each other at each key. This is what adding the respective QCPBars
  20309. plottables to a QCPBarsGroup achieves. (An alternative approach is to stack them on top of each
  20310. other, see \ref QCPBars::moveAbove.)
  20311. \section qcpbarsgroup-usage Usage
  20312. To add a QCPBars plottable to the group, create a new group and then add the respective bars
  20313. intances:
  20314. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbarsgroup-creation
  20315. Alternatively to appending to the group like shown above, you can also set the group on the
  20316. QCPBars plottable via \ref QCPBars::setBarsGroup.
  20317. The spacing between the bars can be configured via \ref setSpacingType and \ref setSpacing. The
  20318. bars in this group appear in the plot in the order they were appended. To insert a bars plottable
  20319. at a certain index position, or to reposition a bars plottable which is already in the group, use
  20320. \ref insert.
  20321. To remove specific bars from the group, use either \ref remove or call \ref
  20322. QCPBars::setBarsGroup "QCPBars::setBarsGroup(0)" on the respective bars plottable.
  20323. To clear the entire group, call \ref clear, or simply delete the group.
  20324. \section qcpbarsgroup-example Example
  20325. The image above is generated with the following code:
  20326. \snippet documentation/doc-image-generator/mainwindow.cpp qcpbarsgroup-example
  20327. */
  20328. /* start of documentation of inline functions */
  20329. /*! \fn QList<QCPBars*> QCPBarsGroup::bars() const
  20330. Returns all bars currently in this group.
  20331. \see bars(int index)
  20332. */
  20333. /*! \fn int QCPBarsGroup::size() const
  20334. Returns the number of QCPBars plottables that are part of this group.
  20335. */
  20336. /*! \fn bool QCPBarsGroup::isEmpty() const
  20337. Returns whether this bars group is empty.
  20338. \see size
  20339. */
  20340. /*! \fn bool QCPBarsGroup::contains(QCPBars *bars)
  20341. Returns whether the specified \a bars plottable is part of this group.
  20342. */
  20343. /* end of documentation of inline functions */
  20344. /*!
  20345. Constructs a new bars group for the specified QCustomPlot instance.
  20346. */
  20347. QCPBarsGroup::QCPBarsGroup(QCustomPlot *parentPlot) :
  20348. QObject(parentPlot),
  20349. mParentPlot(parentPlot),
  20350. mSpacingType(stAbsolute),
  20351. mSpacing(4)
  20352. {
  20353. }
  20354. QCPBarsGroup::~QCPBarsGroup()
  20355. {
  20356. clear();
  20357. }
  20358. /*!
  20359. Sets how the spacing between adjacent bars is interpreted. See \ref SpacingType.
  20360. The actual spacing can then be specified with \ref setSpacing.
  20361. \see setSpacing
  20362. */
  20363. void QCPBarsGroup::setSpacingType(SpacingType spacingType)
  20364. {
  20365. mSpacingType = spacingType;
  20366. }
  20367. /*!
  20368. Sets the spacing between adjacent bars. What the number passed as \a spacing actually means, is
  20369. defined by the current \ref SpacingType, which can be set with \ref setSpacingType.
  20370. \see setSpacingType
  20371. */
  20372. void QCPBarsGroup::setSpacing(double spacing)
  20373. {
  20374. mSpacing = spacing;
  20375. }
  20376. /*!
  20377. Returns the QCPBars instance with the specified \a index in this group. If no such QCPBars
  20378. exists, returns \c nullptr.
  20379. \see bars(), size
  20380. */
  20381. QCPBars *QCPBarsGroup::bars(int index) const
  20382. {
  20383. if (index >= 0 && index < mBars.size())
  20384. {
  20385. return mBars.at(index);
  20386. } else
  20387. {
  20388. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  20389. return nullptr;
  20390. }
  20391. }
  20392. /*!
  20393. Removes all QCPBars plottables from this group.
  20394. \see isEmpty
  20395. */
  20396. void QCPBarsGroup::clear()
  20397. {
  20398. const QList<QCPBars*> oldBars = mBars;
  20399. foreach (QCPBars *bars, oldBars)
  20400. bars->setBarsGroup(nullptr); // removes itself from mBars via removeBars
  20401. }
  20402. /*!
  20403. Adds the specified \a bars plottable to this group. Alternatively, you can also use \ref
  20404. QCPBars::setBarsGroup on the \a bars instance.
  20405. \see insert, remove
  20406. */
  20407. void QCPBarsGroup::append(QCPBars *bars)
  20408. {
  20409. if (!bars)
  20410. {
  20411. qDebug() << Q_FUNC_INFO << "bars is 0";
  20412. return;
  20413. }
  20414. if (!mBars.contains(bars))
  20415. bars->setBarsGroup(this);
  20416. else
  20417. qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast<quintptr>(bars);
  20418. }
  20419. /*!
  20420. Inserts the specified \a bars plottable into this group at the specified index position \a i.
  20421. This gives you full control over the ordering of the bars.
  20422. \a bars may already be part of this group. In that case, \a bars is just moved to the new index
  20423. position.
  20424. \see append, remove
  20425. */
  20426. void QCPBarsGroup::insert(int i, QCPBars *bars)
  20427. {
  20428. if (!bars)
  20429. {
  20430. qDebug() << Q_FUNC_INFO << "bars is 0";
  20431. return;
  20432. }
  20433. // first append to bars list normally:
  20434. if (!mBars.contains(bars))
  20435. bars->setBarsGroup(this);
  20436. // then move to according position:
  20437. mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size()-1));
  20438. }
  20439. /*!
  20440. Removes the specified \a bars plottable from this group.
  20441. \see contains, clear
  20442. */
  20443. void QCPBarsGroup::remove(QCPBars *bars)
  20444. {
  20445. if (!bars)
  20446. {
  20447. qDebug() << Q_FUNC_INFO << "bars is 0";
  20448. return;
  20449. }
  20450. if (mBars.contains(bars))
  20451. bars->setBarsGroup(nullptr);
  20452. else
  20453. qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast<quintptr>(bars);
  20454. }
  20455. /*! \internal
  20456. Adds the specified \a bars to the internal mBars list of bars. This method does not change the
  20457. barsGroup property on \a bars.
  20458. \see unregisterBars
  20459. */
  20460. void QCPBarsGroup::registerBars(QCPBars *bars)
  20461. {
  20462. if (!mBars.contains(bars))
  20463. mBars.append(bars);
  20464. }
  20465. /*! \internal
  20466. Removes the specified \a bars from the internal mBars list of bars. This method does not change
  20467. the barsGroup property on \a bars.
  20468. \see registerBars
  20469. */
  20470. void QCPBarsGroup::unregisterBars(QCPBars *bars)
  20471. {
  20472. mBars.removeOne(bars);
  20473. }
  20474. /*! \internal
  20475. Returns the pixel offset in the key dimension the specified \a bars plottable should have at the
  20476. given key coordinate \a keyCoord. The offset is relative to the pixel position of the key
  20477. coordinate \a keyCoord.
  20478. */
  20479. double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord)
  20480. {
  20481. // find list of all base bars in case some mBars are stacked:
  20482. QList<const QCPBars*> baseBars;
  20483. foreach (const QCPBars *b, mBars)
  20484. {
  20485. while (b->barBelow())
  20486. b = b->barBelow();
  20487. if (!baseBars.contains(b))
  20488. baseBars.append(b);
  20489. }
  20490. // find base bar this "bars" is stacked on:
  20491. const QCPBars *thisBase = bars;
  20492. while (thisBase->barBelow())
  20493. thisBase = thisBase->barBelow();
  20494. // determine key pixel offset of this base bars considering all other base bars in this barsgroup:
  20495. double result = 0;
  20496. int index = baseBars.indexOf(thisBase);
  20497. if (index >= 0)
  20498. {
  20499. if (baseBars.size() % 2 == 1 && index == (baseBars.size()-1)/2) // is center bar (int division on purpose)
  20500. {
  20501. return result;
  20502. } else
  20503. {
  20504. double lowerPixelWidth, upperPixelWidth;
  20505. int startIndex;
  20506. int dir = (index <= (baseBars.size()-1)/2) ? -1 : 1; // if bar is to lower keys of center, dir is negative
  20507. if (baseBars.size() % 2 == 0) // even number of bars
  20508. {
  20509. startIndex = baseBars.size()/2 + (dir < 0 ? -1 : 0);
  20510. result += getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing
  20511. } else // uneven number of bars
  20512. {
  20513. startIndex = (baseBars.size()-1)/2+dir;
  20514. baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  20515. result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar
  20516. result += getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing
  20517. }
  20518. for (int i = startIndex; i != index; i += dir) // add widths and spacings of bars in between center and our bars
  20519. {
  20520. baseBars.at(i)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  20521. result += qAbs(upperPixelWidth-lowerPixelWidth);
  20522. result += getPixelSpacing(baseBars.at(i), keyCoord);
  20523. }
  20524. // finally half of our bars width:
  20525. baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  20526. result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5;
  20527. // correct sign of result depending on orientation and direction of key axis:
  20528. result *= dir*thisBase->keyAxis()->pixelOrientation();
  20529. }
  20530. }
  20531. return result;
  20532. }
  20533. /*! \internal
  20534. Returns the spacing in pixels which is between this \a bars and the following one, both at the
  20535. key coordinate \a keyCoord.
  20536. \note Typically the returned value doesn't depend on \a bars or \a keyCoord. \a bars is only
  20537. needed to get access to the key axis transformation and axis rect for the modes \ref
  20538. stAxisRectRatio and \ref stPlotCoords. The \a keyCoord is only relevant for spacings given in
  20539. \ref stPlotCoords on a logarithmic axis.
  20540. */
  20541. double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord)
  20542. {
  20543. switch (mSpacingType)
  20544. {
  20545. case stAbsolute:
  20546. {
  20547. return mSpacing;
  20548. }
  20549. case stAxisRectRatio:
  20550. {
  20551. if (bars->keyAxis()->orientation() == Qt::Horizontal)
  20552. return bars->keyAxis()->axisRect()->width()*mSpacing;
  20553. else
  20554. return bars->keyAxis()->axisRect()->height()*mSpacing;
  20555. }
  20556. case stPlotCoords:
  20557. {
  20558. double keyPixel = bars->keyAxis()->coordToPixel(keyCoord);
  20559. return qAbs(bars->keyAxis()->coordToPixel(keyCoord+mSpacing)-keyPixel);
  20560. }
  20561. }
  20562. return 0;
  20563. }
  20564. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20565. //////////////////// QCPBarsData
  20566. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20567. /*! \class QCPBarsData
  20568. \brief Holds the data of one single data point (one bar) for QCPBars.
  20569. The stored data is:
  20570. \li \a key: coordinate on the key axis of this bar (this is the \a mainKey and the \a sortKey)
  20571. \li \a value: height coordinate on the value axis of this bar (this is the \a mainValue)
  20572. The container for storing multiple data points is \ref QCPBarsDataContainer. It is a typedef for
  20573. \ref QCPDataContainer with \ref QCPBarsData as the DataType template parameter. See the
  20574. documentation there for an explanation regarding the data type's generic methods.
  20575. \see QCPBarsDataContainer
  20576. */
  20577. /* start documentation of inline functions */
  20578. /*! \fn double QCPBarsData::sortKey() const
  20579. Returns the \a key member of this data point.
  20580. For a general explanation of what this method is good for in the context of the data container,
  20581. see the documentation of \ref QCPDataContainer.
  20582. */
  20583. /*! \fn static QCPBarsData QCPBarsData::fromSortKey(double sortKey)
  20584. Returns a data point with the specified \a sortKey. All other members are set to zero.
  20585. For a general explanation of what this method is good for in the context of the data container,
  20586. see the documentation of \ref QCPDataContainer.
  20587. */
  20588. /*! \fn static static bool QCPBarsData::sortKeyIsMainKey()
  20589. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  20590. this method returns true.
  20591. For a general explanation of what this method is good for in the context of the data container,
  20592. see the documentation of \ref QCPDataContainer.
  20593. */
  20594. /*! \fn double QCPBarsData::mainKey() const
  20595. Returns the \a key member of this data point.
  20596. For a general explanation of what this method is good for in the context of the data container,
  20597. see the documentation of \ref QCPDataContainer.
  20598. */
  20599. /*! \fn double QCPBarsData::mainValue() const
  20600. Returns the \a value 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 QCPRange QCPBarsData::valueRange() const
  20605. Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
  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. /* end documentation of inline functions */
  20610. /*!
  20611. Constructs a bar data point with key and value set to zero.
  20612. */
  20613. QCPBarsData::QCPBarsData() :
  20614. key(0),
  20615. value(0)
  20616. {
  20617. }
  20618. /*!
  20619. Constructs a bar data point with the specified \a key and \a value.
  20620. */
  20621. QCPBarsData::QCPBarsData(double key, double value) :
  20622. key(key),
  20623. value(value)
  20624. {
  20625. }
  20626. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20627. //////////////////// QCPBars
  20628. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20629. /*! \class QCPBars
  20630. \brief A plottable representing a bar chart in a plot.
  20631. \image html QCPBars.png
  20632. To plot data, assign it with the \ref setData or \ref addData functions.
  20633. \section qcpbars-appearance Changing the appearance
  20634. The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush).
  20635. The width of the individual bars can be controlled with \ref setWidthType and \ref setWidth.
  20636. Bar charts are stackable. This means, two QCPBars plottables can be placed on top of each other
  20637. (see \ref QCPBars::moveAbove). So when two bars are at the same key position, they will appear
  20638. stacked.
  20639. If you would like to group multiple QCPBars plottables together so they appear side by side as
  20640. shown below, use QCPBarsGroup.
  20641. \image html QCPBarsGroup.png
  20642. \section qcpbars-usage Usage
  20643. Like all data representing objects in QCustomPlot, the QCPBars is a plottable
  20644. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  20645. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  20646. Usually, you first create an instance:
  20647. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-1
  20648. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  20649. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  20650. The newly created plottable can be modified, e.g.:
  20651. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-2
  20652. */
  20653. /* start of documentation of inline functions */
  20654. /*! \fn QSharedPointer<QCPBarsDataContainer> QCPBars::data() const
  20655. Returns a shared pointer to the internal data storage of type \ref QCPBarsDataContainer. You may
  20656. use it to directly manipulate the data, which may be more convenient and faster than using the
  20657. regular \ref setData or \ref addData methods.
  20658. */
  20659. /*! \fn QCPBars *QCPBars::barBelow() const
  20660. Returns the bars plottable that is directly below this bars plottable.
  20661. If there is no such plottable, returns \c nullptr.
  20662. \see barAbove, moveBelow, moveAbove
  20663. */
  20664. /*! \fn QCPBars *QCPBars::barAbove() const
  20665. Returns the bars plottable that is directly above this bars plottable.
  20666. If there is no such plottable, returns \c nullptr.
  20667. \see barBelow, moveBelow, moveAbove
  20668. */
  20669. /* end of documentation of inline functions */
  20670. /*!
  20671. Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  20672. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  20673. the same orientation. If either of these restrictions is violated, a corresponding message is
  20674. printed to the debug output (qDebug), the construction is not aborted, though.
  20675. The created QCPBars is automatically registered with the QCustomPlot instance inferred from \a
  20676. keyAxis. This QCustomPlot instance takes ownership of the QCPBars, so do not delete it manually
  20677. but use QCustomPlot::removePlottable() instead.
  20678. */
  20679. QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  20680. QCPAbstractPlottable1D<QCPBarsData>(keyAxis, valueAxis),
  20681. mWidth(0.75),
  20682. mWidthType(wtPlotCoords),
  20683. mBarsGroup(nullptr),
  20684. mBaseValue(0),
  20685. mStackingGap(1)
  20686. {
  20687. // modify inherited properties from abstract plottable:
  20688. mPen.setColor(Qt::blue);
  20689. mPen.setStyle(Qt::SolidLine);
  20690. mBrush.setColor(QColor(40, 50, 255, 30));
  20691. mBrush.setStyle(Qt::SolidPattern);
  20692. mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255)));
  20693. }
  20694. QCPBars::~QCPBars()
  20695. {
  20696. setBarsGroup(nullptr);
  20697. if (mBarBelow || mBarAbove)
  20698. connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking
  20699. }
  20700. /*! \overload
  20701. Replaces the current data container with the provided \a data container.
  20702. Since a QSharedPointer is used, multiple QCPBars may share the same data container safely.
  20703. Modifying the data in the container will then affect all bars that share the container. Sharing
  20704. can be achieved by simply exchanging the data containers wrapped in shared pointers:
  20705. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-datasharing-1
  20706. If you do not wish to share containers, but create a copy from an existing container, rather use
  20707. the \ref QCPDataContainer<DataType>::set method on the bar's data container directly:
  20708. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-datasharing-2
  20709. \see addData
  20710. */
  20711. void QCPBars::setData(QSharedPointer<QCPBarsDataContainer> data)
  20712. {
  20713. mDataContainer = data;
  20714. }
  20715. /*! \overload
  20716. Replaces the current data with the provided points in \a keys and \a values. The provided
  20717. vectors should have equal length. Else, the number of added points will be the size of the
  20718. smallest vector.
  20719. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  20720. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  20721. \see addData
  20722. */
  20723. void QCPBars::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  20724. {
  20725. mDataContainer->clear();
  20726. addData(keys, values, alreadySorted);
  20727. }
  20728. /*!
  20729. Sets the width of the bars.
  20730. How the number passed as \a width is interpreted (e.g. screen pixels, plot coordinates,...),
  20731. depends on the currently set width type, see \ref setWidthType and \ref WidthType.
  20732. */
  20733. void QCPBars::setWidth(double width)
  20734. {
  20735. mWidth = width;
  20736. }
  20737. /*!
  20738. Sets how the width of the bars is defined. See the documentation of \ref WidthType for an
  20739. explanation of the possible values for \a widthType.
  20740. The default value is \ref wtPlotCoords.
  20741. \see setWidth
  20742. */
  20743. void QCPBars::setWidthType(QCPBars::WidthType widthType)
  20744. {
  20745. mWidthType = widthType;
  20746. }
  20747. /*!
  20748. Sets to which QCPBarsGroup this QCPBars instance belongs to. Alternatively, you can also use \ref
  20749. QCPBarsGroup::append.
  20750. To remove this QCPBars from any group, set \a barsGroup to \c nullptr.
  20751. */
  20752. void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup)
  20753. {
  20754. // deregister at old group:
  20755. if (mBarsGroup)
  20756. mBarsGroup->unregisterBars(this);
  20757. mBarsGroup = barsGroup;
  20758. // register at new group:
  20759. if (mBarsGroup)
  20760. mBarsGroup->registerBars(this);
  20761. }
  20762. /*!
  20763. Sets the base value of this bars plottable.
  20764. The base value defines where on the value coordinate the bars start. How far the bars extend from
  20765. the base value is given by their individual value data. For example, if the base value is set to
  20766. 1, a bar with data value 2 will have its lowest point at value coordinate 1 and highest point at
  20767. 3.
  20768. For stacked bars, only the base value of the bottom-most QCPBars has meaning.
  20769. The default base value is 0.
  20770. */
  20771. void QCPBars::setBaseValue(double baseValue)
  20772. {
  20773. mBaseValue = baseValue;
  20774. }
  20775. /*!
  20776. If this bars plottable is stacked on top of another bars plottable (\ref moveAbove), this method
  20777. allows specifying a distance in \a pixels, by which the drawn bar rectangles will be separated by
  20778. the bars below it.
  20779. */
  20780. void QCPBars::setStackingGap(double pixels)
  20781. {
  20782. mStackingGap = pixels;
  20783. }
  20784. /*! \overload
  20785. Adds the provided points in \a keys and \a values to the current data. The provided vectors
  20786. should have equal length. Else, the number of added points will be the size of the smallest
  20787. vector.
  20788. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  20789. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  20790. Alternatively, you can also access and modify the data directly via the \ref data method, which
  20791. returns a pointer to the internal data container.
  20792. */
  20793. void QCPBars::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  20794. {
  20795. if (keys.size() != values.size())
  20796. qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
  20797. const int n = qMin(keys.size(), values.size());
  20798. QVector<QCPBarsData> tempData(n);
  20799. QVector<QCPBarsData>::iterator it = tempData.begin();
  20800. const QVector<QCPBarsData>::iterator itEnd = tempData.end();
  20801. int i = 0;
  20802. while (it != itEnd)
  20803. {
  20804. it->key = keys[i];
  20805. it->value = values[i];
  20806. ++it;
  20807. ++i;
  20808. }
  20809. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  20810. }
  20811. /*! \overload
  20812. Adds the provided data point as \a key and \a value to the current data.
  20813. Alternatively, you can also access and modify the data directly via the \ref data method, which
  20814. returns a pointer to the internal data container.
  20815. */
  20816. void QCPBars::addData(double key, double value)
  20817. {
  20818. mDataContainer->add(QCPBarsData(key, value));
  20819. }
  20820. /*!
  20821. Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear
  20822. below the bars of \a bars. The move target \a bars must use the same key and value axis as this
  20823. plottable.
  20824. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
  20825. has a bars object below itself, this bars object is inserted between the two. If this bars object
  20826. is already between two other bars, the two other bars will be stacked on top of each other after
  20827. the operation.
  20828. To remove this bars plottable from any stacking, set \a bars to \c nullptr.
  20829. \see moveBelow, barAbove, barBelow
  20830. */
  20831. void QCPBars::moveBelow(QCPBars *bars)
  20832. {
  20833. if (bars == this) return;
  20834. if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
  20835. {
  20836. qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
  20837. return;
  20838. }
  20839. // remove from stacking:
  20840. connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
  20841. // if new bar given, insert this bar below it:
  20842. if (bars)
  20843. {
  20844. if (bars->mBarBelow)
  20845. connectBars(bars->mBarBelow.data(), this);
  20846. connectBars(this, bars);
  20847. }
  20848. }
  20849. /*!
  20850. Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear
  20851. above the bars of \a bars. The move target \a bars must use the same key and value axis as this
  20852. plottable.
  20853. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
  20854. has a bars object above itself, this bars object is inserted between the two. If this bars object
  20855. is already between two other bars, the two other bars will be stacked on top of each other after
  20856. the operation.
  20857. To remove this bars plottable from any stacking, set \a bars to \c nullptr.
  20858. \see moveBelow, barBelow, barAbove
  20859. */
  20860. void QCPBars::moveAbove(QCPBars *bars)
  20861. {
  20862. if (bars == this) return;
  20863. if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
  20864. {
  20865. qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
  20866. return;
  20867. }
  20868. // remove from stacking:
  20869. connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
  20870. // if new bar given, insert this bar above it:
  20871. if (bars)
  20872. {
  20873. if (bars->mBarAbove)
  20874. connectBars(this, bars->mBarAbove.data());
  20875. connectBars(bars, this);
  20876. }
  20877. }
  20878. /*!
  20879. \copydoc QCPPlottableInterface1D::selectTestRect
  20880. */
  20881. QCPDataSelection QCPBars::selectTestRect(const QRectF &rect, bool onlySelectable) const
  20882. {
  20883. QCPDataSelection result;
  20884. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  20885. return result;
  20886. if (!mKeyAxis || !mValueAxis)
  20887. return result;
  20888. QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  20889. getVisibleDataBounds(visibleBegin, visibleEnd);
  20890. for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  20891. {
  20892. if (rect.intersects(getBarRect(it->key, it->value)))
  20893. result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
  20894. }
  20895. result.simplify();
  20896. return result;
  20897. }
  20898. /*!
  20899. Implements a selectTest specific to this plottable's point geometry.
  20900. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  20901. point to \a pos.
  20902. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  20903. */
  20904. double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  20905. {
  20906. Q_UNUSED(details)
  20907. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  20908. return -1;
  20909. if (!mKeyAxis || !mValueAxis)
  20910. return -1;
  20911. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  20912. {
  20913. // get visible data range:
  20914. QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  20915. getVisibleDataBounds(visibleBegin, visibleEnd);
  20916. for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  20917. {
  20918. if (getBarRect(it->key, it->value).contains(pos))
  20919. {
  20920. if (details)
  20921. {
  20922. int pointIndex = int(it-mDataContainer->constBegin());
  20923. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  20924. }
  20925. return mParentPlot->selectionTolerance()*0.99;
  20926. }
  20927. }
  20928. }
  20929. return -1;
  20930. }
  20931. /* inherits documentation from base class */
  20932. QCPRange QCPBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  20933. {
  20934. /* Note: If this QCPBars uses absolute pixels as width (or is in a QCPBarsGroup with spacing in
  20935. absolute pixels), using this method to adapt the key axis range to fit the bars into the
  20936. currently visible axis range will not work perfectly. Because in the moment the axis range is
  20937. changed to the new range, the fixed pixel widths/spacings will represent different coordinate
  20938. spans than before, which in turn would require a different key range to perfectly fit, and so on.
  20939. The only solution would be to iteratively approach the perfect fitting axis range, but the
  20940. mismatch isn't large enough in most applications, to warrant this here. If a user does need a
  20941. better fit, he should call the corresponding axis rescale multiple times in a row.
  20942. */
  20943. QCPRange range;
  20944. range = mDataContainer->keyRange(foundRange, inSignDomain);
  20945. // determine exact range of bars by including bar width and barsgroup offset:
  20946. if (foundRange && mKeyAxis)
  20947. {
  20948. double lowerPixelWidth, upperPixelWidth, keyPixel;
  20949. // lower range bound:
  20950. getPixelWidth(range.lower, lowerPixelWidth, upperPixelWidth);
  20951. keyPixel = mKeyAxis.data()->coordToPixel(range.lower) + lowerPixelWidth;
  20952. if (mBarsGroup)
  20953. keyPixel += mBarsGroup->keyPixelOffset(this, range.lower);
  20954. const double lowerCorrected = mKeyAxis.data()->pixelToCoord(keyPixel);
  20955. if (!qIsNaN(lowerCorrected) && qIsFinite(lowerCorrected) && range.lower > lowerCorrected)
  20956. range.lower = lowerCorrected;
  20957. // upper range bound:
  20958. getPixelWidth(range.upper, lowerPixelWidth, upperPixelWidth);
  20959. keyPixel = mKeyAxis.data()->coordToPixel(range.upper) + upperPixelWidth;
  20960. if (mBarsGroup)
  20961. keyPixel += mBarsGroup->keyPixelOffset(this, range.upper);
  20962. const double upperCorrected = mKeyAxis.data()->pixelToCoord(keyPixel);
  20963. if (!qIsNaN(upperCorrected) && qIsFinite(upperCorrected) && range.upper < upperCorrected)
  20964. range.upper = upperCorrected;
  20965. }
  20966. return range;
  20967. }
  20968. /* inherits documentation from base class */
  20969. QCPRange QCPBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  20970. {
  20971. // Note: can't simply use mDataContainer->valueRange here because we need to
  20972. // take into account bar base value and possible stacking of multiple bars
  20973. QCPRange range;
  20974. range.lower = mBaseValue;
  20975. range.upper = mBaseValue;
  20976. bool haveLower = true; // set to true, because baseValue should always be visible in bar charts
  20977. bool haveUpper = true; // set to true, because baseValue should always be visible in bar charts
  20978. QCPBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin();
  20979. QCPBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd();
  20980. if (inKeyRange != QCPRange())
  20981. {
  20982. itBegin = mDataContainer->findBegin(inKeyRange.lower, false);
  20983. itEnd = mDataContainer->findEnd(inKeyRange.upper, false);
  20984. }
  20985. for (QCPBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it)
  20986. {
  20987. const double current = it->value + getStackedBaseValue(it->key, it->value >= 0);
  20988. if (qIsNaN(current)) continue;
  20989. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  20990. {
  20991. if (current < range.lower || !haveLower)
  20992. {
  20993. range.lower = current;
  20994. haveLower = true;
  20995. }
  20996. if (current > range.upper || !haveUpper)
  20997. {
  20998. range.upper = current;
  20999. haveUpper = true;
  21000. }
  21001. }
  21002. }
  21003. foundRange = true; // return true because bar charts always have the 0-line visible
  21004. return range;
  21005. }
  21006. /* inherits documentation from base class */
  21007. QPointF QCPBars::dataPixelPosition(int index) const
  21008. {
  21009. if (index >= 0 && index < mDataContainer->size())
  21010. {
  21011. QCPAxis *keyAxis = mKeyAxis.data();
  21012. QCPAxis *valueAxis = mValueAxis.data();
  21013. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
  21014. const QCPDataContainer<QCPBarsData>::const_iterator it = mDataContainer->constBegin()+index;
  21015. const double valuePixel = valueAxis->coordToPixel(getStackedBaseValue(it->key, it->value >= 0) + it->value);
  21016. const double keyPixel = keyAxis->coordToPixel(it->key) + (mBarsGroup ? mBarsGroup->keyPixelOffset(this, it->key) : 0);
  21017. if (keyAxis->orientation() == Qt::Horizontal)
  21018. return {keyPixel, valuePixel};
  21019. else
  21020. return {valuePixel, keyPixel};
  21021. } else
  21022. {
  21023. qDebug() << Q_FUNC_INFO << "Index out of bounds" << index;
  21024. return {};
  21025. }
  21026. }
  21027. /* inherits documentation from base class */
  21028. void QCPBars::draw(QCPPainter *painter)
  21029. {
  21030. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  21031. if (mDataContainer->isEmpty()) return;
  21032. QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  21033. getVisibleDataBounds(visibleBegin, visibleEnd);
  21034. // loop over and draw segments of unselected/selected data:
  21035. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  21036. getDataSegments(selectedSegments, unselectedSegments);
  21037. allSegments << unselectedSegments << selectedSegments;
  21038. for (int i=0; i<allSegments.size(); ++i)
  21039. {
  21040. bool isSelectedSegment = i >= unselectedSegments.size();
  21041. QCPBarsDataContainer::const_iterator begin = visibleBegin;
  21042. QCPBarsDataContainer::const_iterator end = visibleEnd;
  21043. mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
  21044. if (begin == end)
  21045. continue;
  21046. for (QCPBarsDataContainer::const_iterator it=begin; it!=end; ++it)
  21047. {
  21048. // check data validity if flag set:
  21049. #ifdef QCUSTOMPLOT_CHECK_DATA
  21050. if (QCP::isInvalidData(it->key, it->value))
  21051. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range invalid." << "Plottable name:" << name();
  21052. #endif
  21053. // draw bar:
  21054. if (isSelectedSegment && mSelectionDecorator)
  21055. {
  21056. mSelectionDecorator->applyBrush(painter);
  21057. mSelectionDecorator->applyPen(painter);
  21058. } else
  21059. {
  21060. painter->setBrush(mBrush);
  21061. painter->setPen(mPen);
  21062. }
  21063. applyDefaultAntialiasingHint(painter);
  21064. painter->drawPolygon(getBarRect(it->key, it->value));
  21065. }
  21066. }
  21067. // draw other selection decoration that isn't just line/scatter pens and brushes:
  21068. if (mSelectionDecorator)
  21069. mSelectionDecorator->drawDecoration(painter, selection());
  21070. }
  21071. /* inherits documentation from base class */
  21072. void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  21073. {
  21074. // draw filled rect:
  21075. applyDefaultAntialiasingHint(painter);
  21076. painter->setBrush(mBrush);
  21077. painter->setPen(mPen);
  21078. QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
  21079. r.moveCenter(rect.center());
  21080. painter->drawRect(r);
  21081. }
  21082. /*! \internal
  21083. called by \ref draw to determine which data (key) range is visible at the current key axis range
  21084. setting, so only that needs to be processed. It also takes into account the bar width.
  21085. \a begin returns an iterator to the lowest data point that needs to be taken into account when
  21086. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  21087. lower may still be just outside the visible range.
  21088. \a end returns an iterator one higher than the highest visible data point. Same as before, \a end
  21089. may also lie just outside of the visible range.
  21090. if the plottable contains no data, both \a begin and \a end point to constEnd.
  21091. */
  21092. void QCPBars::getVisibleDataBounds(QCPBarsDataContainer::const_iterator &begin, QCPBarsDataContainer::const_iterator &end) const
  21093. {
  21094. if (!mKeyAxis)
  21095. {
  21096. qDebug() << Q_FUNC_INFO << "invalid key axis";
  21097. begin = mDataContainer->constEnd();
  21098. end = mDataContainer->constEnd();
  21099. return;
  21100. }
  21101. if (mDataContainer->isEmpty())
  21102. {
  21103. begin = mDataContainer->constEnd();
  21104. end = mDataContainer->constEnd();
  21105. return;
  21106. }
  21107. // get visible data range as QMap iterators
  21108. begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower);
  21109. end = mDataContainer->findEnd(mKeyAxis.data()->range().upper);
  21110. double lowerPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().lower);
  21111. double upperPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().upper);
  21112. bool isVisible = false;
  21113. // walk left from begin to find lower bar that actually is completely outside visible pixel range:
  21114. QCPBarsDataContainer::const_iterator it = begin;
  21115. while (it != mDataContainer->constBegin())
  21116. {
  21117. --it;
  21118. const QRectF barRect = getBarRect(it->key, it->value);
  21119. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  21120. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.left() <= lowerPixelBound));
  21121. else // keyaxis is vertical
  21122. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.bottom() >= lowerPixelBound));
  21123. if (isVisible)
  21124. begin = it;
  21125. else
  21126. break;
  21127. }
  21128. // walk right from ubound to find upper bar that actually is completely outside visible pixel range:
  21129. it = end;
  21130. while (it != mDataContainer->constEnd())
  21131. {
  21132. const QRectF barRect = getBarRect(it->key, it->value);
  21133. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  21134. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.right() >= upperPixelBound));
  21135. else // keyaxis is vertical
  21136. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.top() <= upperPixelBound));
  21137. if (isVisible)
  21138. end = it+1;
  21139. else
  21140. break;
  21141. ++it;
  21142. }
  21143. }
  21144. /*! \internal
  21145. Returns the rect in pixel coordinates of a single bar with the specified \a key and \a value. The
  21146. rect is shifted according to the bar stacking (see \ref moveAbove) and base value (see \ref
  21147. setBaseValue), and to have non-overlapping border lines with the bars stacked below.
  21148. */
  21149. QRectF QCPBars::getBarRect(double key, double value) const
  21150. {
  21151. QCPAxis *keyAxis = mKeyAxis.data();
  21152. QCPAxis *valueAxis = mValueAxis.data();
  21153. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
  21154. double lowerPixelWidth, upperPixelWidth;
  21155. getPixelWidth(key, lowerPixelWidth, upperPixelWidth);
  21156. double base = getStackedBaseValue(key, value >= 0);
  21157. double basePixel = valueAxis->coordToPixel(base);
  21158. double valuePixel = valueAxis->coordToPixel(base+value);
  21159. double keyPixel = keyAxis->coordToPixel(key);
  21160. if (mBarsGroup)
  21161. keyPixel += mBarsGroup->keyPixelOffset(this, key);
  21162. double bottomOffset = (mBarBelow && mPen != Qt::NoPen ? 1 : 0)*(mPen.isCosmetic() ? 1 : mPen.widthF());
  21163. bottomOffset += mBarBelow ? mStackingGap : 0;
  21164. bottomOffset *= (value<0 ? -1 : 1)*valueAxis->pixelOrientation();
  21165. if (qAbs(valuePixel-basePixel) <= qAbs(bottomOffset))
  21166. bottomOffset = valuePixel-basePixel;
  21167. if (keyAxis->orientation() == Qt::Horizontal)
  21168. {
  21169. return QRectF(QPointF(keyPixel+lowerPixelWidth, valuePixel), QPointF(keyPixel+upperPixelWidth, basePixel+bottomOffset)).normalized();
  21170. } else
  21171. {
  21172. return QRectF(QPointF(basePixel+bottomOffset, keyPixel+lowerPixelWidth), QPointF(valuePixel, keyPixel+upperPixelWidth)).normalized();
  21173. }
  21174. }
  21175. /*! \internal
  21176. This function is used to determine the width of the bar at coordinate \a key, according to the
  21177. specified width (\ref setWidth) and width type (\ref setWidthType).
  21178. The output parameters \a lower and \a upper return the number of pixels the bar extends to lower
  21179. and higher keys, relative to the \a key coordinate (so with a non-reversed horizontal axis, \a
  21180. lower is negative and \a upper positive).
  21181. */
  21182. void QCPBars::getPixelWidth(double key, double &lower, double &upper) const
  21183. {
  21184. lower = 0;
  21185. upper = 0;
  21186. switch (mWidthType)
  21187. {
  21188. case wtAbsolute:
  21189. {
  21190. upper = mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  21191. lower = -upper;
  21192. break;
  21193. }
  21194. case wtAxisRectRatio:
  21195. {
  21196. if (mKeyAxis && mKeyAxis.data()->axisRect())
  21197. {
  21198. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  21199. upper = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  21200. else
  21201. upper = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  21202. lower = -upper;
  21203. } else
  21204. qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined";
  21205. break;
  21206. }
  21207. case wtPlotCoords:
  21208. {
  21209. if (mKeyAxis)
  21210. {
  21211. double keyPixel = mKeyAxis.data()->coordToPixel(key);
  21212. upper = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel;
  21213. lower = mKeyAxis.data()->coordToPixel(key-mWidth*0.5)-keyPixel;
  21214. // no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by
  21215. // coordinate transform which includes range direction
  21216. } else
  21217. qDebug() << Q_FUNC_INFO << "No key axis defined";
  21218. break;
  21219. }
  21220. }
  21221. }
  21222. /*! \internal
  21223. This function is called to find at which value to start drawing the base of a bar at \a key, when
  21224. it is stacked on top of another QCPBars (e.g. with \ref moveAbove).
  21225. positive and negative bars are separated per stack (positive are stacked above baseValue upwards,
  21226. negative are stacked below baseValue downwards). This can be indicated with \a positive. So if the
  21227. bar for which we need the base value is negative, set \a positive to false.
  21228. */
  21229. double QCPBars::getStackedBaseValue(double key, bool positive) const
  21230. {
  21231. if (mBarBelow)
  21232. {
  21233. double max = 0; // don't initialize with mBaseValue here because only base value of bottom-most bar has meaning in a bar stack
  21234. // find bars of mBarBelow that are approximately at key and find largest one:
  21235. double epsilon = qAbs(key)*(sizeof(key)==4 ? 1e-6 : 1e-14); // should be safe even when changed to use float at some point
  21236. if (qFuzzyCompare(key, 0))
  21237. epsilon = (sizeof(key)==4 ? 1e-6 : 1e-14);
  21238. QCPBarsDataContainer::const_iterator it = mBarBelow.data()->mDataContainer->findBegin(key-epsilon);
  21239. QCPBarsDataContainer::const_iterator itEnd = mBarBelow.data()->mDataContainer->findEnd(key+epsilon);
  21240. while (it != itEnd)
  21241. {
  21242. if (it->key > key-epsilon && it->key < key+epsilon)
  21243. {
  21244. if ((positive && it->value > max) ||
  21245. (!positive && it->value < max))
  21246. max = it->value;
  21247. }
  21248. ++it;
  21249. }
  21250. // recurse down the bar-stack to find the total height:
  21251. return max + mBarBelow.data()->getStackedBaseValue(key, positive);
  21252. } else
  21253. return mBaseValue;
  21254. }
  21255. /*! \internal
  21256. Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s)
  21257. currently above lower and below upper will become disconnected to lower/upper.
  21258. If lower is zero, upper will be disconnected at the bottom.
  21259. If upper is zero, lower will be disconnected at the top.
  21260. */
  21261. void QCPBars::connectBars(QCPBars *lower, QCPBars *upper)
  21262. {
  21263. if (!lower && !upper) return;
  21264. if (!lower) // disconnect upper at bottom
  21265. {
  21266. // disconnect old bar below upper:
  21267. if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
  21268. upper->mBarBelow.data()->mBarAbove = nullptr;
  21269. upper->mBarBelow = nullptr;
  21270. } else if (!upper) // disconnect lower at top
  21271. {
  21272. // disconnect old bar above lower:
  21273. if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
  21274. lower->mBarAbove.data()->mBarBelow = nullptr;
  21275. lower->mBarAbove = nullptr;
  21276. } else // connect lower and upper
  21277. {
  21278. // disconnect old bar above lower:
  21279. if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
  21280. lower->mBarAbove.data()->mBarBelow = nullptr;
  21281. // disconnect old bar below upper:
  21282. if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
  21283. upper->mBarBelow.data()->mBarAbove = nullptr;
  21284. lower->mBarAbove = upper;
  21285. upper->mBarBelow = lower;
  21286. }
  21287. }
  21288. /* end of 'src/plottables/plottable-bars.cpp' */
  21289. /* including file 'src/plottables/plottable-statisticalbox.cpp' */
  21290. /* modified 2021-03-29T02:30:44, size 28951 */
  21291. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21292. //////////////////// QCPStatisticalBoxData
  21293. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21294. /*! \class QCPStatisticalBoxData
  21295. \brief Holds the data of one single data point for QCPStatisticalBox.
  21296. The stored data is:
  21297. \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
  21298. \li \a minimum: the position of the lower whisker, typically the minimum measurement of the
  21299. sample that's not considered an outlier.
  21300. \li \a lowerQuartile: the lower end of the box. The lower and the upper quartiles are the two
  21301. statistical quartiles around the median of the sample, they should contain 50% of the sample
  21302. data.
  21303. \li \a median: the value of the median mark inside the quartile box. The median separates the
  21304. sample data in half (50% of the sample data is below/above the median). (This is the \a mainValue)
  21305. \li \a upperQuartile: the upper end of the box. The lower and the upper quartiles are the two
  21306. statistical quartiles around the median of the sample, they should contain 50% of the sample
  21307. data.
  21308. \li \a maximum: the position of the upper whisker, typically the maximum measurement of the
  21309. sample that's not considered an outlier.
  21310. \li \a outliers: a QVector of outlier values that will be drawn as scatter points at the \a key
  21311. coordinate of this data point (see \ref QCPStatisticalBox::setOutlierStyle)
  21312. The container for storing multiple data points is \ref QCPStatisticalBoxDataContainer. It is a
  21313. typedef for \ref QCPDataContainer with \ref QCPStatisticalBoxData as the DataType template
  21314. parameter. See the documentation there for an explanation regarding the data type's generic
  21315. methods.
  21316. \see QCPStatisticalBoxDataContainer
  21317. */
  21318. /* start documentation of inline functions */
  21319. /*! \fn double QCPStatisticalBoxData::sortKey() const
  21320. Returns the \a key member of this data point.
  21321. For a general explanation of what this method is good for in the context of the data container,
  21322. see the documentation of \ref QCPDataContainer.
  21323. */
  21324. /*! \fn static QCPStatisticalBoxData QCPStatisticalBoxData::fromSortKey(double sortKey)
  21325. Returns a data point with the specified \a sortKey. All other members are set to zero.
  21326. For a general explanation of what this method is good for in the context of the data container,
  21327. see the documentation of \ref QCPDataContainer.
  21328. */
  21329. /*! \fn static static bool QCPStatisticalBoxData::sortKeyIsMainKey()
  21330. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  21331. this method returns true.
  21332. For a general explanation of what this method is good for in the context of the data container,
  21333. see the documentation of \ref QCPDataContainer.
  21334. */
  21335. /*! \fn double QCPStatisticalBoxData::mainKey() const
  21336. Returns the \a key member of this data point.
  21337. For a general explanation of what this method is good for in the context of the data container,
  21338. see the documentation of \ref QCPDataContainer.
  21339. */
  21340. /*! \fn double QCPStatisticalBoxData::mainValue() const
  21341. Returns the \a median 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 QCPRange QCPStatisticalBoxData::valueRange() const
  21346. Returns a QCPRange spanning from the \a minimum to the \a maximum member of this statistical box
  21347. data point, possibly further expanded by outliers.
  21348. For a general explanation of what this method is good for in the context of the data container,
  21349. see the documentation of \ref QCPDataContainer.
  21350. */
  21351. /* end documentation of inline functions */
  21352. /*!
  21353. Constructs a data point with key and all values set to zero.
  21354. */
  21355. QCPStatisticalBoxData::QCPStatisticalBoxData() :
  21356. key(0),
  21357. minimum(0),
  21358. lowerQuartile(0),
  21359. median(0),
  21360. upperQuartile(0),
  21361. maximum(0)
  21362. {
  21363. }
  21364. /*!
  21365. Constructs a data point with the specified \a key, \a minimum, \a lowerQuartile, \a median, \a
  21366. upperQuartile, \a maximum and optionally a number of \a outliers.
  21367. */
  21368. QCPStatisticalBoxData::QCPStatisticalBoxData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers) :
  21369. key(key),
  21370. minimum(minimum),
  21371. lowerQuartile(lowerQuartile),
  21372. median(median),
  21373. upperQuartile(upperQuartile),
  21374. maximum(maximum),
  21375. outliers(outliers)
  21376. {
  21377. }
  21378. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21379. //////////////////// QCPStatisticalBox
  21380. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21381. /*! \class QCPStatisticalBox
  21382. \brief A plottable representing a single statistical box in a plot.
  21383. \image html QCPStatisticalBox.png
  21384. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
  21385. also access and modify the data via the \ref data method, which returns a pointer to the internal
  21386. \ref QCPStatisticalBoxDataContainer.
  21387. Additionally each data point can itself have a list of outliers, drawn as scatter points at the
  21388. key coordinate of the respective statistical box data point. They can either be set by using the
  21389. respective \ref addData(double,double,double,double,double,double,const QVector<double>&)
  21390. "addData" method or accessing the individual data points through \ref data, and setting the
  21391. <tt>QVector<double> outliers</tt> of the data points directly.
  21392. \section qcpstatisticalbox-appearance Changing the appearance
  21393. The appearance of each data point box, ranging from the lower to the upper quartile, is
  21394. controlled via \ref setPen and \ref setBrush. You may change the width of the boxes with \ref
  21395. setWidth in plot coordinates.
  21396. Each data point's visual representation also consists of two whiskers. Whiskers are the lines
  21397. which reach from the upper quartile to the maximum, and from the lower quartile to the minimum.
  21398. The appearance of the whiskers can be modified with: \ref setWhiskerPen, \ref setWhiskerBarPen,
  21399. \ref setWhiskerWidth. The whisker width is the width of the bar perpendicular to the whisker at
  21400. the top (for maximum) and bottom (for minimum). If the whisker pen is changed, make sure to set
  21401. the \c capStyle to \c Qt::FlatCap. Otherwise the backbone line might exceed the whisker bars by a
  21402. few pixels due to the pen cap being not perfectly flat.
  21403. The median indicator line inside the box has its own pen, \ref setMedianPen.
  21404. The outlier data points are drawn as normal scatter points. Their look can be controlled with
  21405. \ref setOutlierStyle
  21406. \section qcpstatisticalbox-usage Usage
  21407. Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable
  21408. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  21409. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  21410. Usually, you first create an instance:
  21411. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-1
  21412. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  21413. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  21414. The newly created plottable can be modified, e.g.:
  21415. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-2
  21416. */
  21417. /* start documentation of inline functions */
  21418. /*! \fn QSharedPointer<QCPStatisticalBoxDataContainer> QCPStatisticalBox::data() const
  21419. Returns a shared pointer to the internal data storage of type \ref
  21420. QCPStatisticalBoxDataContainer. You may use it to directly manipulate the data, which may be more
  21421. convenient and faster than using the regular \ref setData or \ref addData methods.
  21422. */
  21423. /* end documentation of inline functions */
  21424. /*!
  21425. Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its
  21426. value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and
  21427. not have the same orientation. If either of these restrictions is violated, a corresponding
  21428. message is printed to the debug output (qDebug), the construction is not aborted, though.
  21429. The created QCPStatisticalBox is automatically registered with the QCustomPlot instance inferred
  21430. from \a keyAxis. This QCustomPlot instance takes ownership of the QCPStatisticalBox, so do not
  21431. delete it manually but use QCustomPlot::removePlottable() instead.
  21432. */
  21433. QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  21434. QCPAbstractPlottable1D<QCPStatisticalBoxData>(keyAxis, valueAxis),
  21435. mWidth(0.5),
  21436. mWhiskerWidth(0.2),
  21437. mWhiskerPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap),
  21438. mWhiskerBarPen(Qt::black),
  21439. mWhiskerAntialiased(false),
  21440. mMedianPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap),
  21441. mOutlierStyle(QCPScatterStyle::ssCircle, Qt::blue, 6)
  21442. {
  21443. setPen(QPen(Qt::black));
  21444. setBrush(Qt::NoBrush);
  21445. }
  21446. /*! \overload
  21447. Replaces the current data container with the provided \a data container.
  21448. Since a QSharedPointer is used, multiple QCPStatisticalBoxes may share the same data container
  21449. safely. Modifying the data in the container will then affect all statistical boxes that share the
  21450. container. Sharing can be achieved by simply exchanging the data containers wrapped in shared
  21451. pointers:
  21452. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-datasharing-1
  21453. If you do not wish to share containers, but create a copy from an existing container, rather use
  21454. the \ref QCPDataContainer<DataType>::set method on the statistical box data container directly:
  21455. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-datasharing-2
  21456. \see addData
  21457. */
  21458. void QCPStatisticalBox::setData(QSharedPointer<QCPStatisticalBoxDataContainer> data)
  21459. {
  21460. mDataContainer = data;
  21461. }
  21462. /*! \overload
  21463. Replaces the current data with the provided points in \a keys, \a minimum, \a lowerQuartile, \a
  21464. median, \a upperQuartile and \a maximum. The provided vectors should have equal length. Else, the
  21465. number of added points will be the size of the smallest vector.
  21466. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  21467. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  21468. \see addData
  21469. */
  21470. 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)
  21471. {
  21472. mDataContainer->clear();
  21473. addData(keys, minimum, lowerQuartile, median, upperQuartile, maximum, alreadySorted);
  21474. }
  21475. /*!
  21476. Sets the width of the boxes in key coordinates.
  21477. \see setWhiskerWidth
  21478. */
  21479. void QCPStatisticalBox::setWidth(double width)
  21480. {
  21481. mWidth = width;
  21482. }
  21483. /*!
  21484. Sets the width of the whiskers in key coordinates.
  21485. Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
  21486. quartile to the minimum.
  21487. \see setWidth
  21488. */
  21489. void QCPStatisticalBox::setWhiskerWidth(double width)
  21490. {
  21491. mWhiskerWidth = width;
  21492. }
  21493. /*!
  21494. Sets the pen used for drawing the whisker backbone.
  21495. Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
  21496. quartile to the minimum.
  21497. Make sure to set the \c capStyle of the passed \a pen to \c Qt::FlatCap. Otherwise the backbone
  21498. line might exceed the whisker bars by a few pixels due to the pen cap being not perfectly flat.
  21499. \see setWhiskerBarPen
  21500. */
  21501. void QCPStatisticalBox::setWhiskerPen(const QPen &pen)
  21502. {
  21503. mWhiskerPen = pen;
  21504. }
  21505. /*!
  21506. Sets the pen used for drawing the whisker bars. Those are the lines parallel to the key axis at
  21507. each end of the whisker backbone.
  21508. Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
  21509. quartile to the minimum.
  21510. \see setWhiskerPen
  21511. */
  21512. void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen)
  21513. {
  21514. mWhiskerBarPen = pen;
  21515. }
  21516. /*!
  21517. Sets whether the statistical boxes whiskers are drawn with antialiasing or not.
  21518. Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and
  21519. QCustomPlot::setNotAntialiasedElements.
  21520. */
  21521. void QCPStatisticalBox::setWhiskerAntialiased(bool enabled)
  21522. {
  21523. mWhiskerAntialiased = enabled;
  21524. }
  21525. /*!
  21526. Sets the pen used for drawing the median indicator line inside the statistical boxes.
  21527. */
  21528. void QCPStatisticalBox::setMedianPen(const QPen &pen)
  21529. {
  21530. mMedianPen = pen;
  21531. }
  21532. /*!
  21533. Sets the appearance of the outlier data points.
  21534. Outliers can be specified with the method
  21535. \ref addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers)
  21536. */
  21537. void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style)
  21538. {
  21539. mOutlierStyle = style;
  21540. }
  21541. /*! \overload
  21542. Adds the provided points in \a keys, \a minimum, \a lowerQuartile, \a median, \a upperQuartile and
  21543. \a maximum to the current data. The provided vectors should have equal length. Else, the number
  21544. of added points will be the size of the smallest vector.
  21545. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  21546. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  21547. Alternatively, you can also access and modify the data directly via the \ref data method, which
  21548. returns a pointer to the internal data container.
  21549. */
  21550. 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)
  21551. {
  21552. if (keys.size() != minimum.size() || minimum.size() != lowerQuartile.size() || lowerQuartile.size() != median.size() ||
  21553. median.size() != upperQuartile.size() || upperQuartile.size() != maximum.size() || maximum.size() != keys.size())
  21554. qDebug() << Q_FUNC_INFO << "keys, minimum, lowerQuartile, median, upperQuartile, maximum have different sizes:"
  21555. << keys.size() << minimum.size() << lowerQuartile.size() << median.size() << upperQuartile.size() << maximum.size();
  21556. const int n = qMin(keys.size(), qMin(minimum.size(), qMin(lowerQuartile.size(), qMin(median.size(), qMin(upperQuartile.size(), maximum.size())))));
  21557. QVector<QCPStatisticalBoxData> tempData(n);
  21558. QVector<QCPStatisticalBoxData>::iterator it = tempData.begin();
  21559. const QVector<QCPStatisticalBoxData>::iterator itEnd = tempData.end();
  21560. int i = 0;
  21561. while (it != itEnd)
  21562. {
  21563. it->key = keys[i];
  21564. it->minimum = minimum[i];
  21565. it->lowerQuartile = lowerQuartile[i];
  21566. it->median = median[i];
  21567. it->upperQuartile = upperQuartile[i];
  21568. it->maximum = maximum[i];
  21569. ++it;
  21570. ++i;
  21571. }
  21572. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  21573. }
  21574. /*! \overload
  21575. Adds the provided data point as \a key, \a minimum, \a lowerQuartile, \a median, \a upperQuartile
  21576. and \a maximum to the current data.
  21577. Alternatively, you can also access and modify the data directly via the \ref data method, which
  21578. returns a pointer to the internal data container.
  21579. */
  21580. void QCPStatisticalBox::addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers)
  21581. {
  21582. mDataContainer->add(QCPStatisticalBoxData(key, minimum, lowerQuartile, median, upperQuartile, maximum, outliers));
  21583. }
  21584. /*!
  21585. \copydoc QCPPlottableInterface1D::selectTestRect
  21586. */
  21587. QCPDataSelection QCPStatisticalBox::selectTestRect(const QRectF &rect, bool onlySelectable) const
  21588. {
  21589. QCPDataSelection result;
  21590. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  21591. return result;
  21592. if (!mKeyAxis || !mValueAxis)
  21593. return result;
  21594. QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
  21595. getVisibleDataBounds(visibleBegin, visibleEnd);
  21596. for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  21597. {
  21598. if (rect.intersects(getQuartileBox(it)))
  21599. result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
  21600. }
  21601. result.simplify();
  21602. return result;
  21603. }
  21604. /*!
  21605. Implements a selectTest specific to this plottable's point geometry.
  21606. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  21607. point to \a pos.
  21608. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  21609. */
  21610. double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  21611. {
  21612. Q_UNUSED(details)
  21613. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  21614. return -1;
  21615. if (!mKeyAxis || !mValueAxis)
  21616. return -1;
  21617. if (mKeyAxis->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  21618. {
  21619. // get visible data range:
  21620. QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
  21621. QCPStatisticalBoxDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  21622. getVisibleDataBounds(visibleBegin, visibleEnd);
  21623. double minDistSqr = (std::numeric_limits<double>::max)();
  21624. for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  21625. {
  21626. if (getQuartileBox(it).contains(pos)) // quartile box
  21627. {
  21628. double currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
  21629. if (currentDistSqr < minDistSqr)
  21630. {
  21631. minDistSqr = currentDistSqr;
  21632. closestDataPoint = it;
  21633. }
  21634. } else // whiskers
  21635. {
  21636. const QVector<QLineF> whiskerBackbones = getWhiskerBackboneLines(it);
  21637. const QCPVector2D posVec(pos);
  21638. foreach (const QLineF &backbone, whiskerBackbones)
  21639. {
  21640. double currentDistSqr = posVec.distanceSquaredToLine(backbone);
  21641. if (currentDistSqr < minDistSqr)
  21642. {
  21643. minDistSqr = currentDistSqr;
  21644. closestDataPoint = it;
  21645. }
  21646. }
  21647. }
  21648. }
  21649. if (details)
  21650. {
  21651. int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
  21652. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  21653. }
  21654. return qSqrt(minDistSqr);
  21655. }
  21656. return -1;
  21657. }
  21658. /* inherits documentation from base class */
  21659. QCPRange QCPStatisticalBox::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  21660. {
  21661. QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain);
  21662. // determine exact range by including width of bars/flags:
  21663. if (foundRange)
  21664. {
  21665. if (inSignDomain != QCP::sdPositive || range.lower-mWidth*0.5 > 0)
  21666. range.lower -= mWidth*0.5;
  21667. if (inSignDomain != QCP::sdNegative || range.upper+mWidth*0.5 < 0)
  21668. range.upper += mWidth*0.5;
  21669. }
  21670. return range;
  21671. }
  21672. /* inherits documentation from base class */
  21673. QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  21674. {
  21675. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  21676. }
  21677. /* inherits documentation from base class */
  21678. void QCPStatisticalBox::draw(QCPPainter *painter)
  21679. {
  21680. if (mDataContainer->isEmpty()) return;
  21681. QCPAxis *keyAxis = mKeyAxis.data();
  21682. QCPAxis *valueAxis = mValueAxis.data();
  21683. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  21684. QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
  21685. getVisibleDataBounds(visibleBegin, visibleEnd);
  21686. // loop over and draw segments of unselected/selected data:
  21687. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  21688. getDataSegments(selectedSegments, unselectedSegments);
  21689. allSegments << unselectedSegments << selectedSegments;
  21690. for (int i=0; i<allSegments.size(); ++i)
  21691. {
  21692. bool isSelectedSegment = i >= unselectedSegments.size();
  21693. QCPStatisticalBoxDataContainer::const_iterator begin = visibleBegin;
  21694. QCPStatisticalBoxDataContainer::const_iterator end = visibleEnd;
  21695. mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
  21696. if (begin == end)
  21697. continue;
  21698. for (QCPStatisticalBoxDataContainer::const_iterator it=begin; it!=end; ++it)
  21699. {
  21700. // check data validity if flag set:
  21701. # ifdef QCUSTOMPLOT_CHECK_DATA
  21702. if (QCP::isInvalidData(it->key, it->minimum) ||
  21703. QCP::isInvalidData(it->lowerQuartile, it->median) ||
  21704. QCP::isInvalidData(it->upperQuartile, it->maximum))
  21705. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range has invalid data." << "Plottable name:" << name();
  21706. for (int i=0; i<it->outliers.size(); ++i)
  21707. if (QCP::isInvalidData(it->outliers.at(i)))
  21708. qDebug() << Q_FUNC_INFO << "Data point outlier at" << it->key << "of drawn range invalid." << "Plottable name:" << name();
  21709. # endif
  21710. if (isSelectedSegment && mSelectionDecorator)
  21711. {
  21712. mSelectionDecorator->applyPen(painter);
  21713. mSelectionDecorator->applyBrush(painter);
  21714. } else
  21715. {
  21716. painter->setPen(mPen);
  21717. painter->setBrush(mBrush);
  21718. }
  21719. QCPScatterStyle finalOutlierStyle = mOutlierStyle;
  21720. if (isSelectedSegment && mSelectionDecorator)
  21721. finalOutlierStyle = mSelectionDecorator->getFinalScatterStyle(mOutlierStyle);
  21722. drawStatisticalBox(painter, it, finalOutlierStyle);
  21723. }
  21724. }
  21725. // draw other selection decoration that isn't just line/scatter pens and brushes:
  21726. if (mSelectionDecorator)
  21727. mSelectionDecorator->drawDecoration(painter, selection());
  21728. }
  21729. /* inherits documentation from base class */
  21730. void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  21731. {
  21732. // draw filled rect:
  21733. applyDefaultAntialiasingHint(painter);
  21734. painter->setPen(mPen);
  21735. painter->setBrush(mBrush);
  21736. QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
  21737. r.moveCenter(rect.center());
  21738. painter->drawRect(r);
  21739. }
  21740. /*!
  21741. Draws the graphical representation of a single statistical box with the data given by the
  21742. iterator \a it with the provided \a painter.
  21743. If the statistical box has a set of outlier data points, they are drawn with \a outlierStyle.
  21744. \see getQuartileBox, getWhiskerBackboneLines, getWhiskerBarLines
  21745. */
  21746. void QCPStatisticalBox::drawStatisticalBox(QCPPainter *painter, QCPStatisticalBoxDataContainer::const_iterator it, const QCPScatterStyle &outlierStyle) const
  21747. {
  21748. // draw quartile box:
  21749. applyDefaultAntialiasingHint(painter);
  21750. const QRectF quartileBox = getQuartileBox(it);
  21751. painter->drawRect(quartileBox);
  21752. // draw median line with cliprect set to quartile box:
  21753. painter->save();
  21754. painter->setClipRect(quartileBox, Qt::IntersectClip);
  21755. painter->setPen(mMedianPen);
  21756. painter->drawLine(QLineF(coordsToPixels(it->key-mWidth*0.5, it->median), coordsToPixels(it->key+mWidth*0.5, it->median)));
  21757. painter->restore();
  21758. // draw whisker lines:
  21759. applyAntialiasingHint(painter, mWhiskerAntialiased, QCP::aePlottables);
  21760. painter->setPen(mWhiskerPen);
  21761. painter->drawLines(getWhiskerBackboneLines(it));
  21762. painter->setPen(mWhiskerBarPen);
  21763. painter->drawLines(getWhiskerBarLines(it));
  21764. // draw outliers:
  21765. applyScattersAntialiasingHint(painter);
  21766. outlierStyle.applyTo(painter, mPen);
  21767. for (int i=0; i<it->outliers.size(); ++i)
  21768. outlierStyle.drawShape(painter, coordsToPixels(it->key, it->outliers.at(i)));
  21769. }
  21770. /*! \internal
  21771. called by \ref draw to determine which data (key) range is visible at the current key axis range
  21772. setting, so only that needs to be processed. It also takes into account the bar width.
  21773. \a begin returns an iterator to the lowest data point that needs to be taken into account when
  21774. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  21775. lower may still be just outside the visible range.
  21776. \a end returns an iterator one higher than the highest visible data point. Same as before, \a end
  21777. may also lie just outside of the visible range.
  21778. if the plottable contains no data, both \a begin and \a end point to constEnd.
  21779. */
  21780. void QCPStatisticalBox::getVisibleDataBounds(QCPStatisticalBoxDataContainer::const_iterator &begin, QCPStatisticalBoxDataContainer::const_iterator &end) const
  21781. {
  21782. if (!mKeyAxis)
  21783. {
  21784. qDebug() << Q_FUNC_INFO << "invalid key axis";
  21785. begin = mDataContainer->constEnd();
  21786. end = mDataContainer->constEnd();
  21787. return;
  21788. }
  21789. begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of box to include partially visible data points
  21790. end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of box to include partially visible data points
  21791. }
  21792. /*! \internal
  21793. Returns the box in plot coordinates (keys in x, values in y of the returned rect) that covers the
  21794. value range from the lower to the upper quartile, of the data given by \a it.
  21795. \see drawStatisticalBox, getWhiskerBackboneLines, getWhiskerBarLines
  21796. */
  21797. QRectF QCPStatisticalBox::getQuartileBox(QCPStatisticalBoxDataContainer::const_iterator it) const
  21798. {
  21799. QRectF result;
  21800. result.setTopLeft(coordsToPixels(it->key-mWidth*0.5, it->upperQuartile));
  21801. result.setBottomRight(coordsToPixels(it->key+mWidth*0.5, it->lowerQuartile));
  21802. return result;
  21803. }
  21804. /*! \internal
  21805. Returns the whisker backbones (keys in x, values in y of the returned lines) that cover the value
  21806. range from the minimum to the lower quartile, and from the upper quartile to the maximum of the
  21807. data given by \a it.
  21808. \see drawStatisticalBox, getQuartileBox, getWhiskerBarLines
  21809. */
  21810. QVector<QLineF> QCPStatisticalBox::getWhiskerBackboneLines(QCPStatisticalBoxDataContainer::const_iterator it) const
  21811. {
  21812. QVector<QLineF> result(2);
  21813. result[0].setPoints(coordsToPixels(it->key, it->lowerQuartile), coordsToPixels(it->key, it->minimum)); // min backbone
  21814. result[1].setPoints(coordsToPixels(it->key, it->upperQuartile), coordsToPixels(it->key, it->maximum)); // max backbone
  21815. return result;
  21816. }
  21817. /*! \internal
  21818. Returns the whisker bars (keys in x, values in y of the returned lines) that are placed at the
  21819. end of the whisker backbones, at the minimum and maximum of the data given by \a it.
  21820. \see drawStatisticalBox, getQuartileBox, getWhiskerBackboneLines
  21821. */
  21822. QVector<QLineF> QCPStatisticalBox::getWhiskerBarLines(QCPStatisticalBoxDataContainer::const_iterator it) const
  21823. {
  21824. QVector<QLineF> result(2);
  21825. result[0].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->minimum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->minimum)); // min bar
  21826. result[1].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->maximum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->maximum)); // max bar
  21827. return result;
  21828. }
  21829. /* end of 'src/plottables/plottable-statisticalbox.cpp' */
  21830. /* including file 'src/plottables/plottable-colormap.cpp' */
  21831. /* modified 2021-03-29T02:30:44, size 48149 */
  21832. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21833. //////////////////// QCPColorMapData
  21834. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21835. /*! \class QCPColorMapData
  21836. \brief Holds the two-dimensional data of a QCPColorMap plottable.
  21837. This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref
  21838. QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a
  21839. color, depending on the value.
  21840. The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize).
  21841. Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref
  21842. setKeyRange, \ref setValueRange).
  21843. The data cells can be accessed in two ways: They can be directly addressed by an integer index
  21844. with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot
  21845. coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are
  21846. provided by the functions \ref coordToCell and \ref cellToCoord.
  21847. A \ref QCPColorMapData also holds an on-demand two-dimensional array of alpha values which (if
  21848. allocated) has the same size as the data map. It can be accessed via \ref setAlpha, \ref
  21849. fillAlpha and \ref clearAlpha. The memory for the alpha map is only allocated if needed, i.e. on
  21850. the first call of \ref setAlpha. \ref clearAlpha restores full opacity and frees the alpha map.
  21851. This class also buffers the minimum and maximum values that are in the data set, to provide
  21852. QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value
  21853. that is greater than the current maximum increases this maximum to the new value. However,
  21854. setting the cell that currently holds the maximum value to a smaller value doesn't decrease the
  21855. maximum again, because finding the true new maximum would require going through the entire data
  21856. array, which might be time consuming. The same holds for the data minimum. This functionality is
  21857. given by \ref recalculateDataBounds, such that you can decide when it is sensible to find the
  21858. true current minimum and maximum. The method QCPColorMap::rescaleDataRange offers a convenience
  21859. parameter \a recalculateDataBounds which may be set to true to automatically call \ref
  21860. recalculateDataBounds internally.
  21861. */
  21862. /* start of documentation of inline functions */
  21863. /*! \fn bool QCPColorMapData::isEmpty() const
  21864. Returns whether this instance carries no data. This is equivalent to having a size where at least
  21865. one of the dimensions is 0 (see \ref setSize).
  21866. */
  21867. /* end of documentation of inline functions */
  21868. /*!
  21869. Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction
  21870. and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap
  21871. at the coordinates \a keyRange and \a valueRange.
  21872. \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange
  21873. */
  21874. QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) :
  21875. mKeySize(0),
  21876. mValueSize(0),
  21877. mKeyRange(keyRange),
  21878. mValueRange(valueRange),
  21879. mIsEmpty(true),
  21880. mData(nullptr),
  21881. mAlpha(nullptr),
  21882. mDataModified(true)
  21883. {
  21884. setSize(keySize, valueSize);
  21885. fill(0);
  21886. }
  21887. QCPColorMapData::~QCPColorMapData()
  21888. {
  21889. delete[] mData;
  21890. delete[] mAlpha;
  21891. }
  21892. /*!
  21893. Constructs a new QCPColorMapData instance copying the data and range of \a other.
  21894. */
  21895. QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) :
  21896. mKeySize(0),
  21897. mValueSize(0),
  21898. mIsEmpty(true),
  21899. mData(nullptr),
  21900. mAlpha(nullptr),
  21901. mDataModified(true)
  21902. {
  21903. *this = other;
  21904. }
  21905. /*!
  21906. Overwrites this color map data instance with the data stored in \a other. The alpha map state is
  21907. transferred, too.
  21908. */
  21909. QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other)
  21910. {
  21911. if (&other != this)
  21912. {
  21913. const int keySize = other.keySize();
  21914. const int valueSize = other.valueSize();
  21915. if (!other.mAlpha && mAlpha)
  21916. clearAlpha();
  21917. setSize(keySize, valueSize);
  21918. if (other.mAlpha && !mAlpha)
  21919. createAlpha(false);
  21920. setRange(other.keyRange(), other.valueRange());
  21921. if (!isEmpty())
  21922. {
  21923. memcpy(mData, other.mData, sizeof(mData[0])*size_t(keySize*valueSize));
  21924. if (mAlpha)
  21925. memcpy(mAlpha, other.mAlpha, sizeof(mAlpha[0])*size_t(keySize*valueSize));
  21926. }
  21927. mDataBounds = other.mDataBounds;
  21928. mDataModified = true;
  21929. }
  21930. return *this;
  21931. }
  21932. /* undocumented getter */
  21933. double QCPColorMapData::data(double key, double value)
  21934. {
  21935. int keyCell = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5 );
  21936. int valueCell = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 );
  21937. if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
  21938. return mData[valueCell*mKeySize + keyCell];
  21939. else
  21940. return 0;
  21941. }
  21942. /* undocumented getter */
  21943. double QCPColorMapData::cell(int keyIndex, int valueIndex)
  21944. {
  21945. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  21946. return mData[valueIndex*mKeySize + keyIndex];
  21947. else
  21948. return 0;
  21949. }
  21950. /*!
  21951. Returns the alpha map value of the cell with the indices \a keyIndex and \a valueIndex.
  21952. If this color map data doesn't have an alpha map (because \ref setAlpha was never called after
  21953. creation or after a call to \ref clearAlpha), returns 255, which corresponds to full opacity.
  21954. \see setAlpha
  21955. */
  21956. unsigned char QCPColorMapData::alpha(int keyIndex, int valueIndex)
  21957. {
  21958. if (mAlpha && keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  21959. return mAlpha[valueIndex*mKeySize + keyIndex];
  21960. else
  21961. return 255;
  21962. }
  21963. /*!
  21964. Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in
  21965. the value dimension.
  21966. The current data is discarded and the map cells are set to 0, unless the map had already the
  21967. requested size.
  21968. Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref
  21969. isEmpty returns true.
  21970. \see setRange, setKeySize, setValueSize
  21971. */
  21972. void QCPColorMapData::setSize(int keySize, int valueSize)
  21973. {
  21974. if (keySize != mKeySize || valueSize != mValueSize)
  21975. {
  21976. mKeySize = keySize;
  21977. mValueSize = valueSize;
  21978. delete[] mData;
  21979. mIsEmpty = mKeySize == 0 || mValueSize == 0;
  21980. if (!mIsEmpty)
  21981. {
  21982. #ifdef __EXCEPTIONS
  21983. try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message
  21984. #endif
  21985. mData = new double[size_t(mKeySize*mValueSize)];
  21986. #ifdef __EXCEPTIONS
  21987. } catch (...) { mData = nullptr; }
  21988. #endif
  21989. if (mData)
  21990. fill(0);
  21991. else
  21992. qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize;
  21993. } else
  21994. mData = nullptr;
  21995. if (mAlpha) // if we had an alpha map, recreate it with new size
  21996. createAlpha();
  21997. mDataModified = true;
  21998. }
  21999. }
  22000. /*!
  22001. Resizes the data array to have \a keySize cells in the key dimension.
  22002. The current data is discarded and the map cells are set to 0, unless the map had already the
  22003. requested size.
  22004. Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true.
  22005. \see setKeyRange, setSize, setValueSize
  22006. */
  22007. void QCPColorMapData::setKeySize(int keySize)
  22008. {
  22009. setSize(keySize, mValueSize);
  22010. }
  22011. /*!
  22012. Resizes the data array to have \a valueSize cells in the value dimension.
  22013. The current data is discarded and the map cells are set to 0, unless the map had already the
  22014. requested size.
  22015. Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true.
  22016. \see setValueRange, setSize, setKeySize
  22017. */
  22018. void QCPColorMapData::setValueSize(int valueSize)
  22019. {
  22020. setSize(mKeySize, valueSize);
  22021. }
  22022. /*!
  22023. Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area
  22024. covered by the color map in plot coordinates.
  22025. The outer cells will be centered on the range boundaries given to this function. For example, if
  22026. the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
  22027. be cells centered on the key coordinates 2, 2.5 and 3.
  22028. \see setSize
  22029. */
  22030. void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange)
  22031. {
  22032. setKeyRange(keyRange);
  22033. setValueRange(valueRange);
  22034. }
  22035. /*!
  22036. Sets the coordinate range the data shall be distributed over in the key dimension. Together with
  22037. the value range, This defines the rectangular area covered by the color map in plot coordinates.
  22038. The outer cells will be centered on the range boundaries given to this function. For example, if
  22039. the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
  22040. be cells centered on the key coordinates 2, 2.5 and 3.
  22041. \see setRange, setValueRange, setSize
  22042. */
  22043. void QCPColorMapData::setKeyRange(const QCPRange &keyRange)
  22044. {
  22045. mKeyRange = keyRange;
  22046. }
  22047. /*!
  22048. Sets the coordinate range the data shall be distributed over in the value dimension. Together with
  22049. the key range, This defines the rectangular area covered by the color map in plot coordinates.
  22050. The outer cells will be centered on the range boundaries given to this function. For example, if
  22051. the value size (\ref setValueSize) is 3 and \a valueRange is set to <tt>QCPRange(2, 3)</tt> there
  22052. will be cells centered on the value coordinates 2, 2.5 and 3.
  22053. \see setRange, setKeyRange, setSize
  22054. */
  22055. void QCPColorMapData::setValueRange(const QCPRange &valueRange)
  22056. {
  22057. mValueRange = valueRange;
  22058. }
  22059. /*!
  22060. Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a
  22061. z.
  22062. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  22063. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  22064. you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
  22065. determine the cell index. Rather directly access the cell index with \ref
  22066. QCPColorMapData::setCell.
  22067. \see setCell, setRange
  22068. */
  22069. void QCPColorMapData::setData(double key, double value, double z)
  22070. {
  22071. int keyCell = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5 );
  22072. int valueCell = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 );
  22073. if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
  22074. {
  22075. mData[valueCell*mKeySize + keyCell] = z;
  22076. if (z < mDataBounds.lower)
  22077. mDataBounds.lower = z;
  22078. if (z > mDataBounds.upper)
  22079. mDataBounds.upper = z;
  22080. mDataModified = true;
  22081. }
  22082. }
  22083. /*!
  22084. Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices
  22085. enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see
  22086. \ref setSize).
  22087. In the standard plot configuration (horizontal key axis and vertical value axis, both not
  22088. range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with
  22089. indices (keySize-1, valueSize-1) is in the top right corner of the color map.
  22090. \see setData, setSize
  22091. */
  22092. void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z)
  22093. {
  22094. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  22095. {
  22096. mData[valueIndex*mKeySize + keyIndex] = z;
  22097. if (z < mDataBounds.lower)
  22098. mDataBounds.lower = z;
  22099. if (z > mDataBounds.upper)
  22100. mDataBounds.upper = z;
  22101. mDataModified = true;
  22102. } else
  22103. qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex;
  22104. }
  22105. /*!
  22106. Sets the alpha of the color map cell given by \a keyIndex and \a valueIndex to \a alpha. A value
  22107. of 0 for \a alpha results in a fully transparent cell, and a value of 255 results in a fully
  22108. opaque cell.
  22109. If an alpha map doesn't exist yet for this color map data, it will be created here. If you wish
  22110. to restore full opacity and free any allocated memory of the alpha map, call \ref clearAlpha.
  22111. Note that the cell-wise alpha which can be configured here is independent of any alpha configured
  22112. in the color map's gradient (\ref QCPColorGradient). If a cell is affected both by the cell-wise
  22113. and gradient alpha, the alpha values will be blended accordingly during rendering of the color
  22114. map.
  22115. \see fillAlpha, clearAlpha
  22116. */
  22117. void QCPColorMapData::setAlpha(int keyIndex, int valueIndex, unsigned char alpha)
  22118. {
  22119. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  22120. {
  22121. if (mAlpha || createAlpha())
  22122. {
  22123. mAlpha[valueIndex*mKeySize + keyIndex] = alpha;
  22124. mDataModified = true;
  22125. }
  22126. } else
  22127. qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex;
  22128. }
  22129. /*!
  22130. Goes through the data and updates the buffered minimum and maximum data values.
  22131. Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange
  22132. and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten
  22133. with a smaller or larger value respectively, since the buffered maximum/minimum values have been
  22134. updated the last time. Why this is the case is explained in the class description (\ref
  22135. QCPColorMapData).
  22136. Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a
  22137. recalculateDataBounds for convenience. Setting this to true will call this method for you, before
  22138. doing the rescale.
  22139. */
  22140. void QCPColorMapData::recalculateDataBounds()
  22141. {
  22142. if (mKeySize > 0 && mValueSize > 0)
  22143. {
  22144. double minHeight = mData[0];
  22145. double maxHeight = mData[0];
  22146. const int dataCount = mValueSize*mKeySize;
  22147. for (int i=0; i<dataCount; ++i)
  22148. {
  22149. if (mData[i] > maxHeight)
  22150. maxHeight = mData[i];
  22151. if (mData[i] < minHeight)
  22152. minHeight = mData[i];
  22153. }
  22154. mDataBounds.lower = minHeight;
  22155. mDataBounds.upper = maxHeight;
  22156. }
  22157. }
  22158. /*!
  22159. Frees the internal data memory.
  22160. This is equivalent to calling \ref setSize "setSize(0, 0)".
  22161. */
  22162. void QCPColorMapData::clear()
  22163. {
  22164. setSize(0, 0);
  22165. }
  22166. /*!
  22167. Frees the internal alpha map. The color map will have full opacity again.
  22168. */
  22169. void QCPColorMapData::clearAlpha()
  22170. {
  22171. if (mAlpha)
  22172. {
  22173. delete[] mAlpha;
  22174. mAlpha = nullptr;
  22175. mDataModified = true;
  22176. }
  22177. }
  22178. /*!
  22179. Sets all cells to the value \a z.
  22180. */
  22181. void QCPColorMapData::fill(double z)
  22182. {
  22183. const int dataCount = mValueSize*mKeySize;
  22184. for (int i=0; i<dataCount; ++i)
  22185. mData[i] = z;
  22186. mDataBounds = QCPRange(z, z);
  22187. mDataModified = true;
  22188. }
  22189. /*!
  22190. Sets the opacity of all color map cells to \a alpha. A value of 0 for \a alpha results in a fully
  22191. transparent color map, and a value of 255 results in a fully opaque color map.
  22192. If you wish to restore opacity to 100% and free any used memory for the alpha map, rather use
  22193. \ref clearAlpha.
  22194. \see setAlpha
  22195. */
  22196. void QCPColorMapData::fillAlpha(unsigned char alpha)
  22197. {
  22198. if (mAlpha || createAlpha(false))
  22199. {
  22200. const int dataCount = mValueSize*mKeySize;
  22201. for (int i=0; i<dataCount; ++i)
  22202. mAlpha[i] = alpha;
  22203. mDataModified = true;
  22204. }
  22205. }
  22206. /*!
  22207. Transforms plot coordinates given by \a key and \a value to cell indices of this QCPColorMapData
  22208. instance. The resulting cell indices are returned via the output parameters \a keyIndex and \a
  22209. valueIndex.
  22210. The retrieved key/value cell indices can then be used for example with \ref setCell.
  22211. If you are only interested in a key or value index, you may pass \c nullptr as \a valueIndex or
  22212. \a keyIndex.
  22213. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  22214. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  22215. you shouldn't use the \ref QCPColorMapData::coordToCell method as it uses a linear transformation to
  22216. determine the cell index.
  22217. \see cellToCoord, QCPAxis::coordToPixel
  22218. */
  22219. void QCPColorMapData::coordToCell(double key, double value, int *keyIndex, int *valueIndex) const
  22220. {
  22221. if (keyIndex)
  22222. *keyIndex = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5 );
  22223. if (valueIndex)
  22224. *valueIndex = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 );
  22225. }
  22226. /*!
  22227. Transforms cell indices given by \a keyIndex and \a valueIndex to cell indices of this QCPColorMapData
  22228. instance. The resulting coordinates are returned via the output parameters \a key and \a
  22229. value.
  22230. If you are only interested in a key or value coordinate, you may pass \c nullptr as \a key or \a
  22231. value.
  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::cellToCoord method as it uses a linear transformation to
  22235. determine the cell index.
  22236. \see coordToCell, QCPAxis::pixelToCoord
  22237. */
  22238. void QCPColorMapData::cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const
  22239. {
  22240. if (key)
  22241. *key = keyIndex/double(mKeySize-1)*(mKeyRange.upper-mKeyRange.lower)+mKeyRange.lower;
  22242. if (value)
  22243. *value = valueIndex/double(mValueSize-1)*(mValueRange.upper-mValueRange.lower)+mValueRange.lower;
  22244. }
  22245. /*! \internal
  22246. Allocates the internal alpha map with the current data map key/value size and, if \a
  22247. initializeOpaque is true, initializes all values to 255. If \a initializeOpaque is false, the
  22248. values are not initialized at all. In this case, the alpha map should be initialized manually,
  22249. e.g. with \ref fillAlpha.
  22250. If an alpha map exists already, it is deleted first. If this color map is empty (has either key
  22251. or value size zero, see \ref isEmpty), the alpha map is cleared.
  22252. The return value indicates the existence of the alpha map after the call. So this method returns
  22253. true if the data map isn't empty and an alpha map was successfully allocated.
  22254. */
  22255. bool QCPColorMapData::createAlpha(bool initializeOpaque)
  22256. {
  22257. clearAlpha();
  22258. if (isEmpty())
  22259. return false;
  22260. #ifdef __EXCEPTIONS
  22261. try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message
  22262. #endif
  22263. mAlpha = new unsigned char[size_t(mKeySize*mValueSize)];
  22264. #ifdef __EXCEPTIONS
  22265. } catch (...) { mAlpha = nullptr; }
  22266. #endif
  22267. if (mAlpha)
  22268. {
  22269. if (initializeOpaque)
  22270. fillAlpha(255);
  22271. return true;
  22272. } else
  22273. {
  22274. qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize;
  22275. return false;
  22276. }
  22277. }
  22278. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22279. //////////////////// QCPColorMap
  22280. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22281. /*! \class QCPColorMap
  22282. \brief A plottable representing a two-dimensional color map in a plot.
  22283. \image html QCPColorMap.png
  22284. The data is stored in the class \ref QCPColorMapData, which can be accessed via the data()
  22285. method.
  22286. A color map has three dimensions to represent a data point: The \a key dimension, the \a value
  22287. dimension and the \a data dimension. As with other plottables such as graphs, \a key and \a value
  22288. correspond to two orthogonal axes on the QCustomPlot surface that you specify in the QCPColorMap
  22289. constructor. The \a data dimension however is encoded as the color of the point at (\a key, \a
  22290. value).
  22291. Set the number of points (or \a cells) in the key/value dimension via \ref
  22292. QCPColorMapData::setSize. The plot coordinate range over which these points will be displayed is
  22293. specified via \ref QCPColorMapData::setRange. The first cell will be centered on the lower range
  22294. boundary and the last cell will be centered on the upper range boundary. The data can be set by
  22295. either accessing the cells directly with QCPColorMapData::setCell or by addressing the cells via
  22296. their plot coordinates with \ref QCPColorMapData::setData. If possible, you should prefer
  22297. setCell, since it doesn't need to do any coordinate transformation and thus performs a bit
  22298. better.
  22299. The cell with index (0, 0) is at the bottom left, if the color map uses normal (i.e. not reversed)
  22300. key and value axes.
  22301. To show the user which colors correspond to which \a data values, a \ref QCPColorScale is
  22302. typically placed to the right of the axis rect. See the documentation there for details on how to
  22303. add and use a color scale.
  22304. \section qcpcolormap-appearance Changing the appearance
  22305. Most important to the appearance is the color gradient, which can be specified via \ref
  22306. setGradient. See the documentation of \ref QCPColorGradient for details on configuring a color
  22307. gradient.
  22308. The \a data range that is mapped to the colors of the gradient can be specified with \ref
  22309. setDataRange. To make the data range encompass the whole data set minimum to maximum, call \ref
  22310. rescaleDataRange. If your data may contain NaN values, use \ref QCPColorGradient::setNanHandling
  22311. to define how they are displayed.
  22312. \section qcpcolormap-transparency Transparency
  22313. Transparency in color maps can be achieved by two mechanisms. On one hand, you can specify alpha
  22314. values for color stops of the \ref QCPColorGradient, via the regular QColor interface. This will
  22315. cause the color map data which gets mapped to colors around those color stops to appear with the
  22316. accordingly interpolated transparency.
  22317. On the other hand you can also directly apply an alpha value to each cell independent of its
  22318. data, by using the alpha map feature of \ref QCPColorMapData. The relevant methods are \ref
  22319. QCPColorMapData::setAlpha, QCPColorMapData::fillAlpha and \ref QCPColorMapData::clearAlpha().
  22320. The two transparencies will be joined together in the plot and otherwise not interfere with each
  22321. other. They are mixed in a multiplicative matter, so an alpha of e.g. 50% (128/255) in both modes
  22322. simultaneously, will result in a total transparency of 25% (64/255).
  22323. \section qcpcolormap-usage Usage
  22324. Like all data representing objects in QCustomPlot, the QCPColorMap is a plottable
  22325. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  22326. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  22327. Usually, you first create an instance:
  22328. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-1
  22329. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  22330. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  22331. The newly created plottable can be modified, e.g.:
  22332. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-2
  22333. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  22334. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  22335. you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
  22336. determine the cell index. Rather directly access the cell index with \ref
  22337. QCPColorMapData::setCell.
  22338. */
  22339. /* start documentation of inline functions */
  22340. /*! \fn QCPColorMapData *QCPColorMap::data() const
  22341. Returns a pointer to the internal data storage of type \ref QCPColorMapData. Access this to
  22342. modify data points (cells) and the color map key/value range.
  22343. \see setData
  22344. */
  22345. /* end documentation of inline functions */
  22346. /* start documentation of signals */
  22347. /*! \fn void QCPColorMap::dataRangeChanged(const QCPRange &newRange);
  22348. This signal is emitted when the data range changes.
  22349. \see setDataRange
  22350. */
  22351. /*! \fn void QCPColorMap::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
  22352. This signal is emitted when the data scale type changes.
  22353. \see setDataScaleType
  22354. */
  22355. /*! \fn void QCPColorMap::gradientChanged(const QCPColorGradient &newGradient);
  22356. This signal is emitted when the gradient changes.
  22357. \see setGradient
  22358. */
  22359. /* end documentation of signals */
  22360. /*!
  22361. Constructs a color map with the specified \a keyAxis and \a valueAxis.
  22362. The created QCPColorMap is automatically registered with the QCustomPlot instance inferred from
  22363. \a keyAxis. This QCustomPlot instance takes ownership of the QCPColorMap, so do not delete it
  22364. manually but use QCustomPlot::removePlottable() instead.
  22365. */
  22366. QCPColorMap::QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  22367. QCPAbstractPlottable(keyAxis, valueAxis),
  22368. mDataScaleType(QCPAxis::stLinear),
  22369. mMapData(new QCPColorMapData(10, 10, QCPRange(0, 5), QCPRange(0, 5))),
  22370. mGradient(QCPColorGradient::gpCold),
  22371. mInterpolate(true),
  22372. mTightBoundary(false),
  22373. mMapImageInvalidated(true)
  22374. {
  22375. }
  22376. QCPColorMap::~QCPColorMap()
  22377. {
  22378. delete mMapData;
  22379. }
  22380. /*!
  22381. Replaces the current \ref data with the provided \a data.
  22382. If \a copy is set to true, the \a data object will only be copied. if false, the color map
  22383. takes ownership of the passed data and replaces the internal data pointer with it. This is
  22384. significantly faster than copying for large datasets.
  22385. */
  22386. void QCPColorMap::setData(QCPColorMapData *data, bool copy)
  22387. {
  22388. if (mMapData == data)
  22389. {
  22390. qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data);
  22391. return;
  22392. }
  22393. if (copy)
  22394. {
  22395. *mMapData = *data;
  22396. } else
  22397. {
  22398. delete mMapData;
  22399. mMapData = data;
  22400. }
  22401. mMapImageInvalidated = true;
  22402. }
  22403. /*!
  22404. Sets the data range of this color map to \a dataRange. The data range defines which data values
  22405. are mapped to the color gradient.
  22406. To make the data range span the full range of the data set, use \ref rescaleDataRange.
  22407. \see QCPColorScale::setDataRange
  22408. */
  22409. void QCPColorMap::setDataRange(const QCPRange &dataRange)
  22410. {
  22411. if (!QCPRange::validRange(dataRange)) return;
  22412. if (!qFuzzyCompare(mDataRange.lower, dataRange.lower) || !qFuzzyCompare(mDataRange.upper, dataRange.upper))
  22413. {
  22414. if (mDataScaleType == QCPAxis::stLogarithmic)
  22415. mDataRange = dataRange.sanitizedForLogScale();
  22416. else
  22417. mDataRange = dataRange.sanitizedForLinScale();
  22418. mMapImageInvalidated = true;
  22419. emit dataRangeChanged(mDataRange);
  22420. }
  22421. }
  22422. /*!
  22423. Sets whether the data is correlated with the color gradient linearly or logarithmically.
  22424. \see QCPColorScale::setDataScaleType
  22425. */
  22426. void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType)
  22427. {
  22428. if (mDataScaleType != scaleType)
  22429. {
  22430. mDataScaleType = scaleType;
  22431. mMapImageInvalidated = true;
  22432. emit dataScaleTypeChanged(mDataScaleType);
  22433. if (mDataScaleType == QCPAxis::stLogarithmic)
  22434. setDataRange(mDataRange.sanitizedForLogScale());
  22435. }
  22436. }
  22437. /*!
  22438. Sets the color gradient that is used to represent the data. For more details on how to create an
  22439. own gradient or use one of the preset gradients, see \ref QCPColorGradient.
  22440. The colors defined by the gradient will be used to represent data values in the currently set
  22441. data range, see \ref setDataRange. Data points that are outside this data range will either be
  22442. colored uniformly with the respective gradient boundary color, or the gradient will repeat,
  22443. depending on \ref QCPColorGradient::setPeriodic.
  22444. \see QCPColorScale::setGradient
  22445. */
  22446. void QCPColorMap::setGradient(const QCPColorGradient &gradient)
  22447. {
  22448. if (mGradient != gradient)
  22449. {
  22450. mGradient = gradient;
  22451. mMapImageInvalidated = true;
  22452. emit gradientChanged(mGradient);
  22453. }
  22454. }
  22455. /*!
  22456. Sets whether the color map image shall use bicubic interpolation when displaying the color map
  22457. shrinked or expanded, and not at a 1:1 pixel-to-data scale.
  22458. \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled"
  22459. */
  22460. void QCPColorMap::setInterpolate(bool enabled)
  22461. {
  22462. mInterpolate = enabled;
  22463. mMapImageInvalidated = true; // because oversampling factors might need to change
  22464. }
  22465. /*!
  22466. Sets whether the outer most data rows and columns are clipped to the specified key and value
  22467. range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange).
  22468. if \a enabled is set to false, the data points at the border of the color map are drawn with the
  22469. same width and height as all other data points. Since the data points are represented by
  22470. rectangles of one color centered on the data coordinate, this means that the shown color map
  22471. extends by half a data point over the specified key/value range in each direction.
  22472. \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled"
  22473. */
  22474. void QCPColorMap::setTightBoundary(bool enabled)
  22475. {
  22476. mTightBoundary = enabled;
  22477. }
  22478. /*!
  22479. Associates the color scale \a colorScale with this color map.
  22480. This means that both the color scale and the color map synchronize their gradient, data range and
  22481. data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps
  22482. can be associated with one single color scale. This causes the color maps to also synchronize
  22483. those properties, via the mutual color scale.
  22484. This function causes the color map to adopt the current color gradient, data range and data scale
  22485. type of \a colorScale. After this call, you may change these properties at either the color map
  22486. or the color scale, and the setting will be applied to both.
  22487. Pass \c nullptr as \a colorScale to disconnect the color scale from this color map again.
  22488. */
  22489. void QCPColorMap::setColorScale(QCPColorScale *colorScale)
  22490. {
  22491. if (mColorScale) // unconnect signals from old color scale
  22492. {
  22493. disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
  22494. disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
  22495. disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
  22496. disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  22497. disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
  22498. disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  22499. }
  22500. mColorScale = colorScale;
  22501. if (mColorScale) // connect signals to new color scale
  22502. {
  22503. setGradient(mColorScale.data()->gradient());
  22504. setDataRange(mColorScale.data()->dataRange());
  22505. setDataScaleType(mColorScale.data()->dataScaleType());
  22506. connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
  22507. connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
  22508. connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
  22509. connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  22510. connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
  22511. connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  22512. }
  22513. }
  22514. /*!
  22515. Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the
  22516. current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods,
  22517. only for the third data dimension of the color map.
  22518. The minimum and maximum values of the data set are buffered in the internal QCPColorMapData
  22519. instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref
  22520. QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For
  22521. performance reasons, however, they are only updated in an expanding fashion. So the buffered
  22522. maximum can only increase and the buffered minimum can only decrease. In consequence, changes to
  22523. the data that actually lower the maximum of the data set (by overwriting the cell holding the
  22524. current maximum with a smaller value), aren't recognized and the buffered maximum overestimates
  22525. the true maximum of the data set. The same happens for the buffered minimum. To recalculate the
  22526. true minimum and maximum by explicitly looking at each cell, the method
  22527. QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a
  22528. recalculateDataBounds calls this method before setting the data range to the buffered minimum and
  22529. maximum.
  22530. \see setDataRange
  22531. */
  22532. void QCPColorMap::rescaleDataRange(bool recalculateDataBounds)
  22533. {
  22534. if (recalculateDataBounds)
  22535. mMapData->recalculateDataBounds();
  22536. setDataRange(mMapData->dataBounds());
  22537. }
  22538. /*!
  22539. Takes the current appearance of the color map and updates the legend icon, which is used to
  22540. represent this color map in the legend (see \ref QCPLegend).
  22541. The \a transformMode specifies whether the rescaling is done by a faster, low quality image
  22542. scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm
  22543. (Qt::SmoothTransformation).
  22544. The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to
  22545. the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured
  22546. legend icon size, the thumb will be rescaled during drawing of the legend item.
  22547. \see setDataRange
  22548. */
  22549. void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize)
  22550. {
  22551. if (mMapImage.isNull() && !data()->isEmpty())
  22552. updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet)
  22553. if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again
  22554. {
  22555. bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
  22556. bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
  22557. mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode);
  22558. }
  22559. }
  22560. /* inherits documentation from base class */
  22561. double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  22562. {
  22563. Q_UNUSED(details)
  22564. if ((onlySelectable && mSelectable == QCP::stNone) || mMapData->isEmpty())
  22565. return -1;
  22566. if (!mKeyAxis || !mValueAxis)
  22567. return -1;
  22568. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  22569. {
  22570. double posKey, posValue;
  22571. pixelsToCoords(pos, posKey, posValue);
  22572. if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue))
  22573. {
  22574. if (details)
  22575. details->setValue(QCPDataSelection(QCPDataRange(0, 1))); // temporary solution, to facilitate whole-plottable selection. Replace in future version with segmented 2D selection.
  22576. return mParentPlot->selectionTolerance()*0.99;
  22577. }
  22578. }
  22579. return -1;
  22580. }
  22581. /* inherits documentation from base class */
  22582. QCPRange QCPColorMap::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  22583. {
  22584. foundRange = true;
  22585. QCPRange result = mMapData->keyRange();
  22586. result.normalize();
  22587. if (inSignDomain == QCP::sdPositive)
  22588. {
  22589. if (result.lower <= 0 && result.upper > 0)
  22590. result.lower = result.upper*1e-3;
  22591. else if (result.lower <= 0 && result.upper <= 0)
  22592. foundRange = false;
  22593. } else if (inSignDomain == QCP::sdNegative)
  22594. {
  22595. if (result.upper >= 0 && result.lower < 0)
  22596. result.upper = result.lower*1e-3;
  22597. else if (result.upper >= 0 && result.lower >= 0)
  22598. foundRange = false;
  22599. }
  22600. return result;
  22601. }
  22602. /* inherits documentation from base class */
  22603. QCPRange QCPColorMap::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  22604. {
  22605. if (inKeyRange != QCPRange())
  22606. {
  22607. if (mMapData->keyRange().upper < inKeyRange.lower || mMapData->keyRange().lower > inKeyRange.upper)
  22608. {
  22609. foundRange = false;
  22610. return {};
  22611. }
  22612. }
  22613. foundRange = true;
  22614. QCPRange result = mMapData->valueRange();
  22615. result.normalize();
  22616. if (inSignDomain == QCP::sdPositive)
  22617. {
  22618. if (result.lower <= 0 && result.upper > 0)
  22619. result.lower = result.upper*1e-3;
  22620. else if (result.lower <= 0 && result.upper <= 0)
  22621. foundRange = false;
  22622. } else if (inSignDomain == QCP::sdNegative)
  22623. {
  22624. if (result.upper >= 0 && result.lower < 0)
  22625. result.upper = result.lower*1e-3;
  22626. else if (result.upper >= 0 && result.lower >= 0)
  22627. foundRange = false;
  22628. }
  22629. return result;
  22630. }
  22631. /*! \internal
  22632. Updates the internal map image buffer by going through the internal \ref QCPColorMapData and
  22633. turning the data values into color pixels with \ref QCPColorGradient::colorize.
  22634. This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image
  22635. has been invalidated for a different reason (e.g. a change of the data range with \ref
  22636. setDataRange).
  22637. If the map cell count is low, the image created will be oversampled in order to avoid a
  22638. QPainter::drawImage bug which makes inner pixel boundaries jitter when stretch-drawing images
  22639. without smooth transform enabled. Accordingly, oversampling isn't performed if \ref
  22640. setInterpolate is true.
  22641. */
  22642. void QCPColorMap::updateMapImage()
  22643. {
  22644. QCPAxis *keyAxis = mKeyAxis.data();
  22645. if (!keyAxis) return;
  22646. if (mMapData->isEmpty()) return;
  22647. const QImage::Format format = QImage::Format_ARGB32_Premultiplied;
  22648. const int keySize = mMapData->keySize();
  22649. const int valueSize = mMapData->valueSize();
  22650. 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
  22651. 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
  22652. // resize mMapImage to correct dimensions including possible oversampling factors, according to key/value axes orientation:
  22653. if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.width() != keySize*keyOversamplingFactor || mMapImage.height() != valueSize*valueOversamplingFactor))
  22654. mMapImage = QImage(QSize(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor), format);
  22655. else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize*valueOversamplingFactor || mMapImage.height() != keySize*keyOversamplingFactor))
  22656. mMapImage = QImage(QSize(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor), format);
  22657. if (mMapImage.isNull())
  22658. {
  22659. qDebug() << Q_FUNC_INFO << "Couldn't create map image (possibly too large for memory)";
  22660. mMapImage = QImage(QSize(10, 10), format);
  22661. mMapImage.fill(Qt::black);
  22662. } else
  22663. {
  22664. QImage *localMapImage = &mMapImage; // this is the image on which the colorization operates. Either the final mMapImage, or if we need oversampling, mUndersampledMapImage
  22665. if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1)
  22666. {
  22667. // resize undersampled map image to actual key/value cell sizes:
  22668. if (keyAxis->orientation() == Qt::Horizontal && (mUndersampledMapImage.width() != keySize || mUndersampledMapImage.height() != valueSize))
  22669. mUndersampledMapImage = QImage(QSize(keySize, valueSize), format);
  22670. else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize))
  22671. mUndersampledMapImage = QImage(QSize(valueSize, keySize), format);
  22672. localMapImage = &mUndersampledMapImage; // make the colorization run on the undersampled image
  22673. } else if (!mUndersampledMapImage.isNull())
  22674. mUndersampledMapImage = QImage(); // don't need oversampling mechanism anymore (map size has changed) but mUndersampledMapImage still has nonzero size, free it
  22675. const double *rawData = mMapData->mData;
  22676. const unsigned char *rawAlpha = mMapData->mAlpha;
  22677. if (keyAxis->orientation() == Qt::Horizontal)
  22678. {
  22679. const int lineCount = valueSize;
  22680. const int rowCount = keySize;
  22681. for (int line=0; line<lineCount; ++line)
  22682. {
  22683. QRgb* pixels = reinterpret_cast<QRgb*>(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system)
  22684. if (rawAlpha)
  22685. mGradient.colorize(rawData+line*rowCount, rawAlpha+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic);
  22686. else
  22687. mGradient.colorize(rawData+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic);
  22688. }
  22689. } else // keyAxis->orientation() == Qt::Vertical
  22690. {
  22691. const int lineCount = keySize;
  22692. const int rowCount = valueSize;
  22693. for (int line=0; line<lineCount; ++line)
  22694. {
  22695. 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)
  22696. if (rawAlpha)
  22697. mGradient.colorize(rawData+line, rawAlpha+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic);
  22698. else
  22699. mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic);
  22700. }
  22701. }
  22702. if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1)
  22703. {
  22704. if (keyAxis->orientation() == Qt::Horizontal)
  22705. mMapImage = mUndersampledMapImage.scaled(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation);
  22706. else
  22707. mMapImage = mUndersampledMapImage.scaled(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation);
  22708. }
  22709. }
  22710. mMapData->mDataModified = false;
  22711. mMapImageInvalidated = false;
  22712. }
  22713. /* inherits documentation from base class */
  22714. void QCPColorMap::draw(QCPPainter *painter)
  22715. {
  22716. if (mMapData->isEmpty()) return;
  22717. if (!mKeyAxis || !mValueAxis) return;
  22718. applyDefaultAntialiasingHint(painter);
  22719. if (mMapData->mDataModified || mMapImageInvalidated)
  22720. updateMapImage();
  22721. // use buffer if painting vectorized (PDF):
  22722. const bool useBuffer = painter->modes().testFlag(QCPPainter::pmVectorized);
  22723. QCPPainter *localPainter = painter; // will be redirected to paint on mapBuffer if painting vectorized
  22724. QRectF mapBufferTarget; // the rect in absolute widget coordinates where the visible map portion/buffer will end up in
  22725. QPixmap mapBuffer;
  22726. if (useBuffer)
  22727. {
  22728. const double mapBufferPixelRatio = 3; // factor by which DPI is increased in embedded bitmaps
  22729. mapBufferTarget = painter->clipRegion().boundingRect();
  22730. mapBuffer = QPixmap((mapBufferTarget.size()*mapBufferPixelRatio).toSize());
  22731. mapBuffer.fill(Qt::transparent);
  22732. localPainter = new QCPPainter(&mapBuffer);
  22733. localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio);
  22734. localPainter->translate(-mapBufferTarget.topLeft());
  22735. }
  22736. QRectF imageRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
  22737. coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized();
  22738. // extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are centered on map range boundary):
  22739. double halfCellWidth = 0; // in pixels
  22740. double halfCellHeight = 0; // in pixels
  22741. if (keyAxis()->orientation() == Qt::Horizontal)
  22742. {
  22743. if (mMapData->keySize() > 1)
  22744. halfCellWidth = 0.5*imageRect.width()/double(mMapData->keySize()-1);
  22745. if (mMapData->valueSize() > 1)
  22746. halfCellHeight = 0.5*imageRect.height()/double(mMapData->valueSize()-1);
  22747. } else // keyAxis orientation is Qt::Vertical
  22748. {
  22749. if (mMapData->keySize() > 1)
  22750. halfCellHeight = 0.5*imageRect.height()/double(mMapData->keySize()-1);
  22751. if (mMapData->valueSize() > 1)
  22752. halfCellWidth = 0.5*imageRect.width()/double(mMapData->valueSize()-1);
  22753. }
  22754. imageRect.adjust(-halfCellWidth, -halfCellHeight, halfCellWidth, halfCellHeight);
  22755. const bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
  22756. const bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
  22757. const bool smoothBackup = localPainter->renderHints().testFlag(QPainter::SmoothPixmapTransform);
  22758. localPainter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate);
  22759. QRegion clipBackup;
  22760. if (mTightBoundary)
  22761. {
  22762. clipBackup = localPainter->clipRegion();
  22763. QRectF tightClipRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
  22764. coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized();
  22765. localPainter->setClipRect(tightClipRect, Qt::IntersectClip);
  22766. }
  22767. localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY));
  22768. if (mTightBoundary)
  22769. localPainter->setClipRegion(clipBackup);
  22770. localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup);
  22771. if (useBuffer) // localPainter painted to mapBuffer, so now draw buffer with original painter
  22772. {
  22773. delete localPainter;
  22774. painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer);
  22775. }
  22776. }
  22777. /* inherits documentation from base class */
  22778. void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  22779. {
  22780. applyDefaultAntialiasingHint(painter);
  22781. // draw map thumbnail:
  22782. if (!mLegendIcon.isNull())
  22783. {
  22784. QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation);
  22785. QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height());
  22786. iconRect.moveCenter(rect.center());
  22787. painter->drawPixmap(iconRect.topLeft(), scaledIcon);
  22788. }
  22789. /*
  22790. // draw frame:
  22791. painter->setBrush(Qt::NoBrush);
  22792. painter->setPen(Qt::black);
  22793. painter->drawRect(rect.adjusted(1, 1, 0, 0));
  22794. */
  22795. }
  22796. /* end of 'src/plottables/plottable-colormap.cpp' */
  22797. /* including file 'src/plottables/plottable-financial.cpp' */
  22798. /* modified 2021-03-29T02:30:44, size 42914 */
  22799. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22800. //////////////////// QCPFinancialData
  22801. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22802. /*! \class QCPFinancialData
  22803. \brief Holds the data of one single data point for QCPFinancial.
  22804. The stored data is:
  22805. \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
  22806. \li \a open: The opening value at the data point (this is the \a mainValue)
  22807. \li \a high: The high/maximum value at the data point
  22808. \li \a low: The low/minimum value at the data point
  22809. \li \a close: The closing value at the data point
  22810. The container for storing multiple data points is \ref QCPFinancialDataContainer. It is a typedef
  22811. for \ref QCPDataContainer with \ref QCPFinancialData as the DataType template parameter. See the
  22812. documentation there for an explanation regarding the data type's generic methods.
  22813. \see QCPFinancialDataContainer
  22814. */
  22815. /* start documentation of inline functions */
  22816. /*! \fn double QCPFinancialData::sortKey() const
  22817. Returns the \a key member of this data point.
  22818. For a general explanation of what this method is good for in the context of the data container,
  22819. see the documentation of \ref QCPDataContainer.
  22820. */
  22821. /*! \fn static QCPFinancialData QCPFinancialData::fromSortKey(double sortKey)
  22822. Returns a data point with the specified \a sortKey. All other members are set to zero.
  22823. For a general explanation of what this method is good for in the context of the data container,
  22824. see the documentation of \ref QCPDataContainer.
  22825. */
  22826. /*! \fn static static bool QCPFinancialData::sortKeyIsMainKey()
  22827. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  22828. this method returns true.
  22829. For a general explanation of what this method is good for in the context of the data container,
  22830. see the documentation of \ref QCPDataContainer.
  22831. */
  22832. /*! \fn double QCPFinancialData::mainKey() const
  22833. Returns the \a key member of this data point.
  22834. For a general explanation of what this method is good for in the context of the data container,
  22835. see the documentation of \ref QCPDataContainer.
  22836. */
  22837. /*! \fn double QCPFinancialData::mainValue() const
  22838. Returns the \a open member of this data point.
  22839. For a general explanation of what this method is good for in the context of the data container,
  22840. see the documentation of \ref QCPDataContainer.
  22841. */
  22842. /*! \fn QCPRange QCPFinancialData::valueRange() const
  22843. Returns a QCPRange spanning from the \a low to the \a high value of this data point.
  22844. For a general explanation of what this method is good for in the context of the data container,
  22845. see the documentation of \ref QCPDataContainer.
  22846. */
  22847. /* end documentation of inline functions */
  22848. /*!
  22849. Constructs a data point with key and all values set to zero.
  22850. */
  22851. QCPFinancialData::QCPFinancialData() :
  22852. key(0),
  22853. open(0),
  22854. high(0),
  22855. low(0),
  22856. close(0)
  22857. {
  22858. }
  22859. /*!
  22860. Constructs a data point with the specified \a key and OHLC values.
  22861. */
  22862. QCPFinancialData::QCPFinancialData(double key, double open, double high, double low, double close) :
  22863. key(key),
  22864. open(open),
  22865. high(high),
  22866. low(low),
  22867. close(close)
  22868. {
  22869. }
  22870. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22871. //////////////////// QCPFinancial
  22872. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22873. /*! \class QCPFinancial
  22874. \brief A plottable representing a financial stock chart
  22875. \image html QCPFinancial.png
  22876. This plottable represents time series data binned to certain intervals, mainly used for stock
  22877. charts. The two common representations OHLC (Open-High-Low-Close) bars and Candlesticks can be
  22878. set via \ref setChartStyle.
  22879. The data is passed via \ref setData as a set of open/high/low/close values at certain keys
  22880. (typically times). This means the data must be already binned appropriately. If data is only
  22881. available as a series of values (e.g. \a price against \a time), you can use the static
  22882. convenience function \ref timeSeriesToOhlc to generate binned OHLC-data which can then be passed
  22883. to \ref setData.
  22884. The width of the OHLC bars/candlesticks can be controlled with \ref setWidth and \ref
  22885. setWidthType. A typical choice is to set the width type to \ref wtPlotCoords (the default) and
  22886. the width to (or slightly less than) one time bin interval width.
  22887. \section qcpfinancial-appearance Changing the appearance
  22888. Charts can be either single- or two-colored (\ref setTwoColored). If set to be single-colored,
  22889. lines are drawn with the plottable's pen (\ref setPen) and fills with the brush (\ref setBrush).
  22890. If set to two-colored, positive changes of the value during an interval (\a close >= \a open) are
  22891. represented with a different pen and brush than negative changes (\a close < \a open). These can
  22892. be configured with \ref setPenPositive, \ref setPenNegative, \ref setBrushPositive, and \ref
  22893. setBrushNegative. In two-colored mode, the normal plottable pen/brush is ignored. Upon selection
  22894. however, the normal selected pen/brush (provided by the \ref selectionDecorator) is used,
  22895. irrespective of whether the chart is single- or two-colored.
  22896. \section qcpfinancial-usage Usage
  22897. Like all data representing objects in QCustomPlot, the QCPFinancial is a plottable
  22898. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  22899. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  22900. Usually, you first create an instance:
  22901. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-creation-1
  22902. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot
  22903. instance takes ownership of the plottable, so do not delete it manually but use
  22904. QCustomPlot::removePlottable() instead. The newly created plottable can be modified, e.g.:
  22905. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-creation-2
  22906. Here we have used the static helper method \ref timeSeriesToOhlc, to turn a time-price data
  22907. series into a 24-hour binned open-high-low-close data series as QCPFinancial uses.
  22908. */
  22909. /* start of documentation of inline functions */
  22910. /*! \fn QCPFinancialDataContainer *QCPFinancial::data() const
  22911. Returns a pointer to the internal data storage of type \ref QCPFinancialDataContainer. You may
  22912. use it to directly manipulate the data, which may be more convenient and faster than using the
  22913. regular \ref setData or \ref addData methods, in certain situations.
  22914. */
  22915. /* end of documentation of inline functions */
  22916. /*!
  22917. Constructs a financial chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  22918. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  22919. the same orientation. If either of these restrictions is violated, a corresponding message is
  22920. printed to the debug output (qDebug), the construction is not aborted, though.
  22921. The created QCPFinancial is automatically registered with the QCustomPlot instance inferred from \a
  22922. keyAxis. This QCustomPlot instance takes ownership of the QCPFinancial, so do not delete it manually
  22923. but use QCustomPlot::removePlottable() instead.
  22924. */
  22925. QCPFinancial::QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  22926. QCPAbstractPlottable1D<QCPFinancialData>(keyAxis, valueAxis),
  22927. mChartStyle(csCandlestick),
  22928. mWidth(0.5),
  22929. mWidthType(wtPlotCoords),
  22930. mTwoColored(true),
  22931. mBrushPositive(QBrush(QColor(50, 160, 0))),
  22932. mBrushNegative(QBrush(QColor(180, 0, 15))),
  22933. mPenPositive(QPen(QColor(40, 150, 0))),
  22934. mPenNegative(QPen(QColor(170, 5, 5)))
  22935. {
  22936. mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255)));
  22937. }
  22938. QCPFinancial::~QCPFinancial()
  22939. {
  22940. }
  22941. /*! \overload
  22942. Replaces the current data container with the provided \a data container.
  22943. Since a QSharedPointer is used, multiple QCPFinancials may share the same data container safely.
  22944. Modifying the data in the container will then affect all financials that share the container.
  22945. Sharing can be achieved by simply exchanging the data containers wrapped in shared pointers:
  22946. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-datasharing-1
  22947. If you do not wish to share containers, but create a copy from an existing container, rather use
  22948. the \ref QCPDataContainer<DataType>::set method on the financial's data container directly:
  22949. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-datasharing-2
  22950. \see addData, timeSeriesToOhlc
  22951. */
  22952. void QCPFinancial::setData(QSharedPointer<QCPFinancialDataContainer> data)
  22953. {
  22954. mDataContainer = data;
  22955. }
  22956. /*! \overload
  22957. Replaces the current data with the provided points in \a keys, \a open, \a high, \a low and \a
  22958. close. The provided vectors should have equal length. Else, the number of added points will be
  22959. the size of the smallest vector.
  22960. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  22961. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  22962. \see addData, timeSeriesToOhlc
  22963. */
  22964. 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)
  22965. {
  22966. mDataContainer->clear();
  22967. addData(keys, open, high, low, close, alreadySorted);
  22968. }
  22969. /*!
  22970. Sets which representation style shall be used to display the OHLC data.
  22971. */
  22972. void QCPFinancial::setChartStyle(QCPFinancial::ChartStyle style)
  22973. {
  22974. mChartStyle = style;
  22975. }
  22976. /*!
  22977. Sets the width of the individual bars/candlesticks to \a width in plot key coordinates.
  22978. A typical choice is to set it to (or slightly less than) one bin interval width.
  22979. */
  22980. void QCPFinancial::setWidth(double width)
  22981. {
  22982. mWidth = width;
  22983. }
  22984. /*!
  22985. Sets how the width of the financial bars is defined. See the documentation of \ref WidthType for
  22986. an explanation of the possible values for \a widthType.
  22987. The default value is \ref wtPlotCoords.
  22988. \see setWidth
  22989. */
  22990. void QCPFinancial::setWidthType(QCPFinancial::WidthType widthType)
  22991. {
  22992. mWidthType = widthType;
  22993. }
  22994. /*!
  22995. Sets whether this chart shall contrast positive from negative trends per data point by using two
  22996. separate colors to draw the respective bars/candlesticks.
  22997. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  22998. setBrush).
  22999. \see setPenPositive, setPenNegative, setBrushPositive, setBrushNegative
  23000. */
  23001. void QCPFinancial::setTwoColored(bool twoColored)
  23002. {
  23003. mTwoColored = twoColored;
  23004. }
  23005. /*!
  23006. If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
  23007. of data points with a positive trend (i.e. bars/candlesticks with close >= open).
  23008. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  23009. setBrush).
  23010. \see setBrushNegative, setPenPositive, setPenNegative
  23011. */
  23012. void QCPFinancial::setBrushPositive(const QBrush &brush)
  23013. {
  23014. mBrushPositive = brush;
  23015. }
  23016. /*!
  23017. If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
  23018. of data points with a negative trend (i.e. bars/candlesticks with close < open).
  23019. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  23020. setBrush).
  23021. \see setBrushPositive, setPenNegative, setPenPositive
  23022. */
  23023. void QCPFinancial::setBrushNegative(const QBrush &brush)
  23024. {
  23025. mBrushNegative = brush;
  23026. }
  23027. /*!
  23028. If \ref setTwoColored is set to true, this function controls the pen that is used to draw
  23029. outlines of data points with a positive trend (i.e. bars/candlesticks with close >= open).
  23030. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  23031. setBrush).
  23032. \see setPenNegative, setBrushPositive, setBrushNegative
  23033. */
  23034. void QCPFinancial::setPenPositive(const QPen &pen)
  23035. {
  23036. mPenPositive = pen;
  23037. }
  23038. /*!
  23039. If \ref setTwoColored is set to true, this function controls the pen that is used to draw
  23040. outlines of data points with a negative trend (i.e. bars/candlesticks with close < open).
  23041. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  23042. setBrush).
  23043. \see setPenPositive, setBrushNegative, setBrushPositive
  23044. */
  23045. void QCPFinancial::setPenNegative(const QPen &pen)
  23046. {
  23047. mPenNegative = pen;
  23048. }
  23049. /*! \overload
  23050. Adds the provided points in \a keys, \a open, \a high, \a low and \a close to the current data.
  23051. The provided vectors should have equal length. Else, the number of added points will be the size
  23052. of the smallest vector.
  23053. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  23054. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  23055. Alternatively, you can also access and modify the data directly via the \ref data method, which
  23056. returns a pointer to the internal data container.
  23057. \see timeSeriesToOhlc
  23058. */
  23059. 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)
  23060. {
  23061. if (keys.size() != open.size() || open.size() != high.size() || high.size() != low.size() || low.size() != close.size() || close.size() != keys.size())
  23062. qDebug() << Q_FUNC_INFO << "keys, open, high, low, close have different sizes:" << keys.size() << open.size() << high.size() << low.size() << close.size();
  23063. const int n = qMin(keys.size(), qMin(open.size(), qMin(high.size(), qMin(low.size(), close.size()))));
  23064. QVector<QCPFinancialData> tempData(n);
  23065. QVector<QCPFinancialData>::iterator it = tempData.begin();
  23066. const QVector<QCPFinancialData>::iterator itEnd = tempData.end();
  23067. int i = 0;
  23068. while (it != itEnd)
  23069. {
  23070. it->key = keys[i];
  23071. it->open = open[i];
  23072. it->high = high[i];
  23073. it->low = low[i];
  23074. it->close = close[i];
  23075. ++it;
  23076. ++i;
  23077. }
  23078. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  23079. }
  23080. /*! \overload
  23081. Adds the provided data point as \a key, \a open, \a high, \a low and \a close to the current
  23082. data.
  23083. Alternatively, you can also access and modify the data directly via the \ref data method, which
  23084. returns a pointer to the internal data container.
  23085. \see timeSeriesToOhlc
  23086. */
  23087. void QCPFinancial::addData(double key, double open, double high, double low, double close)
  23088. {
  23089. mDataContainer->add(QCPFinancialData(key, open, high, low, close));
  23090. }
  23091. /*!
  23092. \copydoc QCPPlottableInterface1D::selectTestRect
  23093. */
  23094. QCPDataSelection QCPFinancial::selectTestRect(const QRectF &rect, bool onlySelectable) const
  23095. {
  23096. QCPDataSelection result;
  23097. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  23098. return result;
  23099. if (!mKeyAxis || !mValueAxis)
  23100. return result;
  23101. QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
  23102. getVisibleDataBounds(visibleBegin, visibleEnd);
  23103. for (QCPFinancialDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  23104. {
  23105. if (rect.intersects(selectionHitBox(it)))
  23106. result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
  23107. }
  23108. result.simplify();
  23109. return result;
  23110. }
  23111. /*!
  23112. Implements a selectTest specific to this plottable's point geometry.
  23113. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  23114. point to \a pos.
  23115. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  23116. */
  23117. double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  23118. {
  23119. Q_UNUSED(details)
  23120. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  23121. return -1;
  23122. if (!mKeyAxis || !mValueAxis)
  23123. return -1;
  23124. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  23125. {
  23126. // get visible data range:
  23127. QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
  23128. QCPFinancialDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  23129. getVisibleDataBounds(visibleBegin, visibleEnd);
  23130. // perform select test according to configured style:
  23131. double result = -1;
  23132. switch (mChartStyle)
  23133. {
  23134. case QCPFinancial::csOhlc:
  23135. result = ohlcSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break;
  23136. case QCPFinancial::csCandlestick:
  23137. result = candlestickSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break;
  23138. }
  23139. if (details)
  23140. {
  23141. int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
  23142. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  23143. }
  23144. return result;
  23145. }
  23146. return -1;
  23147. }
  23148. /* inherits documentation from base class */
  23149. QCPRange QCPFinancial::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  23150. {
  23151. QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain);
  23152. // determine exact range by including width of bars/flags:
  23153. if (foundRange)
  23154. {
  23155. if (inSignDomain != QCP::sdPositive || range.lower-mWidth*0.5 > 0)
  23156. range.lower -= mWidth*0.5;
  23157. if (inSignDomain != QCP::sdNegative || range.upper+mWidth*0.5 < 0)
  23158. range.upper += mWidth*0.5;
  23159. }
  23160. return range;
  23161. }
  23162. /* inherits documentation from base class */
  23163. QCPRange QCPFinancial::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  23164. {
  23165. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  23166. }
  23167. /*!
  23168. A convenience function that converts time series data (\a value against \a time) to OHLC binned
  23169. data points. The return value can then be passed on to \ref QCPFinancialDataContainer::set(const
  23170. QCPFinancialDataContainer&).
  23171. The size of the bins can be controlled with \a timeBinSize in the same units as \a time is given.
  23172. For example, if the unit of \a time is seconds and single OHLC/Candlesticks should span an hour
  23173. each, set \a timeBinSize to 3600.
  23174. \a timeBinOffset allows to control precisely at what \a time coordinate a bin should start. The
  23175. value passed as \a timeBinOffset doesn't need to be in the range encompassed by the \a time keys.
  23176. It merely defines the mathematical offset/phase of the bins that will be used to process the
  23177. data.
  23178. */
  23179. QCPFinancialDataContainer QCPFinancial::timeSeriesToOhlc(const QVector<double> &time, const QVector<double> &value, double timeBinSize, double timeBinOffset)
  23180. {
  23181. QCPFinancialDataContainer data;
  23182. int count = qMin(time.size(), value.size());
  23183. if (count == 0)
  23184. return QCPFinancialDataContainer();
  23185. QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first());
  23186. int currentBinIndex = qFloor((time.first()-timeBinOffset)/timeBinSize+0.5);
  23187. for (int i=0; i<count; ++i)
  23188. {
  23189. int index = qFloor((time.at(i)-timeBinOffset)/timeBinSize+0.5);
  23190. if (currentBinIndex == index) // data point still in current bin, extend high/low:
  23191. {
  23192. if (value.at(i) < currentBinData.low) currentBinData.low = value.at(i);
  23193. if (value.at(i) > currentBinData.high) currentBinData.high = value.at(i);
  23194. if (i == count-1) // last data point is in current bin, finalize bin:
  23195. {
  23196. currentBinData.close = value.at(i);
  23197. currentBinData.key = timeBinOffset+(index)*timeBinSize;
  23198. data.add(currentBinData);
  23199. }
  23200. } else // data point not anymore in current bin, set close of old and open of new bin, and add old to map:
  23201. {
  23202. // finalize current bin:
  23203. currentBinData.close = value.at(i-1);
  23204. currentBinData.key = timeBinOffset+(index-1)*timeBinSize;
  23205. data.add(currentBinData);
  23206. // start next bin:
  23207. currentBinIndex = index;
  23208. currentBinData.open = value.at(i);
  23209. currentBinData.high = value.at(i);
  23210. currentBinData.low = value.at(i);
  23211. }
  23212. }
  23213. return data;
  23214. }
  23215. /* inherits documentation from base class */
  23216. void QCPFinancial::draw(QCPPainter *painter)
  23217. {
  23218. // get visible data range:
  23219. QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
  23220. getVisibleDataBounds(visibleBegin, visibleEnd);
  23221. // loop over and draw segments of unselected/selected data:
  23222. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  23223. getDataSegments(selectedSegments, unselectedSegments);
  23224. allSegments << unselectedSegments << selectedSegments;
  23225. for (int i=0; i<allSegments.size(); ++i)
  23226. {
  23227. bool isSelectedSegment = i >= unselectedSegments.size();
  23228. QCPFinancialDataContainer::const_iterator begin = visibleBegin;
  23229. QCPFinancialDataContainer::const_iterator end = visibleEnd;
  23230. mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
  23231. if (begin == end)
  23232. continue;
  23233. // draw data segment according to configured style:
  23234. switch (mChartStyle)
  23235. {
  23236. case QCPFinancial::csOhlc:
  23237. drawOhlcPlot(painter, begin, end, isSelectedSegment); break;
  23238. case QCPFinancial::csCandlestick:
  23239. drawCandlestickPlot(painter, begin, end, isSelectedSegment); break;
  23240. }
  23241. }
  23242. // draw other selection decoration that isn't just line/scatter pens and brushes:
  23243. if (mSelectionDecorator)
  23244. mSelectionDecorator->drawDecoration(painter, selection());
  23245. }
  23246. /* inherits documentation from base class */
  23247. void QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  23248. {
  23249. painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing
  23250. if (mChartStyle == csOhlc)
  23251. {
  23252. if (mTwoColored)
  23253. {
  23254. // draw upper left half icon with positive color:
  23255. painter->setBrush(mBrushPositive);
  23256. painter->setPen(mPenPositive);
  23257. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint()));
  23258. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23259. painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
  23260. painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
  23261. // draw bottom right half icon with negative color:
  23262. painter->setBrush(mBrushNegative);
  23263. painter->setPen(mPenNegative);
  23264. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint()));
  23265. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23266. painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
  23267. painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
  23268. } else
  23269. {
  23270. painter->setBrush(mBrush);
  23271. painter->setPen(mPen);
  23272. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23273. painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
  23274. painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
  23275. }
  23276. } else if (mChartStyle == csCandlestick)
  23277. {
  23278. if (mTwoColored)
  23279. {
  23280. // draw upper left half icon with positive color:
  23281. painter->setBrush(mBrushPositive);
  23282. painter->setPen(mPenPositive);
  23283. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint()));
  23284. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
  23285. painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23286. painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
  23287. // draw bottom right half icon with negative color:
  23288. painter->setBrush(mBrushNegative);
  23289. painter->setPen(mPenNegative);
  23290. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint()));
  23291. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
  23292. painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23293. painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
  23294. } else
  23295. {
  23296. painter->setBrush(mBrush);
  23297. painter->setPen(mPen);
  23298. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
  23299. painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23300. painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
  23301. }
  23302. }
  23303. }
  23304. /*! \internal
  23305. Draws the data from \a begin to \a end-1 as OHLC bars with the provided \a painter.
  23306. This method is a helper function for \ref draw. It is used when the chart style is \ref csOhlc.
  23307. */
  23308. void QCPFinancial::drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected)
  23309. {
  23310. QCPAxis *keyAxis = mKeyAxis.data();
  23311. QCPAxis *valueAxis = mValueAxis.data();
  23312. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  23313. if (keyAxis->orientation() == Qt::Horizontal)
  23314. {
  23315. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  23316. {
  23317. if (isSelected && mSelectionDecorator)
  23318. mSelectionDecorator->applyPen(painter);
  23319. else if (mTwoColored)
  23320. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  23321. else
  23322. painter->setPen(mPen);
  23323. double keyPixel = keyAxis->coordToPixel(it->key);
  23324. double openPixel = valueAxis->coordToPixel(it->open);
  23325. double closePixel = valueAxis->coordToPixel(it->close);
  23326. // draw backbone:
  23327. painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(it->low)));
  23328. // draw open:
  23329. double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides
  23330. painter->drawLine(QPointF(keyPixel-pixelWidth, openPixel), QPointF(keyPixel, openPixel));
  23331. // draw close:
  23332. painter->drawLine(QPointF(keyPixel, closePixel), QPointF(keyPixel+pixelWidth, closePixel));
  23333. }
  23334. } else
  23335. {
  23336. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  23337. {
  23338. if (isSelected && mSelectionDecorator)
  23339. mSelectionDecorator->applyPen(painter);
  23340. else if (mTwoColored)
  23341. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  23342. else
  23343. painter->setPen(mPen);
  23344. double keyPixel = keyAxis->coordToPixel(it->key);
  23345. double openPixel = valueAxis->coordToPixel(it->open);
  23346. double closePixel = valueAxis->coordToPixel(it->close);
  23347. // draw backbone:
  23348. painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(it->low), keyPixel));
  23349. // draw open:
  23350. double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides
  23351. painter->drawLine(QPointF(openPixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel));
  23352. // draw close:
  23353. painter->drawLine(QPointF(closePixel, keyPixel), QPointF(closePixel, keyPixel+pixelWidth));
  23354. }
  23355. }
  23356. }
  23357. /*! \internal
  23358. Draws the data from \a begin to \a end-1 as Candlesticks with the provided \a painter.
  23359. This method is a helper function for \ref draw. It is used when the chart style is \ref csCandlestick.
  23360. */
  23361. void QCPFinancial::drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected)
  23362. {
  23363. QCPAxis *keyAxis = mKeyAxis.data();
  23364. QCPAxis *valueAxis = mValueAxis.data();
  23365. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  23366. if (keyAxis->orientation() == Qt::Horizontal)
  23367. {
  23368. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  23369. {
  23370. if (isSelected && mSelectionDecorator)
  23371. {
  23372. mSelectionDecorator->applyPen(painter);
  23373. mSelectionDecorator->applyBrush(painter);
  23374. } else if (mTwoColored)
  23375. {
  23376. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  23377. painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative);
  23378. } else
  23379. {
  23380. painter->setPen(mPen);
  23381. painter->setBrush(mBrush);
  23382. }
  23383. double keyPixel = keyAxis->coordToPixel(it->key);
  23384. double openPixel = valueAxis->coordToPixel(it->open);
  23385. double closePixel = valueAxis->coordToPixel(it->close);
  23386. // draw high:
  23387. painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close))));
  23388. // draw low:
  23389. painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close))));
  23390. // draw open-close box:
  23391. double pixelWidth = getPixelWidth(it->key, keyPixel);
  23392. painter->drawRect(QRectF(QPointF(keyPixel-pixelWidth, closePixel), QPointF(keyPixel+pixelWidth, openPixel)));
  23393. }
  23394. } else // keyAxis->orientation() == Qt::Vertical
  23395. {
  23396. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  23397. {
  23398. if (isSelected && mSelectionDecorator)
  23399. {
  23400. mSelectionDecorator->applyPen(painter);
  23401. mSelectionDecorator->applyBrush(painter);
  23402. } else if (mTwoColored)
  23403. {
  23404. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  23405. painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative);
  23406. } else
  23407. {
  23408. painter->setPen(mPen);
  23409. painter->setBrush(mBrush);
  23410. }
  23411. double keyPixel = keyAxis->coordToPixel(it->key);
  23412. double openPixel = valueAxis->coordToPixel(it->open);
  23413. double closePixel = valueAxis->coordToPixel(it->close);
  23414. // draw high:
  23415. painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel));
  23416. // draw low:
  23417. painter->drawLine(QPointF(valueAxis->coordToPixel(it->low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel));
  23418. // draw open-close box:
  23419. double pixelWidth = getPixelWidth(it->key, keyPixel);
  23420. painter->drawRect(QRectF(QPointF(closePixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel+pixelWidth)));
  23421. }
  23422. }
  23423. }
  23424. /*! \internal
  23425. This function is used to determine the width of the bar at coordinate \a key, according to the
  23426. specified width (\ref setWidth) and width type (\ref setWidthType). Provide the pixel position of
  23427. \a key in \a keyPixel (because usually this was already calculated via \ref QCPAxis::coordToPixel
  23428. when this function is called).
  23429. It returns the number of pixels the bar extends to higher keys, relative to the \a key
  23430. coordinate. So with a non-reversed horizontal axis, the return value is positive. With a reversed
  23431. horizontal axis, the return value is negative. This is important so the open/close flags on the
  23432. \ref csOhlc bar are drawn to the correct side.
  23433. */
  23434. double QCPFinancial::getPixelWidth(double key, double keyPixel) const
  23435. {
  23436. double result = 0;
  23437. switch (mWidthType)
  23438. {
  23439. case wtAbsolute:
  23440. {
  23441. if (mKeyAxis)
  23442. result = mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  23443. break;
  23444. }
  23445. case wtAxisRectRatio:
  23446. {
  23447. if (mKeyAxis && mKeyAxis.data()->axisRect())
  23448. {
  23449. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  23450. result = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  23451. else
  23452. result = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  23453. } else
  23454. qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined";
  23455. break;
  23456. }
  23457. case wtPlotCoords:
  23458. {
  23459. if (mKeyAxis)
  23460. result = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel;
  23461. else
  23462. qDebug() << Q_FUNC_INFO << "No key axis defined";
  23463. break;
  23464. }
  23465. }
  23466. return result;
  23467. }
  23468. /*! \internal
  23469. This method is a helper function for \ref selectTest. It is used to test for selection when the
  23470. chart style is \ref csOhlc. It only tests against the data points between \a begin and \a end.
  23471. Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical
  23472. representation of the plottable, and \a closestDataPoint will point to the respective data point.
  23473. */
  23474. double QCPFinancial::ohlcSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const
  23475. {
  23476. closestDataPoint = mDataContainer->constEnd();
  23477. QCPAxis *keyAxis = mKeyAxis.data();
  23478. QCPAxis *valueAxis = mValueAxis.data();
  23479. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  23480. double minDistSqr = (std::numeric_limits<double>::max)();
  23481. if (keyAxis->orientation() == Qt::Horizontal)
  23482. {
  23483. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  23484. {
  23485. double keyPixel = keyAxis->coordToPixel(it->key);
  23486. // calculate distance to backbone:
  23487. double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low)));
  23488. if (currentDistSqr < minDistSqr)
  23489. {
  23490. minDistSqr = currentDistSqr;
  23491. closestDataPoint = it;
  23492. }
  23493. }
  23494. } else // keyAxis->orientation() == Qt::Vertical
  23495. {
  23496. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  23497. {
  23498. double keyPixel = keyAxis->coordToPixel(it->key);
  23499. // calculate distance to backbone:
  23500. double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel));
  23501. if (currentDistSqr < minDistSqr)
  23502. {
  23503. minDistSqr = currentDistSqr;
  23504. closestDataPoint = it;
  23505. }
  23506. }
  23507. }
  23508. return qSqrt(minDistSqr);
  23509. }
  23510. /*! \internal
  23511. This method is a helper function for \ref selectTest. It is used to test for selection when the
  23512. chart style is \ref csCandlestick. It only tests against the data points between \a begin and \a
  23513. end.
  23514. Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical
  23515. representation of the plottable, and \a closestDataPoint will point to the respective data point.
  23516. */
  23517. double QCPFinancial::candlestickSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const
  23518. {
  23519. closestDataPoint = mDataContainer->constEnd();
  23520. QCPAxis *keyAxis = mKeyAxis.data();
  23521. QCPAxis *valueAxis = mValueAxis.data();
  23522. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  23523. double minDistSqr = (std::numeric_limits<double>::max)();
  23524. if (keyAxis->orientation() == Qt::Horizontal)
  23525. {
  23526. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  23527. {
  23528. double currentDistSqr;
  23529. // determine whether pos is in open-close-box:
  23530. QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5);
  23531. QCPRange boxValueRange(it->close, it->open);
  23532. double posKey, posValue;
  23533. pixelsToCoords(pos, posKey, posValue);
  23534. if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box
  23535. {
  23536. currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
  23537. } else
  23538. {
  23539. // calculate distance to high/low lines:
  23540. double keyPixel = keyAxis->coordToPixel(it->key);
  23541. double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close))));
  23542. double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close))));
  23543. currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
  23544. }
  23545. if (currentDistSqr < minDistSqr)
  23546. {
  23547. minDistSqr = currentDistSqr;
  23548. closestDataPoint = it;
  23549. }
  23550. }
  23551. } else // keyAxis->orientation() == Qt::Vertical
  23552. {
  23553. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  23554. {
  23555. double currentDistSqr;
  23556. // determine whether pos is in open-close-box:
  23557. QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5);
  23558. QCPRange boxValueRange(it->close, it->open);
  23559. double posKey, posValue;
  23560. pixelsToCoords(pos, posKey, posValue);
  23561. if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box
  23562. {
  23563. currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
  23564. } else
  23565. {
  23566. // calculate distance to high/low lines:
  23567. double keyPixel = keyAxis->coordToPixel(it->key);
  23568. double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel));
  23569. double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel));
  23570. currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
  23571. }
  23572. if (currentDistSqr < minDistSqr)
  23573. {
  23574. minDistSqr = currentDistSqr;
  23575. closestDataPoint = it;
  23576. }
  23577. }
  23578. }
  23579. return qSqrt(minDistSqr);
  23580. }
  23581. /*! \internal
  23582. called by the drawing methods to determine which data (key) range is visible at the current key
  23583. axis range setting, so only that needs to be processed.
  23584. \a begin returns an iterator to the lowest data point that needs to be taken into account when
  23585. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  23586. begin may still be just outside the visible range.
  23587. \a end returns the iterator just above the highest data point that needs to be taken into
  23588. account. Same as before, \a end may also lie just outside of the visible range
  23589. if the plottable contains no data, both \a begin and \a end point to \c constEnd.
  23590. */
  23591. void QCPFinancial::getVisibleDataBounds(QCPFinancialDataContainer::const_iterator &begin, QCPFinancialDataContainer::const_iterator &end) const
  23592. {
  23593. if (!mKeyAxis)
  23594. {
  23595. qDebug() << Q_FUNC_INFO << "invalid key axis";
  23596. begin = mDataContainer->constEnd();
  23597. end = mDataContainer->constEnd();
  23598. return;
  23599. }
  23600. begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of ohlc/candlestick to include partially visible data points
  23601. end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of ohlc/candlestick to include partially visible data points
  23602. }
  23603. /*! \internal
  23604. Returns the hit box in pixel coordinates that will be used for data selection with the selection
  23605. rect (\ref selectTestRect), of the data point given by \a it.
  23606. */
  23607. QRectF QCPFinancial::selectionHitBox(QCPFinancialDataContainer::const_iterator it) const
  23608. {
  23609. QCPAxis *keyAxis = mKeyAxis.data();
  23610. QCPAxis *valueAxis = mValueAxis.data();
  23611. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
  23612. double keyPixel = keyAxis->coordToPixel(it->key);
  23613. double highPixel = valueAxis->coordToPixel(it->high);
  23614. double lowPixel = valueAxis->coordToPixel(it->low);
  23615. double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it->key-mWidth*0.5);
  23616. if (keyAxis->orientation() == Qt::Horizontal)
  23617. return QRectF(keyPixel-keyWidthPixels, highPixel, keyWidthPixels*2, lowPixel-highPixel).normalized();
  23618. else
  23619. return QRectF(highPixel, keyPixel-keyWidthPixels, lowPixel-highPixel, keyWidthPixels*2).normalized();
  23620. }
  23621. /* end of 'src/plottables/plottable-financial.cpp' */
  23622. /* including file 'src/plottables/plottable-errorbar.cpp' */
  23623. /* modified 2021-03-29T02:30:44, size 37679 */
  23624. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23625. //////////////////// QCPErrorBarsData
  23626. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23627. /*! \class QCPErrorBarsData
  23628. \brief Holds the data of one single error bar for QCPErrorBars.
  23629. The stored data is:
  23630. \li \a errorMinus: how much the error bar extends towards negative coordinates from the data
  23631. point position
  23632. \li \a errorPlus: how much the error bar extends towards positive coordinates from the data point
  23633. position
  23634. The container for storing the error bar information is \ref QCPErrorBarsDataContainer. It is a
  23635. typedef for <tt>QVector<\ref QCPErrorBarsData></tt>.
  23636. \see QCPErrorBarsDataContainer
  23637. */
  23638. /*!
  23639. Constructs an error bar with errors set to zero.
  23640. */
  23641. QCPErrorBarsData::QCPErrorBarsData() :
  23642. errorMinus(0),
  23643. errorPlus(0)
  23644. {
  23645. }
  23646. /*!
  23647. Constructs an error bar with equal \a error in both negative and positive direction.
  23648. */
  23649. QCPErrorBarsData::QCPErrorBarsData(double error) :
  23650. errorMinus(error),
  23651. errorPlus(error)
  23652. {
  23653. }
  23654. /*!
  23655. Constructs an error bar with negative and positive errors set to \a errorMinus and \a errorPlus,
  23656. respectively.
  23657. */
  23658. QCPErrorBarsData::QCPErrorBarsData(double errorMinus, double errorPlus) :
  23659. errorMinus(errorMinus),
  23660. errorPlus(errorPlus)
  23661. {
  23662. }
  23663. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23664. //////////////////// QCPErrorBars
  23665. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23666. /*! \class QCPErrorBars
  23667. \brief A plottable that adds a set of error bars to other plottables.
  23668. \image html QCPErrorBars.png
  23669. The \ref QCPErrorBars plottable can be attached to other one-dimensional plottables (e.g. \ref
  23670. QCPGraph, \ref QCPCurve, \ref QCPBars, etc.) and equips them with error bars.
  23671. Use \ref setDataPlottable to define for which plottable the \ref QCPErrorBars shall display the
  23672. error bars. The orientation of the error bars can be controlled with \ref setErrorType.
  23673. By using \ref setData, you can supply the actual error data, either as symmetric error or
  23674. plus/minus asymmetric errors. \ref QCPErrorBars only stores the error data. The absolute
  23675. key/value position of each error bar will be adopted from the configured data plottable. The
  23676. error data of the \ref QCPErrorBars are associated one-to-one via their index to the data points
  23677. of the data plottable. You can directly access and manipulate the error bar data via \ref data.
  23678. Set either of the plus/minus errors to NaN (<tt>qQNaN()</tt> or
  23679. <tt>std::numeric_limits<double>::quiet_NaN()</tt>) to not show the respective error bar on the data point at
  23680. that index.
  23681. \section qcperrorbars-appearance Changing the appearance
  23682. The appearance of the error bars is defined by the pen (\ref setPen), and the width of the
  23683. whiskers (\ref setWhiskerWidth). Further, the error bar backbones may leave a gap around the data
  23684. point center to prevent that error bars are drawn too close to or even through scatter points.
  23685. This gap size can be controlled via \ref setSymbolGap.
  23686. */
  23687. /* start of documentation of inline functions */
  23688. /*! \fn QSharedPointer<QCPErrorBarsDataContainer> QCPErrorBars::data() const
  23689. Returns a shared pointer to the internal data storage of type \ref QCPErrorBarsDataContainer. You
  23690. may use it to directly manipulate the error values, which may be more convenient and faster than
  23691. using the regular \ref setData methods.
  23692. */
  23693. /* end of documentation of inline functions */
  23694. /*!
  23695. Constructs an error bars plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  23696. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  23697. the same orientation. If either of these restrictions is violated, a corresponding message is
  23698. printed to the debug output (qDebug), the construction is not aborted, though.
  23699. It is also important that the \a keyAxis and \a valueAxis are the same for the error bars
  23700. plottable and the data plottable that the error bars shall be drawn on (\ref setDataPlottable).
  23701. The created \ref QCPErrorBars is automatically registered with the QCustomPlot instance inferred
  23702. from \a keyAxis. This QCustomPlot instance takes ownership of the \ref QCPErrorBars, so do not
  23703. delete it manually but use \ref QCustomPlot::removePlottable() instead.
  23704. */
  23705. QCPErrorBars::QCPErrorBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  23706. QCPAbstractPlottable(keyAxis, valueAxis),
  23707. mDataContainer(new QVector<QCPErrorBarsData>),
  23708. mErrorType(etValueError),
  23709. mWhiskerWidth(9),
  23710. mSymbolGap(10)
  23711. {
  23712. setPen(QPen(Qt::black, 0));
  23713. setBrush(Qt::NoBrush);
  23714. }
  23715. QCPErrorBars::~QCPErrorBars()
  23716. {
  23717. }
  23718. /*! \overload
  23719. Replaces the current data container with the provided \a data container.
  23720. Since a QSharedPointer is used, multiple \ref QCPErrorBars instances may share the same data
  23721. container safely. Modifying the data in the container will then affect all \ref QCPErrorBars
  23722. instances that share the container. Sharing can be achieved by simply exchanging the data
  23723. containers wrapped in shared pointers:
  23724. \snippet documentation/doc-code-snippets/mainwindow.cpp qcperrorbars-datasharing-1
  23725. If you do not wish to share containers, but create a copy from an existing container, assign the
  23726. data containers directly:
  23727. \snippet documentation/doc-code-snippets/mainwindow.cpp qcperrorbars-datasharing-2
  23728. (This uses different notation compared with other plottables, because the \ref QCPErrorBars
  23729. uses a \c QVector<QCPErrorBarsData> as its data container, instead of a \ref QCPDataContainer.)
  23730. \see addData
  23731. */
  23732. void QCPErrorBars::setData(QSharedPointer<QCPErrorBarsDataContainer> data)
  23733. {
  23734. mDataContainer = data;
  23735. }
  23736. /*! \overload
  23737. Sets symmetrical error values as specified in \a error. The errors will be associated one-to-one
  23738. by the data point index to the associated data plottable (\ref setDataPlottable).
  23739. You can directly access and manipulate the error bar data via \ref data.
  23740. \see addData
  23741. */
  23742. void QCPErrorBars::setData(const QVector<double> &error)
  23743. {
  23744. mDataContainer->clear();
  23745. addData(error);
  23746. }
  23747. /*! \overload
  23748. Sets asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be
  23749. associated one-to-one by the data point index to the associated data plottable (\ref
  23750. setDataPlottable).
  23751. You can directly access and manipulate the error bar data via \ref data.
  23752. \see addData
  23753. */
  23754. void QCPErrorBars::setData(const QVector<double> &errorMinus, const QVector<double> &errorPlus)
  23755. {
  23756. mDataContainer->clear();
  23757. addData(errorMinus, errorPlus);
  23758. }
  23759. /*!
  23760. Sets the data plottable to which the error bars will be applied. The error values specified e.g.
  23761. via \ref setData will be associated one-to-one by the data point index to the data points of \a
  23762. plottable. This means that the error bars will adopt the key/value coordinates of the data point
  23763. with the same index.
  23764. The passed \a plottable must be a one-dimensional plottable, i.e. it must implement the \ref
  23765. QCPPlottableInterface1D. Further, it must not be a \ref QCPErrorBars instance itself. If either
  23766. of these restrictions is violated, a corresponding qDebug output is generated, and the data
  23767. plottable of this \ref QCPErrorBars instance is set to zero.
  23768. For proper display, care must also be taken that the key and value axes of the \a plottable match
  23769. those configured for this \ref QCPErrorBars instance.
  23770. */
  23771. void QCPErrorBars::setDataPlottable(QCPAbstractPlottable *plottable)
  23772. {
  23773. if (plottable && qobject_cast<QCPErrorBars*>(plottable))
  23774. {
  23775. mDataPlottable = nullptr;
  23776. qDebug() << Q_FUNC_INFO << "can't set another QCPErrorBars instance as data plottable";
  23777. return;
  23778. }
  23779. if (plottable && !plottable->interface1D())
  23780. {
  23781. mDataPlottable = nullptr;
  23782. qDebug() << Q_FUNC_INFO << "passed plottable doesn't implement 1d interface, can't associate with QCPErrorBars";
  23783. return;
  23784. }
  23785. mDataPlottable = plottable;
  23786. }
  23787. /*!
  23788. Sets in which orientation the error bars shall appear on the data points. If your data needs both
  23789. error dimensions, create two \ref QCPErrorBars with different \a type.
  23790. */
  23791. void QCPErrorBars::setErrorType(ErrorType type)
  23792. {
  23793. mErrorType = type;
  23794. }
  23795. /*!
  23796. Sets the width of the whiskers (the short bars at the end of the actual error bar backbones) to
  23797. \a pixels.
  23798. */
  23799. void QCPErrorBars::setWhiskerWidth(double pixels)
  23800. {
  23801. mWhiskerWidth = pixels;
  23802. }
  23803. /*!
  23804. Sets the gap diameter around the data points that will be left out when drawing the error bar
  23805. backbones. This gap prevents that error bars are drawn too close to or even through scatter
  23806. points.
  23807. */
  23808. void QCPErrorBars::setSymbolGap(double pixels)
  23809. {
  23810. mSymbolGap = pixels;
  23811. }
  23812. /*! \overload
  23813. Adds symmetrical error values as specified in \a error. The errors will be associated one-to-one
  23814. by the data point index to the associated data plottable (\ref setDataPlottable).
  23815. You can directly access and manipulate the error bar data via \ref data.
  23816. \see setData
  23817. */
  23818. void QCPErrorBars::addData(const QVector<double> &error)
  23819. {
  23820. addData(error, error);
  23821. }
  23822. /*! \overload
  23823. Adds asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be
  23824. associated one-to-one by the data point index to the associated data plottable (\ref
  23825. setDataPlottable).
  23826. You can directly access and manipulate the error bar data via \ref data.
  23827. \see setData
  23828. */
  23829. void QCPErrorBars::addData(const QVector<double> &errorMinus, const QVector<double> &errorPlus)
  23830. {
  23831. if (errorMinus.size() != errorPlus.size())
  23832. qDebug() << Q_FUNC_INFO << "minus and plus error vectors have different sizes:" << errorMinus.size() << errorPlus.size();
  23833. const int n = qMin(errorMinus.size(), errorPlus.size());
  23834. mDataContainer->reserve(n);
  23835. for (int i=0; i<n; ++i)
  23836. mDataContainer->append(QCPErrorBarsData(errorMinus.at(i), errorPlus.at(i)));
  23837. }
  23838. /*! \overload
  23839. Adds a single symmetrical error bar as specified in \a error. The errors will be associated
  23840. one-to-one by the data point index to the associated data plottable (\ref setDataPlottable).
  23841. You can directly access and manipulate the error bar data via \ref data.
  23842. \see setData
  23843. */
  23844. void QCPErrorBars::addData(double error)
  23845. {
  23846. mDataContainer->append(QCPErrorBarsData(error));
  23847. }
  23848. /*! \overload
  23849. Adds a single asymmetrical error bar as specified in \a errorMinus and \a errorPlus. The errors
  23850. will be associated one-to-one by the data point index to the associated data plottable (\ref
  23851. setDataPlottable).
  23852. You can directly access and manipulate the error bar data via \ref data.
  23853. \see setData
  23854. */
  23855. void QCPErrorBars::addData(double errorMinus, double errorPlus)
  23856. {
  23857. mDataContainer->append(QCPErrorBarsData(errorMinus, errorPlus));
  23858. }
  23859. /* inherits documentation from base class */
  23860. int QCPErrorBars::dataCount() const
  23861. {
  23862. return mDataContainer->size();
  23863. }
  23864. /* inherits documentation from base class */
  23865. double QCPErrorBars::dataMainKey(int index) const
  23866. {
  23867. if (mDataPlottable)
  23868. return mDataPlottable->interface1D()->dataMainKey(index);
  23869. else
  23870. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23871. return 0;
  23872. }
  23873. /* inherits documentation from base class */
  23874. double QCPErrorBars::dataSortKey(int index) const
  23875. {
  23876. if (mDataPlottable)
  23877. return mDataPlottable->interface1D()->dataSortKey(index);
  23878. else
  23879. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23880. return 0;
  23881. }
  23882. /* inherits documentation from base class */
  23883. double QCPErrorBars::dataMainValue(int index) const
  23884. {
  23885. if (mDataPlottable)
  23886. return mDataPlottable->interface1D()->dataMainValue(index);
  23887. else
  23888. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23889. return 0;
  23890. }
  23891. /* inherits documentation from base class */
  23892. QCPRange QCPErrorBars::dataValueRange(int index) const
  23893. {
  23894. if (mDataPlottable)
  23895. {
  23896. const double value = mDataPlottable->interface1D()->dataMainValue(index);
  23897. if (index >= 0 && index < mDataContainer->size() && mErrorType == etValueError)
  23898. return {value-mDataContainer->at(index).errorMinus, value+mDataContainer->at(index).errorPlus};
  23899. else
  23900. return {value, value};
  23901. } else
  23902. {
  23903. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23904. return {};
  23905. }
  23906. }
  23907. /* inherits documentation from base class */
  23908. QPointF QCPErrorBars::dataPixelPosition(int index) const
  23909. {
  23910. if (mDataPlottable)
  23911. return mDataPlottable->interface1D()->dataPixelPosition(index);
  23912. else
  23913. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23914. return {};
  23915. }
  23916. /* inherits documentation from base class */
  23917. bool QCPErrorBars::sortKeyIsMainKey() const
  23918. {
  23919. if (mDataPlottable)
  23920. {
  23921. return mDataPlottable->interface1D()->sortKeyIsMainKey();
  23922. } else
  23923. {
  23924. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23925. return true;
  23926. }
  23927. }
  23928. /*!
  23929. \copydoc QCPPlottableInterface1D::selectTestRect
  23930. */
  23931. QCPDataSelection QCPErrorBars::selectTestRect(const QRectF &rect, bool onlySelectable) const
  23932. {
  23933. QCPDataSelection result;
  23934. if (!mDataPlottable)
  23935. return result;
  23936. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  23937. return result;
  23938. if (!mKeyAxis || !mValueAxis)
  23939. return result;
  23940. QCPErrorBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  23941. getVisibleDataBounds(visibleBegin, visibleEnd, QCPDataRange(0, dataCount()));
  23942. QVector<QLineF> backbones, whiskers;
  23943. for (QCPErrorBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  23944. {
  23945. backbones.clear();
  23946. whiskers.clear();
  23947. getErrorBarLines(it, backbones, whiskers);
  23948. foreach (const QLineF &backbone, backbones)
  23949. {
  23950. if (rectIntersectsLine(rect, backbone))
  23951. {
  23952. result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
  23953. break;
  23954. }
  23955. }
  23956. }
  23957. result.simplify();
  23958. return result;
  23959. }
  23960. /* inherits documentation from base class */
  23961. int QCPErrorBars::findBegin(double sortKey, bool expandedRange) const
  23962. {
  23963. if (mDataPlottable)
  23964. {
  23965. if (mDataContainer->isEmpty())
  23966. return 0;
  23967. int beginIndex = mDataPlottable->interface1D()->findBegin(sortKey, expandedRange);
  23968. if (beginIndex >= mDataContainer->size())
  23969. beginIndex = mDataContainer->size()-1;
  23970. return beginIndex;
  23971. } else
  23972. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23973. return 0;
  23974. }
  23975. /* inherits documentation from base class */
  23976. int QCPErrorBars::findEnd(double sortKey, bool expandedRange) const
  23977. {
  23978. if (mDataPlottable)
  23979. {
  23980. if (mDataContainer->isEmpty())
  23981. return 0;
  23982. int endIndex = mDataPlottable->interface1D()->findEnd(sortKey, expandedRange);
  23983. if (endIndex > mDataContainer->size())
  23984. endIndex = mDataContainer->size();
  23985. return endIndex;
  23986. } else
  23987. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23988. return 0;
  23989. }
  23990. /*!
  23991. Implements a selectTest specific to this plottable's point geometry.
  23992. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  23993. point to \a pos.
  23994. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  23995. */
  23996. double QCPErrorBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  23997. {
  23998. if (!mDataPlottable) return -1;
  23999. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  24000. return -1;
  24001. if (!mKeyAxis || !mValueAxis)
  24002. return -1;
  24003. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  24004. {
  24005. QCPErrorBarsDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  24006. double result = pointDistance(pos, closestDataPoint);
  24007. if (details)
  24008. {
  24009. int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
  24010. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  24011. }
  24012. return result;
  24013. } else
  24014. return -1;
  24015. }
  24016. /* inherits documentation from base class */
  24017. void QCPErrorBars::draw(QCPPainter *painter)
  24018. {
  24019. if (!mDataPlottable) return;
  24020. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  24021. if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
  24022. // if the sort key isn't the main key, we must check the visibility for each data point/error bar individually
  24023. // (getVisibleDataBounds applies range restriction, but otherwise can only return full data range):
  24024. bool checkPointVisibility = !mDataPlottable->interface1D()->sortKeyIsMainKey();
  24025. // check data validity if flag set:
  24026. #ifdef QCUSTOMPLOT_CHECK_DATA
  24027. QCPErrorBarsDataContainer::const_iterator it;
  24028. for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  24029. {
  24030. if (QCP::isInvalidData(it->errorMinus, it->errorPlus))
  24031. qDebug() << Q_FUNC_INFO << "Data point at index" << it-mDataContainer->constBegin() << "invalid." << "Plottable name:" << name();
  24032. }
  24033. #endif
  24034. applyDefaultAntialiasingHint(painter);
  24035. painter->setBrush(Qt::NoBrush);
  24036. // loop over and draw segments of unselected/selected data:
  24037. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  24038. getDataSegments(selectedSegments, unselectedSegments);
  24039. allSegments << unselectedSegments << selectedSegments;
  24040. QVector<QLineF> backbones, whiskers;
  24041. for (int i=0; i<allSegments.size(); ++i)
  24042. {
  24043. QCPErrorBarsDataContainer::const_iterator begin, end;
  24044. getVisibleDataBounds(begin, end, allSegments.at(i));
  24045. if (begin == end)
  24046. continue;
  24047. bool isSelectedSegment = i >= unselectedSegments.size();
  24048. if (isSelectedSegment && mSelectionDecorator)
  24049. mSelectionDecorator->applyPen(painter);
  24050. else
  24051. painter->setPen(mPen);
  24052. if (painter->pen().capStyle() == Qt::SquareCap)
  24053. {
  24054. QPen capFixPen(painter->pen());
  24055. capFixPen.setCapStyle(Qt::FlatCap);
  24056. painter->setPen(capFixPen);
  24057. }
  24058. backbones.clear();
  24059. whiskers.clear();
  24060. for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it)
  24061. {
  24062. if (!checkPointVisibility || errorBarVisible(int(it-mDataContainer->constBegin())))
  24063. getErrorBarLines(it, backbones, whiskers);
  24064. }
  24065. painter->drawLines(backbones);
  24066. painter->drawLines(whiskers);
  24067. }
  24068. // draw other selection decoration that isn't just line/scatter pens and brushes:
  24069. if (mSelectionDecorator)
  24070. mSelectionDecorator->drawDecoration(painter, selection());
  24071. }
  24072. /* inherits documentation from base class */
  24073. void QCPErrorBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  24074. {
  24075. applyDefaultAntialiasingHint(painter);
  24076. painter->setPen(mPen);
  24077. if (mErrorType == etValueError && mValueAxis && mValueAxis->orientation() == Qt::Vertical)
  24078. {
  24079. painter->drawLine(QLineF(rect.center().x(), rect.top()+2, rect.center().x(), rect.bottom()-1));
  24080. painter->drawLine(QLineF(rect.center().x()-4, rect.top()+2, rect.center().x()+4, rect.top()+2));
  24081. painter->drawLine(QLineF(rect.center().x()-4, rect.bottom()-1, rect.center().x()+4, rect.bottom()-1));
  24082. } else
  24083. {
  24084. painter->drawLine(QLineF(rect.left()+2, rect.center().y(), rect.right()-2, rect.center().y()));
  24085. painter->drawLine(QLineF(rect.left()+2, rect.center().y()-4, rect.left()+2, rect.center().y()+4));
  24086. painter->drawLine(QLineF(rect.right()-2, rect.center().y()-4, rect.right()-2, rect.center().y()+4));
  24087. }
  24088. }
  24089. /* inherits documentation from base class */
  24090. QCPRange QCPErrorBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  24091. {
  24092. if (!mDataPlottable)
  24093. {
  24094. foundRange = false;
  24095. return {};
  24096. }
  24097. QCPRange range;
  24098. bool haveLower = false;
  24099. bool haveUpper = false;
  24100. QCPErrorBarsDataContainer::const_iterator it;
  24101. for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  24102. {
  24103. if (mErrorType == etValueError)
  24104. {
  24105. // error bar doesn't extend in key dimension (except whisker but we ignore that here), so only use data point center
  24106. const double current = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin()));
  24107. if (qIsNaN(current)) continue;
  24108. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  24109. {
  24110. if (current < range.lower || !haveLower)
  24111. {
  24112. range.lower = current;
  24113. haveLower = true;
  24114. }
  24115. if (current > range.upper || !haveUpper)
  24116. {
  24117. range.upper = current;
  24118. haveUpper = true;
  24119. }
  24120. }
  24121. } else // mErrorType == etKeyError
  24122. {
  24123. const double dataKey = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin()));
  24124. if (qIsNaN(dataKey)) continue;
  24125. // plus error:
  24126. double current = dataKey + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus);
  24127. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  24128. {
  24129. if (current > range.upper || !haveUpper)
  24130. {
  24131. range.upper = current;
  24132. haveUpper = true;
  24133. }
  24134. }
  24135. // minus error:
  24136. current = dataKey - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus);
  24137. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  24138. {
  24139. if (current < range.lower || !haveLower)
  24140. {
  24141. range.lower = current;
  24142. haveLower = true;
  24143. }
  24144. }
  24145. }
  24146. }
  24147. if (haveUpper && !haveLower)
  24148. {
  24149. range.lower = range.upper;
  24150. haveLower = true;
  24151. } else if (haveLower && !haveUpper)
  24152. {
  24153. range.upper = range.lower;
  24154. haveUpper = true;
  24155. }
  24156. foundRange = haveLower && haveUpper;
  24157. return range;
  24158. }
  24159. /* inherits documentation from base class */
  24160. QCPRange QCPErrorBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  24161. {
  24162. if (!mDataPlottable)
  24163. {
  24164. foundRange = false;
  24165. return {};
  24166. }
  24167. QCPRange range;
  24168. const bool restrictKeyRange = inKeyRange != QCPRange();
  24169. bool haveLower = false;
  24170. bool haveUpper = false;
  24171. QCPErrorBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin();
  24172. QCPErrorBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd();
  24173. if (mDataPlottable->interface1D()->sortKeyIsMainKey() && restrictKeyRange)
  24174. {
  24175. itBegin = mDataContainer->constBegin()+findBegin(inKeyRange.lower, false);
  24176. itEnd = mDataContainer->constBegin()+findEnd(inKeyRange.upper, false);
  24177. }
  24178. for (QCPErrorBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it)
  24179. {
  24180. if (restrictKeyRange)
  24181. {
  24182. const double dataKey = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin()));
  24183. if (dataKey < inKeyRange.lower || dataKey > inKeyRange.upper)
  24184. continue;
  24185. }
  24186. if (mErrorType == etValueError)
  24187. {
  24188. const double dataValue = mDataPlottable->interface1D()->dataMainValue(int(it-mDataContainer->constBegin()));
  24189. if (qIsNaN(dataValue)) continue;
  24190. // plus error:
  24191. double current = dataValue + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus);
  24192. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  24193. {
  24194. if (current > range.upper || !haveUpper)
  24195. {
  24196. range.upper = current;
  24197. haveUpper = true;
  24198. }
  24199. }
  24200. // minus error:
  24201. current = dataValue - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus);
  24202. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  24203. {
  24204. if (current < range.lower || !haveLower)
  24205. {
  24206. range.lower = current;
  24207. haveLower = true;
  24208. }
  24209. }
  24210. } else // mErrorType == etKeyError
  24211. {
  24212. // error bar doesn't extend in value dimension (except whisker but we ignore that here), so only use data point center
  24213. const double current = mDataPlottable->interface1D()->dataMainValue(int(it-mDataContainer->constBegin()));
  24214. if (qIsNaN(current)) continue;
  24215. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  24216. {
  24217. if (current < range.lower || !haveLower)
  24218. {
  24219. range.lower = current;
  24220. haveLower = true;
  24221. }
  24222. if (current > range.upper || !haveUpper)
  24223. {
  24224. range.upper = current;
  24225. haveUpper = true;
  24226. }
  24227. }
  24228. }
  24229. }
  24230. if (haveUpper && !haveLower)
  24231. {
  24232. range.lower = range.upper;
  24233. haveLower = true;
  24234. } else if (haveLower && !haveUpper)
  24235. {
  24236. range.upper = range.lower;
  24237. haveUpper = true;
  24238. }
  24239. foundRange = haveLower && haveUpper;
  24240. return range;
  24241. }
  24242. /*! \internal
  24243. Calculates the lines that make up the error bar belonging to the data point \a it.
  24244. The resulting lines are added to \a backbones and \a whiskers. The vectors are not cleared, so
  24245. calling this method with different \a it but the same \a backbones and \a whiskers allows to
  24246. accumulate lines for multiple data points.
  24247. This method assumes that \a it is a valid iterator within the bounds of this \ref QCPErrorBars
  24248. instance and within the bounds of the associated data plottable.
  24249. */
  24250. void QCPErrorBars::getErrorBarLines(QCPErrorBarsDataContainer::const_iterator it, QVector<QLineF> &backbones, QVector<QLineF> &whiskers) const
  24251. {
  24252. if (!mDataPlottable) return;
  24253. int index = int(it-mDataContainer->constBegin());
  24254. QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index);
  24255. if (qIsNaN(centerPixel.x()) || qIsNaN(centerPixel.y()))
  24256. return;
  24257. QCPAxis *errorAxis = mErrorType == etValueError ? mValueAxis.data() : mKeyAxis.data();
  24258. QCPAxis *orthoAxis = mErrorType == etValueError ? mKeyAxis.data() : mValueAxis.data();
  24259. const double centerErrorAxisPixel = errorAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
  24260. const double centerOrthoAxisPixel = orthoAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
  24261. const double centerErrorAxisCoord = errorAxis->pixelToCoord(centerErrorAxisPixel); // depending on plottable, this might be different from just mDataPlottable->interface1D()->dataMainKey/Value
  24262. const double symbolGap = mSymbolGap*0.5*errorAxis->pixelOrientation();
  24263. // plus error:
  24264. double errorStart, errorEnd;
  24265. if (!qIsNaN(it->errorPlus))
  24266. {
  24267. errorStart = centerErrorAxisPixel+symbolGap;
  24268. errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord+it->errorPlus);
  24269. if (errorAxis->orientation() == Qt::Vertical)
  24270. {
  24271. if ((errorStart > errorEnd) != errorAxis->rangeReversed())
  24272. backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd));
  24273. whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd));
  24274. } else
  24275. {
  24276. if ((errorStart < errorEnd) != errorAxis->rangeReversed())
  24277. backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel));
  24278. whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5));
  24279. }
  24280. }
  24281. // minus error:
  24282. if (!qIsNaN(it->errorMinus))
  24283. {
  24284. errorStart = centerErrorAxisPixel-symbolGap;
  24285. errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord-it->errorMinus);
  24286. if (errorAxis->orientation() == Qt::Vertical)
  24287. {
  24288. if ((errorStart < errorEnd) != errorAxis->rangeReversed())
  24289. backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd));
  24290. whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd));
  24291. } else
  24292. {
  24293. if ((errorStart > errorEnd) != errorAxis->rangeReversed())
  24294. backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel));
  24295. whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5));
  24296. }
  24297. }
  24298. }
  24299. /*! \internal
  24300. This method outputs the currently visible data range via \a begin and \a end. The returned range
  24301. will also never exceed \a rangeRestriction.
  24302. Since error bars with type \ref etKeyError may extend to arbitrarily positive and negative key
  24303. coordinates relative to their data point key, this method checks all outer error bars whether
  24304. they truly don't reach into the visible portion of the axis rect, by calling \ref
  24305. errorBarVisible. On the other hand error bars with type \ref etValueError that are associated
  24306. with data plottables whose sort key is equal to the main key (see \ref qcpdatacontainer-datatype
  24307. "QCPDataContainer DataType") can be handled very efficiently by finding the visible range of
  24308. error bars through binary search (\ref QCPPlottableInterface1D::findBegin and \ref
  24309. QCPPlottableInterface1D::findEnd).
  24310. If the plottable's sort key is not equal to the main key, this method returns the full data
  24311. range, only restricted by \a rangeRestriction. Drawing optimization then has to be done on a
  24312. point-by-point basis in the \ref draw method.
  24313. */
  24314. void QCPErrorBars::getVisibleDataBounds(QCPErrorBarsDataContainer::const_iterator &begin, QCPErrorBarsDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
  24315. {
  24316. QCPAxis *keyAxis = mKeyAxis.data();
  24317. QCPAxis *valueAxis = mValueAxis.data();
  24318. if (!keyAxis || !valueAxis)
  24319. {
  24320. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  24321. end = mDataContainer->constEnd();
  24322. begin = end;
  24323. return;
  24324. }
  24325. if (!mDataPlottable || rangeRestriction.isEmpty())
  24326. {
  24327. end = mDataContainer->constEnd();
  24328. begin = end;
  24329. return;
  24330. }
  24331. if (!mDataPlottable->interface1D()->sortKeyIsMainKey())
  24332. {
  24333. // if the sort key isn't the main key, it's not possible to find a contiguous range of visible
  24334. // data points, so this method then only applies the range restriction and otherwise returns
  24335. // the full data range. Visibility checks must be done on a per-datapoin-basis during drawing
  24336. QCPDataRange dataRange(0, mDataContainer->size());
  24337. dataRange = dataRange.bounded(rangeRestriction);
  24338. begin = mDataContainer->constBegin()+dataRange.begin();
  24339. end = mDataContainer->constBegin()+dataRange.end();
  24340. return;
  24341. }
  24342. // get visible data range via interface from data plottable, and then restrict to available error data points:
  24343. const int n = qMin(mDataContainer->size(), mDataPlottable->interface1D()->dataCount());
  24344. int beginIndex = mDataPlottable->interface1D()->findBegin(keyAxis->range().lower);
  24345. int endIndex = mDataPlottable->interface1D()->findEnd(keyAxis->range().upper);
  24346. int i = beginIndex;
  24347. while (i > 0 && i < n && i > rangeRestriction.begin())
  24348. {
  24349. if (errorBarVisible(i))
  24350. beginIndex = i;
  24351. --i;
  24352. }
  24353. i = endIndex;
  24354. while (i >= 0 && i < n && i < rangeRestriction.end())
  24355. {
  24356. if (errorBarVisible(i))
  24357. endIndex = i+1;
  24358. ++i;
  24359. }
  24360. QCPDataRange dataRange(beginIndex, endIndex);
  24361. dataRange = dataRange.bounded(rangeRestriction.bounded(QCPDataRange(0, mDataContainer->size())));
  24362. begin = mDataContainer->constBegin()+dataRange.begin();
  24363. end = mDataContainer->constBegin()+dataRange.end();
  24364. }
  24365. /*! \internal
  24366. Calculates the minimum distance in pixels the error bars' representation has from the given \a
  24367. pixelPoint. This is used to determine whether the error bar was clicked or not, e.g. in \ref
  24368. selectTest. The closest data point to \a pixelPoint is returned in \a closestData.
  24369. */
  24370. double QCPErrorBars::pointDistance(const QPointF &pixelPoint, QCPErrorBarsDataContainer::const_iterator &closestData) const
  24371. {
  24372. closestData = mDataContainer->constEnd();
  24373. if (!mDataPlottable || mDataContainer->isEmpty())
  24374. return -1.0;
  24375. if (!mKeyAxis || !mValueAxis)
  24376. {
  24377. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  24378. return -1.0;
  24379. }
  24380. QCPErrorBarsDataContainer::const_iterator begin, end;
  24381. getVisibleDataBounds(begin, end, QCPDataRange(0, dataCount()));
  24382. // calculate minimum distances to error backbones (whiskers are ignored for speed) and find closestData iterator:
  24383. double minDistSqr = (std::numeric_limits<double>::max)();
  24384. QVector<QLineF> backbones, whiskers;
  24385. for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it)
  24386. {
  24387. getErrorBarLines(it, backbones, whiskers);
  24388. foreach (const QLineF &backbone, backbones)
  24389. {
  24390. const double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(backbone);
  24391. if (currentDistSqr < minDistSqr)
  24392. {
  24393. minDistSqr = currentDistSqr;
  24394. closestData = it;
  24395. }
  24396. }
  24397. }
  24398. return qSqrt(minDistSqr);
  24399. }
  24400. /*! \internal
  24401. \note This method is identical to \ref QCPAbstractPlottable1D::getDataSegments but needs to be
  24402. reproduced here since the \ref QCPErrorBars plottable, as a special case that doesn't have its
  24403. own key/value data coordinates, doesn't derive from \ref QCPAbstractPlottable1D. See the
  24404. documentation there for details.
  24405. */
  24406. void QCPErrorBars::getDataSegments(QList<QCPDataRange> &selectedSegments, QList<QCPDataRange> &unselectedSegments) const
  24407. {
  24408. selectedSegments.clear();
  24409. unselectedSegments.clear();
  24410. if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty
  24411. {
  24412. if (selected())
  24413. selectedSegments << QCPDataRange(0, dataCount());
  24414. else
  24415. unselectedSegments << QCPDataRange(0, dataCount());
  24416. } else
  24417. {
  24418. QCPDataSelection sel(selection());
  24419. sel.simplify();
  24420. selectedSegments = sel.dataRanges();
  24421. unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges();
  24422. }
  24423. }
  24424. /*! \internal
  24425. Returns whether the error bar at the specified \a index is visible within the current key axis
  24426. range.
  24427. This method assumes for performance reasons without checking that the key axis, the value axis,
  24428. and the data plottable (\ref setDataPlottable) are not \c nullptr and that \a index is within
  24429. valid bounds of this \ref QCPErrorBars instance and the bounds of the data plottable.
  24430. */
  24431. bool QCPErrorBars::errorBarVisible(int index) const
  24432. {
  24433. QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index);
  24434. const double centerKeyPixel = mKeyAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
  24435. if (qIsNaN(centerKeyPixel))
  24436. return false;
  24437. double keyMin, keyMax;
  24438. if (mErrorType == etKeyError)
  24439. {
  24440. const double centerKey = mKeyAxis->pixelToCoord(centerKeyPixel);
  24441. const double errorPlus = mDataContainer->at(index).errorPlus;
  24442. const double errorMinus = mDataContainer->at(index).errorMinus;
  24443. keyMax = centerKey+(qIsNaN(errorPlus) ? 0 : errorPlus);
  24444. keyMin = centerKey-(qIsNaN(errorMinus) ? 0 : errorMinus);
  24445. } else // mErrorType == etValueError
  24446. {
  24447. keyMax = mKeyAxis->pixelToCoord(centerKeyPixel+mWhiskerWidth*0.5*mKeyAxis->pixelOrientation());
  24448. keyMin = mKeyAxis->pixelToCoord(centerKeyPixel-mWhiskerWidth*0.5*mKeyAxis->pixelOrientation());
  24449. }
  24450. return ((keyMax > mKeyAxis->range().lower) && (keyMin < mKeyAxis->range().upper));
  24451. }
  24452. /*! \internal
  24453. Returns whether \a line intersects (or is contained in) \a pixelRect.
  24454. \a line is assumed to be either perfectly horizontal or perfectly vertical, as is the case for
  24455. error bar lines.
  24456. */
  24457. bool QCPErrorBars::rectIntersectsLine(const QRectF &pixelRect, const QLineF &line) const
  24458. {
  24459. if (pixelRect.left() > line.x1() && pixelRect.left() > line.x2())
  24460. return false;
  24461. else if (pixelRect.right() < line.x1() && pixelRect.right() < line.x2())
  24462. return false;
  24463. else if (pixelRect.top() > line.y1() && pixelRect.top() > line.y2())
  24464. return false;
  24465. else if (pixelRect.bottom() < line.y1() && pixelRect.bottom() < line.y2())
  24466. return false;
  24467. else
  24468. return true;
  24469. }
  24470. /* end of 'src/plottables/plottable-errorbar.cpp' */
  24471. /* including file 'src/items/item-straightline.cpp' */
  24472. /* modified 2021-03-29T02:30:44, size 7596 */
  24473. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24474. //////////////////// QCPItemStraightLine
  24475. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24476. /*! \class QCPItemStraightLine
  24477. \brief A straight line that spans infinitely in both directions
  24478. \image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid blue discs are positions."
  24479. It has two positions, \a point1 and \a point2, which define the straight line.
  24480. */
  24481. /*!
  24482. Creates a straight line item and sets default values.
  24483. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24484. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24485. */
  24486. QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) :
  24487. QCPAbstractItem(parentPlot),
  24488. point1(createPosition(QLatin1String("point1"))),
  24489. point2(createPosition(QLatin1String("point2")))
  24490. {
  24491. point1->setCoords(0, 0);
  24492. point2->setCoords(1, 1);
  24493. setPen(QPen(Qt::black));
  24494. setSelectedPen(QPen(Qt::blue,2));
  24495. }
  24496. QCPItemStraightLine::~QCPItemStraightLine()
  24497. {
  24498. }
  24499. /*!
  24500. Sets the pen that will be used to draw the line
  24501. \see setSelectedPen
  24502. */
  24503. void QCPItemStraightLine::setPen(const QPen &pen)
  24504. {
  24505. mPen = pen;
  24506. }
  24507. /*!
  24508. Sets the pen that will be used to draw the line when selected
  24509. \see setPen, setSelected
  24510. */
  24511. void QCPItemStraightLine::setSelectedPen(const QPen &pen)
  24512. {
  24513. mSelectedPen = pen;
  24514. }
  24515. /* inherits documentation from base class */
  24516. double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  24517. {
  24518. Q_UNUSED(details)
  24519. if (onlySelectable && !mSelectable)
  24520. return -1;
  24521. return QCPVector2D(pos).distanceToStraightLine(point1->pixelPosition(), point2->pixelPosition()-point1->pixelPosition());
  24522. }
  24523. /* inherits documentation from base class */
  24524. void QCPItemStraightLine::draw(QCPPainter *painter)
  24525. {
  24526. QCPVector2D start(point1->pixelPosition());
  24527. QCPVector2D end(point2->pixelPosition());
  24528. // get visible segment of straight line inside clipRect:
  24529. double clipPad = mainPen().widthF();
  24530. QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
  24531. // paint visible segment, if existent:
  24532. if (!line.isNull())
  24533. {
  24534. painter->setPen(mainPen());
  24535. painter->drawLine(line);
  24536. }
  24537. }
  24538. /*! \internal
  24539. Returns the section of the straight line defined by \a base and direction vector \a
  24540. vec, that is visible in the specified \a rect.
  24541. This is a helper function for \ref draw.
  24542. */
  24543. QLineF QCPItemStraightLine::getRectClippedStraightLine(const QCPVector2D &base, const QCPVector2D &vec, const QRectF &rect) const
  24544. {
  24545. double bx, by;
  24546. double gamma;
  24547. QLineF result;
  24548. if (qFuzzyCompare(vec.x(), 0) && qFuzzyCompare(vec.y(), 0))
  24549. return result;
  24550. if (qFuzzyIsNull(vec.x())) // line is vertical
  24551. {
  24552. // check top of rect:
  24553. bx = rect.left();
  24554. by = rect.top();
  24555. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  24556. if (gamma >= 0 && gamma <= rect.width())
  24557. result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical
  24558. } else if (qFuzzyIsNull(vec.y())) // line is horizontal
  24559. {
  24560. // check left of rect:
  24561. bx = rect.left();
  24562. by = rect.top();
  24563. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  24564. if (gamma >= 0 && gamma <= rect.height())
  24565. result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal
  24566. } else // line is skewed
  24567. {
  24568. QList<QCPVector2D> pointVectors;
  24569. // check top of rect:
  24570. bx = rect.left();
  24571. by = rect.top();
  24572. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  24573. if (gamma >= 0 && gamma <= rect.width())
  24574. pointVectors.append(QCPVector2D(bx+gamma, by));
  24575. // check bottom of rect:
  24576. bx = rect.left();
  24577. by = rect.bottom();
  24578. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  24579. if (gamma >= 0 && gamma <= rect.width())
  24580. pointVectors.append(QCPVector2D(bx+gamma, by));
  24581. // check left of rect:
  24582. bx = rect.left();
  24583. by = rect.top();
  24584. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  24585. if (gamma >= 0 && gamma <= rect.height())
  24586. pointVectors.append(QCPVector2D(bx, by+gamma));
  24587. // check right of rect:
  24588. bx = rect.right();
  24589. by = rect.top();
  24590. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  24591. if (gamma >= 0 && gamma <= rect.height())
  24592. pointVectors.append(QCPVector2D(bx, by+gamma));
  24593. // evaluate points:
  24594. if (pointVectors.size() == 2)
  24595. {
  24596. result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
  24597. } else if (pointVectors.size() > 2)
  24598. {
  24599. // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
  24600. double distSqrMax = 0;
  24601. QCPVector2D pv1, pv2;
  24602. for (int i=0; i<pointVectors.size()-1; ++i)
  24603. {
  24604. for (int k=i+1; k<pointVectors.size(); ++k)
  24605. {
  24606. double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
  24607. if (distSqr > distSqrMax)
  24608. {
  24609. pv1 = pointVectors.at(i);
  24610. pv2 = pointVectors.at(k);
  24611. distSqrMax = distSqr;
  24612. }
  24613. }
  24614. }
  24615. result.setPoints(pv1.toPointF(), pv2.toPointF());
  24616. }
  24617. }
  24618. return result;
  24619. }
  24620. /*! \internal
  24621. Returns the pen that should be used for drawing lines. Returns mPen when the
  24622. item is not selected and mSelectedPen when it is.
  24623. */
  24624. QPen QCPItemStraightLine::mainPen() const
  24625. {
  24626. return mSelected ? mSelectedPen : mPen;
  24627. }
  24628. /* end of 'src/items/item-straightline.cpp' */
  24629. /* including file 'src/items/item-line.cpp' */
  24630. /* modified 2021-03-29T02:30:44, size 8525 */
  24631. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24632. //////////////////// QCPItemLine
  24633. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24634. /*! \class QCPItemLine
  24635. \brief A line from one point to another
  24636. \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions."
  24637. It has two positions, \a start and \a end, which define the end points of the line.
  24638. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow.
  24639. */
  24640. /*!
  24641. Creates a line item and sets default values.
  24642. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24643. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24644. */
  24645. QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) :
  24646. QCPAbstractItem(parentPlot),
  24647. start(createPosition(QLatin1String("start"))),
  24648. end(createPosition(QLatin1String("end")))
  24649. {
  24650. start->setCoords(0, 0);
  24651. end->setCoords(1, 1);
  24652. setPen(QPen(Qt::black));
  24653. setSelectedPen(QPen(Qt::blue,2));
  24654. }
  24655. QCPItemLine::~QCPItemLine()
  24656. {
  24657. }
  24658. /*!
  24659. Sets the pen that will be used to draw the line
  24660. \see setSelectedPen
  24661. */
  24662. void QCPItemLine::setPen(const QPen &pen)
  24663. {
  24664. mPen = pen;
  24665. }
  24666. /*!
  24667. Sets the pen that will be used to draw the line when selected
  24668. \see setPen, setSelected
  24669. */
  24670. void QCPItemLine::setSelectedPen(const QPen &pen)
  24671. {
  24672. mSelectedPen = pen;
  24673. }
  24674. /*!
  24675. Sets the line ending style of the head. The head corresponds to the \a end position.
  24676. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  24677. a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
  24678. \see setTail
  24679. */
  24680. void QCPItemLine::setHead(const QCPLineEnding &head)
  24681. {
  24682. mHead = head;
  24683. }
  24684. /*!
  24685. Sets the line ending style of the tail. The tail corresponds to the \a start position.
  24686. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  24687. a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
  24688. \see setHead
  24689. */
  24690. void QCPItemLine::setTail(const QCPLineEnding &tail)
  24691. {
  24692. mTail = tail;
  24693. }
  24694. /* inherits documentation from base class */
  24695. double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  24696. {
  24697. Q_UNUSED(details)
  24698. if (onlySelectable && !mSelectable)
  24699. return -1;
  24700. return qSqrt(QCPVector2D(pos).distanceSquaredToLine(start->pixelPosition(), end->pixelPosition()));
  24701. }
  24702. /* inherits documentation from base class */
  24703. void QCPItemLine::draw(QCPPainter *painter)
  24704. {
  24705. QCPVector2D startVec(start->pixelPosition());
  24706. QCPVector2D endVec(end->pixelPosition());
  24707. if (qFuzzyIsNull((startVec-endVec).lengthSquared()))
  24708. return;
  24709. // get visible segment of straight line inside clipRect:
  24710. double clipPad = qMax(mHead.boundingDistance(), mTail.boundingDistance());
  24711. clipPad = qMax(clipPad, double(mainPen().widthF()));
  24712. QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
  24713. // paint visible segment, if existent:
  24714. if (!line.isNull())
  24715. {
  24716. painter->setPen(mainPen());
  24717. painter->drawLine(line);
  24718. painter->setBrush(Qt::SolidPattern);
  24719. if (mTail.style() != QCPLineEnding::esNone)
  24720. mTail.draw(painter, startVec, startVec-endVec);
  24721. if (mHead.style() != QCPLineEnding::esNone)
  24722. mHead.draw(painter, endVec, endVec-startVec);
  24723. }
  24724. }
  24725. /*! \internal
  24726. Returns the section of the line defined by \a start and \a end, that is visible in the specified
  24727. \a rect.
  24728. This is a helper function for \ref draw.
  24729. */
  24730. QLineF QCPItemLine::getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRectF &rect) const
  24731. {
  24732. bool containsStart = rect.contains(start.x(), start.y());
  24733. bool containsEnd = rect.contains(end.x(), end.y());
  24734. if (containsStart && containsEnd)
  24735. return {start.toPointF(), end.toPointF()};
  24736. QCPVector2D base = start;
  24737. QCPVector2D vec = end-start;
  24738. double bx, by;
  24739. double gamma, mu;
  24740. QLineF result;
  24741. QList<QCPVector2D> pointVectors;
  24742. if (!qFuzzyIsNull(vec.y())) // line is not horizontal
  24743. {
  24744. // check top of rect:
  24745. bx = rect.left();
  24746. by = rect.top();
  24747. mu = (by-base.y())/vec.y();
  24748. if (mu >= 0 && mu <= 1)
  24749. {
  24750. gamma = base.x()-bx + mu*vec.x();
  24751. if (gamma >= 0 && gamma <= rect.width())
  24752. pointVectors.append(QCPVector2D(bx+gamma, by));
  24753. }
  24754. // check bottom of rect:
  24755. bx = rect.left();
  24756. by = rect.bottom();
  24757. mu = (by-base.y())/vec.y();
  24758. if (mu >= 0 && mu <= 1)
  24759. {
  24760. gamma = base.x()-bx + mu*vec.x();
  24761. if (gamma >= 0 && gamma <= rect.width())
  24762. pointVectors.append(QCPVector2D(bx+gamma, by));
  24763. }
  24764. }
  24765. if (!qFuzzyIsNull(vec.x())) // line is not vertical
  24766. {
  24767. // check left of rect:
  24768. bx = rect.left();
  24769. by = rect.top();
  24770. mu = (bx-base.x())/vec.x();
  24771. if (mu >= 0 && mu <= 1)
  24772. {
  24773. gamma = base.y()-by + mu*vec.y();
  24774. if (gamma >= 0 && gamma <= rect.height())
  24775. pointVectors.append(QCPVector2D(bx, by+gamma));
  24776. }
  24777. // check right of rect:
  24778. bx = rect.right();
  24779. by = rect.top();
  24780. mu = (bx-base.x())/vec.x();
  24781. if (mu >= 0 && mu <= 1)
  24782. {
  24783. gamma = base.y()-by + mu*vec.y();
  24784. if (gamma >= 0 && gamma <= rect.height())
  24785. pointVectors.append(QCPVector2D(bx, by+gamma));
  24786. }
  24787. }
  24788. if (containsStart)
  24789. pointVectors.append(start);
  24790. if (containsEnd)
  24791. pointVectors.append(end);
  24792. // evaluate points:
  24793. if (pointVectors.size() == 2)
  24794. {
  24795. result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
  24796. } else if (pointVectors.size() > 2)
  24797. {
  24798. // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
  24799. double distSqrMax = 0;
  24800. QCPVector2D pv1, pv2;
  24801. for (int i=0; i<pointVectors.size()-1; ++i)
  24802. {
  24803. for (int k=i+1; k<pointVectors.size(); ++k)
  24804. {
  24805. double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
  24806. if (distSqr > distSqrMax)
  24807. {
  24808. pv1 = pointVectors.at(i);
  24809. pv2 = pointVectors.at(k);
  24810. distSqrMax = distSqr;
  24811. }
  24812. }
  24813. }
  24814. result.setPoints(pv1.toPointF(), pv2.toPointF());
  24815. }
  24816. return result;
  24817. }
  24818. /*! \internal
  24819. Returns the pen that should be used for drawing lines. Returns mPen when the
  24820. item is not selected and mSelectedPen when it is.
  24821. */
  24822. QPen QCPItemLine::mainPen() const
  24823. {
  24824. return mSelected ? mSelectedPen : mPen;
  24825. }
  24826. /* end of 'src/items/item-line.cpp' */
  24827. /* including file 'src/items/item-curve.cpp' */
  24828. /* modified 2021-03-29T02:30:44, size 7273 */
  24829. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24830. //////////////////// QCPItemCurve
  24831. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24832. /*! \class QCPItemCurve
  24833. \brief A curved line from one point to another
  24834. \image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are positions."
  24835. It has four positions, \a start and \a end, which define the end points of the line, and two
  24836. control points which define the direction the line exits from the start and the direction from
  24837. which it approaches the end: \a startDir and \a endDir.
  24838. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an
  24839. arrow.
  24840. Often it is desirable for the control points to stay at fixed relative positions to the start/end
  24841. point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start,
  24842. and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir.
  24843. */
  24844. /*!
  24845. Creates a curve item and sets default values.
  24846. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24847. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24848. */
  24849. QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) :
  24850. QCPAbstractItem(parentPlot),
  24851. start(createPosition(QLatin1String("start"))),
  24852. startDir(createPosition(QLatin1String("startDir"))),
  24853. endDir(createPosition(QLatin1String("endDir"))),
  24854. end(createPosition(QLatin1String("end")))
  24855. {
  24856. start->setCoords(0, 0);
  24857. startDir->setCoords(0.5, 0);
  24858. endDir->setCoords(0, 0.5);
  24859. end->setCoords(1, 1);
  24860. setPen(QPen(Qt::black));
  24861. setSelectedPen(QPen(Qt::blue,2));
  24862. }
  24863. QCPItemCurve::~QCPItemCurve()
  24864. {
  24865. }
  24866. /*!
  24867. Sets the pen that will be used to draw the line
  24868. \see setSelectedPen
  24869. */
  24870. void QCPItemCurve::setPen(const QPen &pen)
  24871. {
  24872. mPen = pen;
  24873. }
  24874. /*!
  24875. Sets the pen that will be used to draw the line when selected
  24876. \see setPen, setSelected
  24877. */
  24878. void QCPItemCurve::setSelectedPen(const QPen &pen)
  24879. {
  24880. mSelectedPen = pen;
  24881. }
  24882. /*!
  24883. Sets the line ending style of the head. The head corresponds to the \a end position.
  24884. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  24885. a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
  24886. \see setTail
  24887. */
  24888. void QCPItemCurve::setHead(const QCPLineEnding &head)
  24889. {
  24890. mHead = head;
  24891. }
  24892. /*!
  24893. Sets the line ending style of the tail. The tail corresponds to the \a start position.
  24894. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  24895. a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
  24896. \see setHead
  24897. */
  24898. void QCPItemCurve::setTail(const QCPLineEnding &tail)
  24899. {
  24900. mTail = tail;
  24901. }
  24902. /* inherits documentation from base class */
  24903. double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  24904. {
  24905. Q_UNUSED(details)
  24906. if (onlySelectable && !mSelectable)
  24907. return -1;
  24908. QPointF startVec(start->pixelPosition());
  24909. QPointF startDirVec(startDir->pixelPosition());
  24910. QPointF endDirVec(endDir->pixelPosition());
  24911. QPointF endVec(end->pixelPosition());
  24912. QPainterPath cubicPath(startVec);
  24913. cubicPath.cubicTo(startDirVec, endDirVec, endVec);
  24914. QList<QPolygonF> polygons = cubicPath.toSubpathPolygons();
  24915. if (polygons.isEmpty())
  24916. return -1;
  24917. const QPolygonF polygon = polygons.first();
  24918. QCPVector2D p(pos);
  24919. double minDistSqr = (std::numeric_limits<double>::max)();
  24920. for (int i=1; i<polygon.size(); ++i)
  24921. {
  24922. double distSqr = p.distanceSquaredToLine(polygon.at(i-1), polygon.at(i));
  24923. if (distSqr < minDistSqr)
  24924. minDistSqr = distSqr;
  24925. }
  24926. return qSqrt(minDistSqr);
  24927. }
  24928. /* inherits documentation from base class */
  24929. void QCPItemCurve::draw(QCPPainter *painter)
  24930. {
  24931. QCPVector2D startVec(start->pixelPosition());
  24932. QCPVector2D startDirVec(startDir->pixelPosition());
  24933. QCPVector2D endDirVec(endDir->pixelPosition());
  24934. QCPVector2D endVec(end->pixelPosition());
  24935. if ((endVec-startVec).length() > 1e10) // too large curves cause crash
  24936. return;
  24937. QPainterPath cubicPath(startVec.toPointF());
  24938. cubicPath.cubicTo(startDirVec.toPointF(), endDirVec.toPointF(), endVec.toPointF());
  24939. // paint visible segment, if existent:
  24940. QRectF clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
  24941. QRectF cubicRect = cubicPath.controlPointRect();
  24942. if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position
  24943. cubicRect.adjust(0, 0, 1, 1);
  24944. if (clip.intersects(cubicRect))
  24945. {
  24946. painter->setPen(mainPen());
  24947. painter->drawPath(cubicPath);
  24948. painter->setBrush(Qt::SolidPattern);
  24949. if (mTail.style() != QCPLineEnding::esNone)
  24950. mTail.draw(painter, startVec, M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI);
  24951. if (mHead.style() != QCPLineEnding::esNone)
  24952. mHead.draw(painter, endVec, -cubicPath.angleAtPercent(1)/180.0*M_PI);
  24953. }
  24954. }
  24955. /*! \internal
  24956. Returns the pen that should be used for drawing lines. Returns mPen when the
  24957. item is not selected and mSelectedPen when it is.
  24958. */
  24959. QPen QCPItemCurve::mainPen() const
  24960. {
  24961. return mSelected ? mSelectedPen : mPen;
  24962. }
  24963. /* end of 'src/items/item-curve.cpp' */
  24964. /* including file 'src/items/item-rect.cpp' */
  24965. /* modified 2021-03-29T02:30:44, size 6472 */
  24966. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24967. //////////////////// QCPItemRect
  24968. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24969. /*! \class QCPItemRect
  24970. \brief A rectangle
  24971. \image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions."
  24972. It has two positions, \a topLeft and \a bottomRight, which define the rectangle.
  24973. */
  24974. /*!
  24975. Creates a rectangle item and sets default values.
  24976. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24977. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24978. */
  24979. QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) :
  24980. QCPAbstractItem(parentPlot),
  24981. topLeft(createPosition(QLatin1String("topLeft"))),
  24982. bottomRight(createPosition(QLatin1String("bottomRight"))),
  24983. top(createAnchor(QLatin1String("top"), aiTop)),
  24984. topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
  24985. right(createAnchor(QLatin1String("right"), aiRight)),
  24986. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  24987. bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
  24988. left(createAnchor(QLatin1String("left"), aiLeft))
  24989. {
  24990. topLeft->setCoords(0, 1);
  24991. bottomRight->setCoords(1, 0);
  24992. setPen(QPen(Qt::black));
  24993. setSelectedPen(QPen(Qt::blue,2));
  24994. setBrush(Qt::NoBrush);
  24995. setSelectedBrush(Qt::NoBrush);
  24996. }
  24997. QCPItemRect::~QCPItemRect()
  24998. {
  24999. }
  25000. /*!
  25001. Sets the pen that will be used to draw the line of the rectangle
  25002. \see setSelectedPen, setBrush
  25003. */
  25004. void QCPItemRect::setPen(const QPen &pen)
  25005. {
  25006. mPen = pen;
  25007. }
  25008. /*!
  25009. Sets the pen that will be used to draw the line of the rectangle when selected
  25010. \see setPen, setSelected
  25011. */
  25012. void QCPItemRect::setSelectedPen(const QPen &pen)
  25013. {
  25014. mSelectedPen = pen;
  25015. }
  25016. /*!
  25017. Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to
  25018. Qt::NoBrush.
  25019. \see setSelectedBrush, setPen
  25020. */
  25021. void QCPItemRect::setBrush(const QBrush &brush)
  25022. {
  25023. mBrush = brush;
  25024. }
  25025. /*!
  25026. Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a
  25027. brush to Qt::NoBrush.
  25028. \see setBrush
  25029. */
  25030. void QCPItemRect::setSelectedBrush(const QBrush &brush)
  25031. {
  25032. mSelectedBrush = brush;
  25033. }
  25034. /* inherits documentation from base class */
  25035. double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25036. {
  25037. Q_UNUSED(details)
  25038. if (onlySelectable && !mSelectable)
  25039. return -1;
  25040. QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()).normalized();
  25041. bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
  25042. return rectDistance(rect, pos, filledRect);
  25043. }
  25044. /* inherits documentation from base class */
  25045. void QCPItemRect::draw(QCPPainter *painter)
  25046. {
  25047. QPointF p1 = topLeft->pixelPosition();
  25048. QPointF p2 = bottomRight->pixelPosition();
  25049. if (p1.toPoint() == p2.toPoint())
  25050. return;
  25051. QRectF rect = QRectF(p1, p2).normalized();
  25052. double clipPad = mainPen().widthF();
  25053. QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  25054. if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect
  25055. {
  25056. painter->setPen(mainPen());
  25057. painter->setBrush(mainBrush());
  25058. painter->drawRect(rect);
  25059. }
  25060. }
  25061. /* inherits documentation from base class */
  25062. QPointF QCPItemRect::anchorPixelPosition(int anchorId) const
  25063. {
  25064. QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition());
  25065. switch (anchorId)
  25066. {
  25067. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  25068. case aiTopRight: return rect.topRight();
  25069. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  25070. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  25071. case aiBottomLeft: return rect.bottomLeft();
  25072. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
  25073. }
  25074. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  25075. return {};
  25076. }
  25077. /*! \internal
  25078. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  25079. and mSelectedPen when it is.
  25080. */
  25081. QPen QCPItemRect::mainPen() const
  25082. {
  25083. return mSelected ? mSelectedPen : mPen;
  25084. }
  25085. /*! \internal
  25086. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  25087. is not selected and mSelectedBrush when it is.
  25088. */
  25089. QBrush QCPItemRect::mainBrush() const
  25090. {
  25091. return mSelected ? mSelectedBrush : mBrush;
  25092. }
  25093. /* end of 'src/items/item-rect.cpp' */
  25094. /* including file 'src/items/item-text.cpp' */
  25095. /* modified 2021-03-29T02:30:44, size 13335 */
  25096. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25097. //////////////////// QCPItemText
  25098. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25099. /*! \class QCPItemText
  25100. \brief A text label
  25101. \image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions."
  25102. Its position is defined by the member \a position and the setting of \ref setPositionAlignment.
  25103. The latter controls which part of the text rect shall be aligned with \a position.
  25104. The text alignment itself (i.e. left, center, right) can be controlled with \ref
  25105. setTextAlignment.
  25106. The text may be rotated around the \a position point with \ref setRotation.
  25107. */
  25108. /*!
  25109. Creates a text item and sets default values.
  25110. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  25111. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  25112. */
  25113. QCPItemText::QCPItemText(QCustomPlot *parentPlot) :
  25114. QCPAbstractItem(parentPlot),
  25115. position(createPosition(QLatin1String("position"))),
  25116. topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft)),
  25117. top(createAnchor(QLatin1String("top"), aiTop)),
  25118. topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
  25119. right(createAnchor(QLatin1String("right"), aiRight)),
  25120. bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)),
  25121. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  25122. bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
  25123. left(createAnchor(QLatin1String("left"), aiLeft)),
  25124. mText(QLatin1String("text")),
  25125. mPositionAlignment(Qt::AlignCenter),
  25126. mTextAlignment(Qt::AlignTop|Qt::AlignHCenter),
  25127. mRotation(0)
  25128. {
  25129. position->setCoords(0, 0);
  25130. setPen(Qt::NoPen);
  25131. setSelectedPen(Qt::NoPen);
  25132. setBrush(Qt::NoBrush);
  25133. setSelectedBrush(Qt::NoBrush);
  25134. setColor(Qt::black);
  25135. setSelectedColor(Qt::blue);
  25136. }
  25137. QCPItemText::~QCPItemText()
  25138. {
  25139. }
  25140. /*!
  25141. Sets the color of the text.
  25142. */
  25143. void QCPItemText::setColor(const QColor &color)
  25144. {
  25145. mColor = color;
  25146. }
  25147. /*!
  25148. Sets the color of the text that will be used when the item is selected.
  25149. */
  25150. void QCPItemText::setSelectedColor(const QColor &color)
  25151. {
  25152. mSelectedColor = color;
  25153. }
  25154. /*!
  25155. Sets the pen that will be used do draw a rectangular border around the text. To disable the
  25156. border, set \a pen to Qt::NoPen.
  25157. \see setSelectedPen, setBrush, setPadding
  25158. */
  25159. void QCPItemText::setPen(const QPen &pen)
  25160. {
  25161. mPen = pen;
  25162. }
  25163. /*!
  25164. Sets the pen that will be used do draw a rectangular border around the text, when the item is
  25165. selected. To disable the border, set \a pen to Qt::NoPen.
  25166. \see setPen
  25167. */
  25168. void QCPItemText::setSelectedPen(const QPen &pen)
  25169. {
  25170. mSelectedPen = pen;
  25171. }
  25172. /*!
  25173. Sets the brush that will be used do fill the background of the text. To disable the
  25174. background, set \a brush to Qt::NoBrush.
  25175. \see setSelectedBrush, setPen, setPadding
  25176. */
  25177. void QCPItemText::setBrush(const QBrush &brush)
  25178. {
  25179. mBrush = brush;
  25180. }
  25181. /*!
  25182. Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the
  25183. background, set \a brush to Qt::NoBrush.
  25184. \see setBrush
  25185. */
  25186. void QCPItemText::setSelectedBrush(const QBrush &brush)
  25187. {
  25188. mSelectedBrush = brush;
  25189. }
  25190. /*!
  25191. Sets the font of the text.
  25192. \see setSelectedFont, setColor
  25193. */
  25194. void QCPItemText::setFont(const QFont &font)
  25195. {
  25196. mFont = font;
  25197. }
  25198. /*!
  25199. Sets the font of the text that will be used when the item is selected.
  25200. \see setFont
  25201. */
  25202. void QCPItemText::setSelectedFont(const QFont &font)
  25203. {
  25204. mSelectedFont = font;
  25205. }
  25206. /*!
  25207. Sets the text that will be displayed. Multi-line texts are supported by inserting a line break
  25208. character, e.g. '\n'.
  25209. \see setFont, setColor, setTextAlignment
  25210. */
  25211. void QCPItemText::setText(const QString &text)
  25212. {
  25213. mText = text;
  25214. }
  25215. /*!
  25216. Sets which point of the text rect shall be aligned with \a position.
  25217. Examples:
  25218. \li If \a alignment is <tt>Qt::AlignHCenter | Qt::AlignTop</tt>, the text will be positioned such
  25219. that the top of the text rect will be horizontally centered on \a position.
  25220. \li If \a alignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt>, \a position will indicate the
  25221. bottom left corner of the text rect.
  25222. If you want to control the alignment of (multi-lined) text within the text rect, use \ref
  25223. setTextAlignment.
  25224. */
  25225. void QCPItemText::setPositionAlignment(Qt::Alignment alignment)
  25226. {
  25227. mPositionAlignment = alignment;
  25228. }
  25229. /*!
  25230. Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or Qt::AlignRight).
  25231. */
  25232. void QCPItemText::setTextAlignment(Qt::Alignment alignment)
  25233. {
  25234. mTextAlignment = alignment;
  25235. }
  25236. /*!
  25237. Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated
  25238. around \a position.
  25239. */
  25240. void QCPItemText::setRotation(double degrees)
  25241. {
  25242. mRotation = degrees;
  25243. }
  25244. /*!
  25245. Sets the distance between the border of the text rectangle and the text. The appearance (and
  25246. visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush.
  25247. */
  25248. void QCPItemText::setPadding(const QMargins &padding)
  25249. {
  25250. mPadding = padding;
  25251. }
  25252. /* inherits documentation from base class */
  25253. double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25254. {
  25255. Q_UNUSED(details)
  25256. if (onlySelectable && !mSelectable)
  25257. return -1;
  25258. // The rect may be rotated, so we transform the actual clicked pos to the rotated
  25259. // coordinate system, so we can use the normal rectDistance function for non-rotated rects:
  25260. QPointF positionPixels(position->pixelPosition());
  25261. QTransform inputTransform;
  25262. inputTransform.translate(positionPixels.x(), positionPixels.y());
  25263. inputTransform.rotate(-mRotation);
  25264. inputTransform.translate(-positionPixels.x(), -positionPixels.y());
  25265. QPointF rotatedPos = inputTransform.map(pos);
  25266. QFontMetrics fontMetrics(mFont);
  25267. QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  25268. QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  25269. QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment);
  25270. textBoxRect.moveTopLeft(textPos.toPoint());
  25271. return rectDistance(textBoxRect, rotatedPos, true);
  25272. }
  25273. /* inherits documentation from base class */
  25274. void QCPItemText::draw(QCPPainter *painter)
  25275. {
  25276. QPointF pos(position->pixelPosition());
  25277. QTransform transform = painter->transform();
  25278. transform.translate(pos.x(), pos.y());
  25279. if (!qFuzzyIsNull(mRotation))
  25280. transform.rotate(mRotation);
  25281. painter->setFont(mainFont());
  25282. QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  25283. QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  25284. QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
  25285. textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top()));
  25286. textBoxRect.moveTopLeft(textPos.toPoint());
  25287. double clipPad = mainPen().widthF();
  25288. QRectF boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  25289. if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect())))
  25290. {
  25291. painter->setTransform(transform);
  25292. if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) ||
  25293. (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0))
  25294. {
  25295. painter->setPen(mainPen());
  25296. painter->setBrush(mainBrush());
  25297. painter->drawRect(textBoxRect);
  25298. }
  25299. painter->setBrush(Qt::NoBrush);
  25300. painter->setPen(QPen(mainColor()));
  25301. painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText);
  25302. }
  25303. }
  25304. /* inherits documentation from base class */
  25305. QPointF QCPItemText::anchorPixelPosition(int anchorId) const
  25306. {
  25307. // get actual rect points (pretty much copied from draw function):
  25308. QPointF pos(position->pixelPosition());
  25309. QTransform transform;
  25310. transform.translate(pos.x(), pos.y());
  25311. if (!qFuzzyIsNull(mRotation))
  25312. transform.rotate(mRotation);
  25313. QFontMetrics fontMetrics(mainFont());
  25314. QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  25315. QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  25316. QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
  25317. textBoxRect.moveTopLeft(textPos.toPoint());
  25318. QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect));
  25319. switch (anchorId)
  25320. {
  25321. case aiTopLeft: return rectPoly.at(0);
  25322. case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5;
  25323. case aiTopRight: return rectPoly.at(1);
  25324. case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5;
  25325. case aiBottomRight: return rectPoly.at(2);
  25326. case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5;
  25327. case aiBottomLeft: return rectPoly.at(3);
  25328. case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5;
  25329. }
  25330. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  25331. return {};
  25332. }
  25333. /*! \internal
  25334. Returns the point that must be given to the QPainter::drawText function (which expects the top
  25335. left point of the text rect), according to the position \a pos, the text bounding box \a rect and
  25336. the requested \a positionAlignment.
  25337. For example, if \a positionAlignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt> the returned point
  25338. will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally
  25339. drawn at that point, the lower left corner of the resulting text rect is at \a pos.
  25340. */
  25341. QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const
  25342. {
  25343. if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop))
  25344. return pos;
  25345. QPointF result = pos; // start at top left
  25346. if (positionAlignment.testFlag(Qt::AlignHCenter))
  25347. result.rx() -= rect.width()/2.0;
  25348. else if (positionAlignment.testFlag(Qt::AlignRight))
  25349. result.rx() -= rect.width();
  25350. if (positionAlignment.testFlag(Qt::AlignVCenter))
  25351. result.ry() -= rect.height()/2.0;
  25352. else if (positionAlignment.testFlag(Qt::AlignBottom))
  25353. result.ry() -= rect.height();
  25354. return result;
  25355. }
  25356. /*! \internal
  25357. Returns the font that should be used for drawing text. Returns mFont when the item is not selected
  25358. and mSelectedFont when it is.
  25359. */
  25360. QFont QCPItemText::mainFont() const
  25361. {
  25362. return mSelected ? mSelectedFont : mFont;
  25363. }
  25364. /*! \internal
  25365. Returns the color that should be used for drawing text. Returns mColor when the item is not
  25366. selected and mSelectedColor when it is.
  25367. */
  25368. QColor QCPItemText::mainColor() const
  25369. {
  25370. return mSelected ? mSelectedColor : mColor;
  25371. }
  25372. /*! \internal
  25373. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  25374. and mSelectedPen when it is.
  25375. */
  25376. QPen QCPItemText::mainPen() const
  25377. {
  25378. return mSelected ? mSelectedPen : mPen;
  25379. }
  25380. /*! \internal
  25381. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  25382. is not selected and mSelectedBrush when it is.
  25383. */
  25384. QBrush QCPItemText::mainBrush() const
  25385. {
  25386. return mSelected ? mSelectedBrush : mBrush;
  25387. }
  25388. /* end of 'src/items/item-text.cpp' */
  25389. /* including file 'src/items/item-ellipse.cpp' */
  25390. /* modified 2021-03-29T02:30:44, size 7881 */
  25391. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25392. //////////////////// QCPItemEllipse
  25393. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25394. /*! \class QCPItemEllipse
  25395. \brief An ellipse
  25396. \image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions."
  25397. It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be drawn in.
  25398. */
  25399. /*!
  25400. Creates an ellipse item and sets default values.
  25401. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  25402. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  25403. */
  25404. QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) :
  25405. QCPAbstractItem(parentPlot),
  25406. topLeft(createPosition(QLatin1String("topLeft"))),
  25407. bottomRight(createPosition(QLatin1String("bottomRight"))),
  25408. topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim)),
  25409. top(createAnchor(QLatin1String("top"), aiTop)),
  25410. topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim)),
  25411. right(createAnchor(QLatin1String("right"), aiRight)),
  25412. bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim)),
  25413. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  25414. bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim)),
  25415. left(createAnchor(QLatin1String("left"), aiLeft)),
  25416. center(createAnchor(QLatin1String("center"), aiCenter))
  25417. {
  25418. topLeft->setCoords(0, 1);
  25419. bottomRight->setCoords(1, 0);
  25420. setPen(QPen(Qt::black));
  25421. setSelectedPen(QPen(Qt::blue, 2));
  25422. setBrush(Qt::NoBrush);
  25423. setSelectedBrush(Qt::NoBrush);
  25424. }
  25425. QCPItemEllipse::~QCPItemEllipse()
  25426. {
  25427. }
  25428. /*!
  25429. Sets the pen that will be used to draw the line of the ellipse
  25430. \see setSelectedPen, setBrush
  25431. */
  25432. void QCPItemEllipse::setPen(const QPen &pen)
  25433. {
  25434. mPen = pen;
  25435. }
  25436. /*!
  25437. Sets the pen that will be used to draw the line of the ellipse when selected
  25438. \see setPen, setSelected
  25439. */
  25440. void QCPItemEllipse::setSelectedPen(const QPen &pen)
  25441. {
  25442. mSelectedPen = pen;
  25443. }
  25444. /*!
  25445. Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to
  25446. Qt::NoBrush.
  25447. \see setSelectedBrush, setPen
  25448. */
  25449. void QCPItemEllipse::setBrush(const QBrush &brush)
  25450. {
  25451. mBrush = brush;
  25452. }
  25453. /*!
  25454. Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a
  25455. brush to Qt::NoBrush.
  25456. \see setBrush
  25457. */
  25458. void QCPItemEllipse::setSelectedBrush(const QBrush &brush)
  25459. {
  25460. mSelectedBrush = brush;
  25461. }
  25462. /* inherits documentation from base class */
  25463. double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25464. {
  25465. Q_UNUSED(details)
  25466. if (onlySelectable && !mSelectable)
  25467. return -1;
  25468. QPointF p1 = topLeft->pixelPosition();
  25469. QPointF p2 = bottomRight->pixelPosition();
  25470. QPointF center((p1+p2)/2.0);
  25471. double a = qAbs(p1.x()-p2.x())/2.0;
  25472. double b = qAbs(p1.y()-p2.y())/2.0;
  25473. double x = pos.x()-center.x();
  25474. double y = pos.y()-center.y();
  25475. // distance to border:
  25476. double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b));
  25477. double result = qAbs(c-1)*qSqrt(x*x+y*y);
  25478. // filled ellipse, allow click inside to count as hit:
  25479. if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
  25480. {
  25481. if (x*x/(a*a) + y*y/(b*b) <= 1)
  25482. result = mParentPlot->selectionTolerance()*0.99;
  25483. }
  25484. return result;
  25485. }
  25486. /* inherits documentation from base class */
  25487. void QCPItemEllipse::draw(QCPPainter *painter)
  25488. {
  25489. QPointF p1 = topLeft->pixelPosition();
  25490. QPointF p2 = bottomRight->pixelPosition();
  25491. if (p1.toPoint() == p2.toPoint())
  25492. return;
  25493. QRectF ellipseRect = QRectF(p1, p2).normalized();
  25494. QRectF clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
  25495. if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect
  25496. {
  25497. painter->setPen(mainPen());
  25498. painter->setBrush(mainBrush());
  25499. #ifdef __EXCEPTIONS
  25500. try // drawEllipse sometimes throws exceptions if ellipse is too big
  25501. {
  25502. #endif
  25503. painter->drawEllipse(ellipseRect);
  25504. #ifdef __EXCEPTIONS
  25505. } catch (...)
  25506. {
  25507. qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible";
  25508. setVisible(false);
  25509. }
  25510. #endif
  25511. }
  25512. }
  25513. /* inherits documentation from base class */
  25514. QPointF QCPItemEllipse::anchorPixelPosition(int anchorId) const
  25515. {
  25516. QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition());
  25517. switch (anchorId)
  25518. {
  25519. case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2);
  25520. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  25521. case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2);
  25522. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  25523. case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2);
  25524. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  25525. case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2);
  25526. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
  25527. case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5;
  25528. }
  25529. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  25530. return {};
  25531. }
  25532. /*! \internal
  25533. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  25534. and mSelectedPen when it is.
  25535. */
  25536. QPen QCPItemEllipse::mainPen() const
  25537. {
  25538. return mSelected ? mSelectedPen : mPen;
  25539. }
  25540. /*! \internal
  25541. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  25542. is not selected and mSelectedBrush when it is.
  25543. */
  25544. QBrush QCPItemEllipse::mainBrush() const
  25545. {
  25546. return mSelected ? mSelectedBrush : mBrush;
  25547. }
  25548. /* end of 'src/items/item-ellipse.cpp' */
  25549. /* including file 'src/items/item-pixmap.cpp' */
  25550. /* modified 2021-03-29T02:30:44, size 10622 */
  25551. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25552. //////////////////// QCPItemPixmap
  25553. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25554. /*! \class QCPItemPixmap
  25555. \brief An arbitrary pixmap
  25556. \image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions."
  25557. It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will
  25558. be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to
  25559. fit the rectangle or be drawn aligned to the topLeft position.
  25560. If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown
  25561. on the right side of the example image), the pixmap will be flipped in the respective
  25562. orientations.
  25563. */
  25564. /*!
  25565. Creates a rectangle item and sets default values.
  25566. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  25567. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  25568. */
  25569. QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) :
  25570. QCPAbstractItem(parentPlot),
  25571. topLeft(createPosition(QLatin1String("topLeft"))),
  25572. bottomRight(createPosition(QLatin1String("bottomRight"))),
  25573. top(createAnchor(QLatin1String("top"), aiTop)),
  25574. topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
  25575. right(createAnchor(QLatin1String("right"), aiRight)),
  25576. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  25577. bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
  25578. left(createAnchor(QLatin1String("left"), aiLeft)),
  25579. mScaled(false),
  25580. mScaledPixmapInvalidated(true),
  25581. mAspectRatioMode(Qt::KeepAspectRatio),
  25582. mTransformationMode(Qt::SmoothTransformation)
  25583. {
  25584. topLeft->setCoords(0, 1);
  25585. bottomRight->setCoords(1, 0);
  25586. setPen(Qt::NoPen);
  25587. setSelectedPen(QPen(Qt::blue));
  25588. }
  25589. QCPItemPixmap::~QCPItemPixmap()
  25590. {
  25591. }
  25592. /*!
  25593. Sets the pixmap that will be displayed.
  25594. */
  25595. void QCPItemPixmap::setPixmap(const QPixmap &pixmap)
  25596. {
  25597. mPixmap = pixmap;
  25598. mScaledPixmapInvalidated = true;
  25599. if (mPixmap.isNull())
  25600. qDebug() << Q_FUNC_INFO << "pixmap is null";
  25601. }
  25602. /*!
  25603. Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a
  25604. bottomRight positions.
  25605. */
  25606. void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformationMode)
  25607. {
  25608. mScaled = scaled;
  25609. mAspectRatioMode = aspectRatioMode;
  25610. mTransformationMode = transformationMode;
  25611. mScaledPixmapInvalidated = true;
  25612. }
  25613. /*!
  25614. Sets the pen that will be used to draw a border around the pixmap.
  25615. \see setSelectedPen, setBrush
  25616. */
  25617. void QCPItemPixmap::setPen(const QPen &pen)
  25618. {
  25619. mPen = pen;
  25620. }
  25621. /*!
  25622. Sets the pen that will be used to draw a border around the pixmap when selected
  25623. \see setPen, setSelected
  25624. */
  25625. void QCPItemPixmap::setSelectedPen(const QPen &pen)
  25626. {
  25627. mSelectedPen = pen;
  25628. }
  25629. /* inherits documentation from base class */
  25630. double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25631. {
  25632. Q_UNUSED(details)
  25633. if (onlySelectable && !mSelectable)
  25634. return -1;
  25635. return rectDistance(getFinalRect(), pos, true);
  25636. }
  25637. /* inherits documentation from base class */
  25638. void QCPItemPixmap::draw(QCPPainter *painter)
  25639. {
  25640. bool flipHorz = false;
  25641. bool flipVert = false;
  25642. QRectF rect = getFinalRect(&flipHorz, &flipVert);
  25643. double clipPad = mainPen().style() == Qt::NoPen ? 0 : mainPen().widthF();
  25644. QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  25645. if (boundingRect.intersects(clipRect()))
  25646. {
  25647. updateScaledPixmap(rect, flipHorz, flipVert);
  25648. painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap);
  25649. QPen pen = mainPen();
  25650. if (pen.style() != Qt::NoPen)
  25651. {
  25652. painter->setPen(pen);
  25653. painter->setBrush(Qt::NoBrush);
  25654. painter->drawRect(rect);
  25655. }
  25656. }
  25657. }
  25658. /* inherits documentation from base class */
  25659. QPointF QCPItemPixmap::anchorPixelPosition(int anchorId) const
  25660. {
  25661. bool flipHorz = false;
  25662. bool flipVert = false;
  25663. QRectF rect = getFinalRect(&flipHorz, &flipVert);
  25664. // we actually want denormal rects (negative width/height) here, so restore
  25665. // the flipped state:
  25666. if (flipHorz)
  25667. rect.adjust(rect.width(), 0, -rect.width(), 0);
  25668. if (flipVert)
  25669. rect.adjust(0, rect.height(), 0, -rect.height());
  25670. switch (anchorId)
  25671. {
  25672. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  25673. case aiTopRight: return rect.topRight();
  25674. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  25675. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  25676. case aiBottomLeft: return rect.bottomLeft();
  25677. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
  25678. }
  25679. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  25680. return {};
  25681. }
  25682. /*! \internal
  25683. Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The
  25684. parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped
  25685. horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a
  25686. bottomRight.)
  25687. This function only creates the scaled pixmap when the buffered pixmap has a different size than
  25688. the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does
  25689. not cause expensive rescaling every time.
  25690. If scaling is disabled, sets mScaledPixmap to a null QPixmap.
  25691. */
  25692. void QCPItemPixmap::updateScaledPixmap(QRectF finalRect, bool flipHorz, bool flipVert)
  25693. {
  25694. if (mPixmap.isNull())
  25695. return;
  25696. if (mScaled)
  25697. {
  25698. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  25699. double devicePixelRatio = mPixmap.devicePixelRatio();
  25700. #else
  25701. double devicePixelRatio = 1.0;
  25702. #endif
  25703. if (finalRect.isNull())
  25704. finalRect = getFinalRect(&flipHorz, &flipVert);
  25705. if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size()/devicePixelRatio)
  25706. {
  25707. mScaledPixmap = mPixmap.scaled(finalRect.size().toSize()*devicePixelRatio, mAspectRatioMode, mTransformationMode);
  25708. if (flipHorz || flipVert)
  25709. mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert));
  25710. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  25711. mScaledPixmap.setDevicePixelRatio(devicePixelRatio);
  25712. #endif
  25713. }
  25714. } else if (!mScaledPixmap.isNull())
  25715. mScaledPixmap = QPixmap();
  25716. mScaledPixmapInvalidated = false;
  25717. }
  25718. /*! \internal
  25719. Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions
  25720. and scaling settings.
  25721. The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn
  25722. flipped horizontally or vertically in the returned rect. (The returned rect itself is always
  25723. normalized, i.e. the top left corner of the rect is actually further to the top/left than the
  25724. bottom right corner). This is the case when the item position \a topLeft is further to the
  25725. bottom/right than \a bottomRight.
  25726. If scaling is disabled, returns a rect with size of the original pixmap and the top left corner
  25727. aligned with the item position \a topLeft. The position \a bottomRight is ignored.
  25728. */
  25729. QRectF QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const
  25730. {
  25731. QRectF result;
  25732. bool flipHorz = false;
  25733. bool flipVert = false;
  25734. QPointF p1 = topLeft->pixelPosition();
  25735. QPointF p2 = bottomRight->pixelPosition();
  25736. if (p1 == p2)
  25737. return {p1, QSizeF(0, 0)};
  25738. if (mScaled)
  25739. {
  25740. QSizeF newSize = QSizeF(p2.x()-p1.x(), p2.y()-p1.y());
  25741. QPointF topLeft = p1;
  25742. if (newSize.width() < 0)
  25743. {
  25744. flipHorz = true;
  25745. newSize.rwidth() *= -1;
  25746. topLeft.setX(p2.x());
  25747. }
  25748. if (newSize.height() < 0)
  25749. {
  25750. flipVert = true;
  25751. newSize.rheight() *= -1;
  25752. topLeft.setY(p2.y());
  25753. }
  25754. QSize scaledSize = mPixmap.size();
  25755. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  25756. scaledSize /= mPixmap.devicePixelRatio();
  25757. scaledSize.scale(newSize.toSize()*mPixmap.devicePixelRatio(), mAspectRatioMode);
  25758. #else
  25759. scaledSize.scale(newSize, mAspectRatioMode);
  25760. #endif
  25761. result = QRectF(topLeft, scaledSize);
  25762. } else
  25763. {
  25764. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  25765. result = QRectF(p1, mPixmap.size()/mPixmap.devicePixelRatio());
  25766. #else
  25767. result = QRect(p1, mPixmap.size());
  25768. #endif
  25769. }
  25770. if (flippedHorz)
  25771. *flippedHorz = flipHorz;
  25772. if (flippedVert)
  25773. *flippedVert = flipVert;
  25774. return result;
  25775. }
  25776. /*! \internal
  25777. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  25778. and mSelectedPen when it is.
  25779. */
  25780. QPen QCPItemPixmap::mainPen() const
  25781. {
  25782. return mSelected ? mSelectedPen : mPen;
  25783. }
  25784. /* end of 'src/items/item-pixmap.cpp' */
  25785. /* including file 'src/items/item-tracer.cpp' */
  25786. /* modified 2021-03-29T02:30:44, size 14645 */
  25787. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25788. //////////////////// QCPItemTracer
  25789. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25790. /*! \class QCPItemTracer
  25791. \brief Item that sticks to QCPGraph data points
  25792. \image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs are positions."
  25793. The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt
  25794. the coordinate axes of the graph and update its \a position to be on the graph's data. This means
  25795. the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a
  25796. QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a
  25797. position will have no effect because they will be overriden in the next redraw (this is when the
  25798. coordinate update happens).
  25799. If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will
  25800. stay at the corresponding end of the graph.
  25801. With \ref setInterpolating you may specify whether the tracer may only stay exactly on data
  25802. points or whether it interpolates data points linearly, if given a key that lies between two data
  25803. points of the graph.
  25804. The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer
  25805. have no own visual appearance (set the style to \ref tsNone), and just connect other item
  25806. positions to the tracer \a position (used as an anchor) via \ref
  25807. QCPItemPosition::setParentAnchor.
  25808. \note The tracer position is only automatically updated upon redraws. So when the data of the
  25809. graph changes and immediately afterwards (without a redraw) the position coordinates of the
  25810. tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref
  25811. updatePosition must be called manually, prior to reading the tracer coordinates.
  25812. */
  25813. /*!
  25814. Creates a tracer item and sets default values.
  25815. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  25816. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  25817. */
  25818. QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) :
  25819. QCPAbstractItem(parentPlot),
  25820. position(createPosition(QLatin1String("position"))),
  25821. mSize(6),
  25822. mStyle(tsCrosshair),
  25823. mGraph(nullptr),
  25824. mGraphKey(0),
  25825. mInterpolating(false)
  25826. {
  25827. position->setCoords(0, 0);
  25828. setBrush(Qt::NoBrush);
  25829. setSelectedBrush(Qt::NoBrush);
  25830. setPen(QPen(Qt::black));
  25831. setSelectedPen(QPen(Qt::blue, 2));
  25832. }
  25833. QCPItemTracer::~QCPItemTracer()
  25834. {
  25835. }
  25836. /*!
  25837. Sets the pen that will be used to draw the line of the tracer
  25838. \see setSelectedPen, setBrush
  25839. */
  25840. void QCPItemTracer::setPen(const QPen &pen)
  25841. {
  25842. mPen = pen;
  25843. }
  25844. /*!
  25845. Sets the pen that will be used to draw the line of the tracer when selected
  25846. \see setPen, setSelected
  25847. */
  25848. void QCPItemTracer::setSelectedPen(const QPen &pen)
  25849. {
  25850. mSelectedPen = pen;
  25851. }
  25852. /*!
  25853. Sets the brush that will be used to draw any fills of the tracer
  25854. \see setSelectedBrush, setPen
  25855. */
  25856. void QCPItemTracer::setBrush(const QBrush &brush)
  25857. {
  25858. mBrush = brush;
  25859. }
  25860. /*!
  25861. Sets the brush that will be used to draw any fills of the tracer, when selected.
  25862. \see setBrush, setSelected
  25863. */
  25864. void QCPItemTracer::setSelectedBrush(const QBrush &brush)
  25865. {
  25866. mSelectedBrush = brush;
  25867. }
  25868. /*!
  25869. Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare
  25870. does, \ref tsCrosshair does not).
  25871. */
  25872. void QCPItemTracer::setSize(double size)
  25873. {
  25874. mSize = size;
  25875. }
  25876. /*!
  25877. Sets the style/visual appearance of the tracer.
  25878. If you only want to use the tracer \a position as an anchor for other items, set \a style to
  25879. \ref tsNone.
  25880. */
  25881. void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style)
  25882. {
  25883. mStyle = style;
  25884. }
  25885. /*!
  25886. Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type
  25887. QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph.
  25888. To free the tracer from any graph, set \a graph to \c nullptr. The tracer \a position can then be
  25889. placed freely like any other item position. This is the state the tracer will assume when its
  25890. graph gets deleted while still attached to it.
  25891. \see setGraphKey
  25892. */
  25893. void QCPItemTracer::setGraph(QCPGraph *graph)
  25894. {
  25895. if (graph)
  25896. {
  25897. if (graph->parentPlot() == mParentPlot)
  25898. {
  25899. position->setType(QCPItemPosition::ptPlotCoords);
  25900. position->setAxes(graph->keyAxis(), graph->valueAxis());
  25901. mGraph = graph;
  25902. updatePosition();
  25903. } else
  25904. qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item";
  25905. } else
  25906. {
  25907. mGraph = nullptr;
  25908. }
  25909. }
  25910. /*!
  25911. Sets the key of the graph's data point the tracer will be positioned at. This is the only free
  25912. coordinate of a tracer when attached to a graph.
  25913. Depending on \ref setInterpolating, the tracer will be either positioned on the data point
  25914. closest to \a key, or will stay exactly at \a key and interpolate the value linearly.
  25915. \see setGraph, setInterpolating
  25916. */
  25917. void QCPItemTracer::setGraphKey(double key)
  25918. {
  25919. mGraphKey = key;
  25920. }
  25921. /*!
  25922. Sets whether the value of the graph's data points shall be interpolated, when positioning the
  25923. tracer.
  25924. If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on
  25925. the data point of the graph which is closest to the key, but which is not necessarily exactly
  25926. there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and
  25927. the appropriate value will be interpolated from the graph's data points linearly.
  25928. \see setGraph, setGraphKey
  25929. */
  25930. void QCPItemTracer::setInterpolating(bool enabled)
  25931. {
  25932. mInterpolating = enabled;
  25933. }
  25934. /* inherits documentation from base class */
  25935. double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25936. {
  25937. Q_UNUSED(details)
  25938. if (onlySelectable && !mSelectable)
  25939. return -1;
  25940. QPointF center(position->pixelPosition());
  25941. double w = mSize/2.0;
  25942. QRectF clip = clipRect();
  25943. switch (mStyle)
  25944. {
  25945. case tsNone: return -1;
  25946. case tsPlus:
  25947. {
  25948. if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  25949. return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(center+QPointF(-w, 0), center+QPointF(w, 0)),
  25950. QCPVector2D(pos).distanceSquaredToLine(center+QPointF(0, -w), center+QPointF(0, w))));
  25951. break;
  25952. }
  25953. case tsCrosshair:
  25954. {
  25955. return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(clip.left(), center.y()), QCPVector2D(clip.right(), center.y())),
  25956. QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(center.x(), clip.top()), QCPVector2D(center.x(), clip.bottom()))));
  25957. }
  25958. case tsCircle:
  25959. {
  25960. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  25961. {
  25962. // distance to border:
  25963. double centerDist = QCPVector2D(center-pos).length();
  25964. double circleLine = w;
  25965. double result = qAbs(centerDist-circleLine);
  25966. // filled ellipse, allow click inside to count as hit:
  25967. if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
  25968. {
  25969. if (centerDist <= circleLine)
  25970. result = mParentPlot->selectionTolerance()*0.99;
  25971. }
  25972. return result;
  25973. }
  25974. break;
  25975. }
  25976. case tsSquare:
  25977. {
  25978. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  25979. {
  25980. QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w));
  25981. bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
  25982. return rectDistance(rect, pos, filledRect);
  25983. }
  25984. break;
  25985. }
  25986. }
  25987. return -1;
  25988. }
  25989. /* inherits documentation from base class */
  25990. void QCPItemTracer::draw(QCPPainter *painter)
  25991. {
  25992. updatePosition();
  25993. if (mStyle == tsNone)
  25994. return;
  25995. painter->setPen(mainPen());
  25996. painter->setBrush(mainBrush());
  25997. QPointF center(position->pixelPosition());
  25998. double w = mSize/2.0;
  25999. QRectF clip = clipRect();
  26000. switch (mStyle)
  26001. {
  26002. case tsNone: return;
  26003. case tsPlus:
  26004. {
  26005. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  26006. {
  26007. painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0)));
  26008. painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w)));
  26009. }
  26010. break;
  26011. }
  26012. case tsCrosshair:
  26013. {
  26014. if (center.y() > clip.top() && center.y() < clip.bottom())
  26015. painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y()));
  26016. if (center.x() > clip.left() && center.x() < clip.right())
  26017. painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom()));
  26018. break;
  26019. }
  26020. case tsCircle:
  26021. {
  26022. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  26023. painter->drawEllipse(center, w, w);
  26024. break;
  26025. }
  26026. case tsSquare:
  26027. {
  26028. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  26029. painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w)));
  26030. break;
  26031. }
  26032. }
  26033. }
  26034. /*!
  26035. If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a
  26036. position to reside on the graph data, depending on the configured key (\ref setGraphKey).
  26037. It is called automatically on every redraw and normally doesn't need to be called manually. One
  26038. exception is when you want to read the tracer coordinates via \a position and are not sure that
  26039. the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw.
  26040. In that situation, call this function before accessing \a position, to make sure you don't get
  26041. out-of-date coordinates.
  26042. If there is no graph set on this tracer, this function does nothing.
  26043. */
  26044. void QCPItemTracer::updatePosition()
  26045. {
  26046. if (mGraph)
  26047. {
  26048. if (mParentPlot->hasPlottable(mGraph))
  26049. {
  26050. if (mGraph->data()->size() > 1)
  26051. {
  26052. QCPGraphDataContainer::const_iterator first = mGraph->data()->constBegin();
  26053. QCPGraphDataContainer::const_iterator last = mGraph->data()->constEnd()-1;
  26054. if (mGraphKey <= first->key)
  26055. position->setCoords(first->key, first->value);
  26056. else if (mGraphKey >= last->key)
  26057. position->setCoords(last->key, last->value);
  26058. else
  26059. {
  26060. QCPGraphDataContainer::const_iterator it = mGraph->data()->findBegin(mGraphKey);
  26061. if (it != mGraph->data()->constEnd()) // mGraphKey is not exactly on last iterator, but somewhere between iterators
  26062. {
  26063. QCPGraphDataContainer::const_iterator prevIt = it;
  26064. ++it; // won't advance to constEnd because we handled that case (mGraphKey >= last->key) before
  26065. if (mInterpolating)
  26066. {
  26067. // interpolate between iterators around mGraphKey:
  26068. double slope = 0;
  26069. if (!qFuzzyCompare(double(it->key), double(prevIt->key)))
  26070. slope = (it->value-prevIt->value)/(it->key-prevIt->key);
  26071. position->setCoords(mGraphKey, (mGraphKey-prevIt->key)*slope+prevIt->value);
  26072. } else
  26073. {
  26074. // find iterator with key closest to mGraphKey:
  26075. if (mGraphKey < (prevIt->key+it->key)*0.5)
  26076. position->setCoords(prevIt->key, prevIt->value);
  26077. else
  26078. position->setCoords(it->key, it->value);
  26079. }
  26080. } else // mGraphKey is exactly on last iterator (should actually be caught when comparing first/last keys, but this is a failsafe for fp uncertainty)
  26081. position->setCoords(it->key, it->value);
  26082. }
  26083. } else if (mGraph->data()->size() == 1)
  26084. {
  26085. QCPGraphDataContainer::const_iterator it = mGraph->data()->constBegin();
  26086. position->setCoords(it->key, it->value);
  26087. } else {
  26088. // qDebug() << Q_FUNC_INFO << "graph has no data";
  26089. }
  26090. } else
  26091. qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)";
  26092. }
  26093. }
  26094. /*! \internal
  26095. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  26096. and mSelectedPen when it is.
  26097. */
  26098. QPen QCPItemTracer::mainPen() const
  26099. {
  26100. return mSelected ? mSelectedPen : mPen;
  26101. }
  26102. /*! \internal
  26103. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  26104. is not selected and mSelectedBrush when it is.
  26105. */
  26106. QBrush QCPItemTracer::mainBrush() const
  26107. {
  26108. return mSelected ? mSelectedBrush : mBrush;
  26109. }
  26110. /* end of 'src/items/item-tracer.cpp' */
  26111. /* including file 'src/items/item-bracket.cpp' */
  26112. /* modified 2021-03-29T02:30:44, size 10705 */
  26113. ////////////////////////////////////////////////////////////////////////////////////////////////////
  26114. //////////////////// QCPItemBracket
  26115. ////////////////////////////////////////////////////////////////////////////////////////////////////
  26116. /*! \class QCPItemBracket
  26117. \brief A bracket for referencing/highlighting certain parts in the plot.
  26118. \image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs are positions."
  26119. It has two positions, \a left and \a right, which define the span of the bracket. If \a left is
  26120. actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the
  26121. example image.
  26122. The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket
  26123. stretches away from the embraced span, can be controlled with \ref setLength.
  26124. \image html QCPItemBracket-length.png
  26125. <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
  26126. bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
  26127. It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine
  26128. or QCPItemCurve) or a text label (QCPItemText), to the bracket.
  26129. */
  26130. /*!
  26131. Creates a bracket item and sets default values.
  26132. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  26133. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  26134. */
  26135. QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) :
  26136. QCPAbstractItem(parentPlot),
  26137. left(createPosition(QLatin1String("left"))),
  26138. right(createPosition(QLatin1String("right"))),
  26139. center(createAnchor(QLatin1String("center"), aiCenter)),
  26140. mLength(8),
  26141. mStyle(bsCalligraphic)
  26142. {
  26143. left->setCoords(0, 0);
  26144. right->setCoords(1, 1);
  26145. setPen(QPen(Qt::black));
  26146. setSelectedPen(QPen(Qt::blue, 2));
  26147. }
  26148. QCPItemBracket::~QCPItemBracket()
  26149. {
  26150. }
  26151. /*!
  26152. Sets the pen that will be used to draw the bracket.
  26153. Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the
  26154. stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use
  26155. \ref setLength, which has a similar effect.
  26156. \see setSelectedPen
  26157. */
  26158. void QCPItemBracket::setPen(const QPen &pen)
  26159. {
  26160. mPen = pen;
  26161. }
  26162. /*!
  26163. Sets the pen that will be used to draw the bracket when selected
  26164. \see setPen, setSelected
  26165. */
  26166. void QCPItemBracket::setSelectedPen(const QPen &pen)
  26167. {
  26168. mSelectedPen = pen;
  26169. }
  26170. /*!
  26171. Sets the \a length in pixels how far the bracket extends in the direction towards the embraced
  26172. span of the bracket (i.e. perpendicular to the <i>left</i>-<i>right</i>-direction)
  26173. \image html QCPItemBracket-length.png
  26174. <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
  26175. bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
  26176. */
  26177. void QCPItemBracket::setLength(double length)
  26178. {
  26179. mLength = length;
  26180. }
  26181. /*!
  26182. Sets the style of the bracket, i.e. the shape/visual appearance.
  26183. \see setPen
  26184. */
  26185. void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style)
  26186. {
  26187. mStyle = style;
  26188. }
  26189. /* inherits documentation from base class */
  26190. double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  26191. {
  26192. Q_UNUSED(details)
  26193. if (onlySelectable && !mSelectable)
  26194. return -1;
  26195. QCPVector2D p(pos);
  26196. QCPVector2D leftVec(left->pixelPosition());
  26197. QCPVector2D rightVec(right->pixelPosition());
  26198. if (leftVec.toPoint() == rightVec.toPoint())
  26199. return -1;
  26200. QCPVector2D widthVec = (rightVec-leftVec)*0.5;
  26201. QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
  26202. QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
  26203. switch (mStyle)
  26204. {
  26205. case QCPItemBracket::bsSquare:
  26206. case QCPItemBracket::bsRound:
  26207. {
  26208. double a = p.distanceSquaredToLine(centerVec-widthVec, centerVec+widthVec);
  26209. double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec, centerVec-widthVec);
  26210. double c = p.distanceSquaredToLine(centerVec+widthVec+lengthVec, centerVec+widthVec);
  26211. return qSqrt(qMin(qMin(a, b), c));
  26212. }
  26213. case QCPItemBracket::bsCurly:
  26214. case QCPItemBracket::bsCalligraphic:
  26215. {
  26216. double a = p.distanceSquaredToLine(centerVec-widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3);
  26217. double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec*0.7, centerVec-widthVec*0.75+lengthVec*0.15);
  26218. double c = p.distanceSquaredToLine(centerVec+widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3);
  26219. double d = p.distanceSquaredToLine(centerVec+widthVec+lengthVec*0.7, centerVec+widthVec*0.75+lengthVec*0.15);
  26220. return qSqrt(qMin(qMin(a, b), qMin(c, d)));
  26221. }
  26222. }
  26223. return -1;
  26224. }
  26225. /* inherits documentation from base class */
  26226. void QCPItemBracket::draw(QCPPainter *painter)
  26227. {
  26228. QCPVector2D leftVec(left->pixelPosition());
  26229. QCPVector2D rightVec(right->pixelPosition());
  26230. if (leftVec.toPoint() == rightVec.toPoint())
  26231. return;
  26232. QCPVector2D widthVec = (rightVec-leftVec)*0.5;
  26233. QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
  26234. QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
  26235. QPolygon boundingPoly;
  26236. boundingPoly << leftVec.toPoint() << rightVec.toPoint()
  26237. << (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint();
  26238. QRectF clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
  26239. if (clip.intersects(boundingPoly.boundingRect()))
  26240. {
  26241. painter->setPen(mainPen());
  26242. switch (mStyle)
  26243. {
  26244. case bsSquare:
  26245. {
  26246. painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF());
  26247. painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
  26248. painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  26249. break;
  26250. }
  26251. case bsRound:
  26252. {
  26253. painter->setBrush(Qt::NoBrush);
  26254. QPainterPath path;
  26255. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  26256. path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF());
  26257. path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  26258. painter->drawPath(path);
  26259. break;
  26260. }
  26261. case bsCurly:
  26262. {
  26263. painter->setBrush(Qt::NoBrush);
  26264. QPainterPath path;
  26265. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  26266. path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+lengthVec).toPointF(), centerVec.toPointF());
  26267. path.cubicTo((centerVec-0.4*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  26268. painter->drawPath(path);
  26269. break;
  26270. }
  26271. case bsCalligraphic:
  26272. {
  26273. painter->setPen(Qt::NoPen);
  26274. painter->setBrush(QBrush(mainPen().color()));
  26275. QPainterPath path;
  26276. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  26277. path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+0.8*lengthVec).toPointF(), centerVec.toPointF());
  26278. path.cubicTo((centerVec-0.4*widthVec+0.8*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  26279. path.cubicTo((centerVec-widthVec-lengthVec*0.5).toPointF(), (centerVec-0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+lengthVec*0.2).toPointF());
  26280. path.cubicTo((centerVec+0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
  26281. painter->drawPath(path);
  26282. break;
  26283. }
  26284. }
  26285. }
  26286. }
  26287. /* inherits documentation from base class */
  26288. QPointF QCPItemBracket::anchorPixelPosition(int anchorId) const
  26289. {
  26290. QCPVector2D leftVec(left->pixelPosition());
  26291. QCPVector2D rightVec(right->pixelPosition());
  26292. if (leftVec.toPoint() == rightVec.toPoint())
  26293. return leftVec.toPointF();
  26294. QCPVector2D widthVec = (rightVec-leftVec)*0.5;
  26295. QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
  26296. QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
  26297. switch (anchorId)
  26298. {
  26299. case aiCenter:
  26300. return centerVec.toPointF();
  26301. }
  26302. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  26303. return {};
  26304. }
  26305. /*! \internal
  26306. Returns the pen that should be used for drawing lines. Returns mPen when the
  26307. item is not selected and mSelectedPen when it is.
  26308. */
  26309. QPen QCPItemBracket::mainPen() const
  26310. {
  26311. return mSelected ? mSelectedPen : mPen;
  26312. }
  26313. /* end of 'src/items/item-bracket.cpp' */
  26314. /* including file 'src/polar/radialaxis.cpp' */
  26315. /* modified 2021-03-29T02:30:44, size 49415 */
  26316. ////////////////////////////////////////////////////////////////////////////////////////////////////
  26317. //////////////////// QCPPolarAxisRadial
  26318. ////////////////////////////////////////////////////////////////////////////////////////////////////
  26319. /*! \class QCPPolarAxisRadial
  26320. \brief The radial axis inside a radial plot
  26321. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  26322. functionality to be incomplete, as well as changing public interfaces in the future.
  26323. Each axis holds an instance of QCPAxisTicker which is used to generate the tick coordinates and
  26324. tick labels. You can access the currently installed \ref ticker or set a new one (possibly one of
  26325. the specialized subclasses, or your own subclass) via \ref setTicker. For details, see the
  26326. documentation of QCPAxisTicker.
  26327. */
  26328. /* start of documentation of inline functions */
  26329. /*! \fn QSharedPointer<QCPAxisTicker> QCPPolarAxisRadial::ticker() const
  26330. Returns a modifiable shared pointer to the currently installed axis ticker. The axis ticker is
  26331. responsible for generating the tick positions and tick labels of this axis. You can access the
  26332. \ref QCPAxisTicker with this method and modify basic properties such as the approximate tick count
  26333. (\ref QCPAxisTicker::setTickCount).
  26334. You can gain more control over the axis ticks by setting a different \ref QCPAxisTicker subclass, see
  26335. the documentation there. A new axis ticker can be set with \ref setTicker.
  26336. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  26337. ticker simply by passing the same shared pointer to multiple axes.
  26338. \see setTicker
  26339. */
  26340. /* end of documentation of inline functions */
  26341. /* start of documentation of signals */
  26342. /*! \fn void QCPPolarAxisRadial::rangeChanged(const QCPRange &newRange)
  26343. This signal is emitted when the range of this axis has changed. You can connect it to the \ref
  26344. setRange slot of another axis to communicate the new range to the other axis, in order for it to
  26345. be synchronized.
  26346. You may also manipulate/correct the range with \ref setRange in a slot connected to this signal.
  26347. This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper
  26348. range shouldn't go beyond certain values (see \ref QCPRange::bounded). For example, the following
  26349. slot would limit the x axis to ranges between 0 and 10:
  26350. \code
  26351. customPlot->xAxis->setRange(newRange.bounded(0, 10))
  26352. \endcode
  26353. */
  26354. /*! \fn void QCPPolarAxisRadial::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange)
  26355. \overload
  26356. Additionally to the new range, this signal also provides the previous range held by the axis as
  26357. \a oldRange.
  26358. */
  26359. /*! \fn void QCPPolarAxisRadial::scaleTypeChanged(QCPPolarAxisRadial::ScaleType scaleType);
  26360. This signal is emitted when the scale type changes, by calls to \ref setScaleType
  26361. */
  26362. /*! \fn void QCPPolarAxisRadial::selectionChanged(QCPPolarAxisRadial::SelectableParts selection)
  26363. This signal is emitted when the selection state of this axis has changed, either by user interaction
  26364. or by a direct call to \ref setSelectedParts.
  26365. */
  26366. /*! \fn void QCPPolarAxisRadial::selectableChanged(const QCPPolarAxisRadial::SelectableParts &parts);
  26367. This signal is emitted when the selectability changes, by calls to \ref setSelectableParts
  26368. */
  26369. /* end of documentation of signals */
  26370. /*!
  26371. Constructs an Axis instance of Type \a type for the axis rect \a parent.
  26372. Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create
  26373. them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however,
  26374. create them manually and then inject them also via \ref QCPAxisRect::addAxis.
  26375. */
  26376. QCPPolarAxisRadial::QCPPolarAxisRadial(QCPPolarAxisAngular *parent) :
  26377. QCPLayerable(parent->parentPlot(), QString(), parent),
  26378. mRangeDrag(true),
  26379. mRangeZoom(true),
  26380. mRangeZoomFactor(0.85),
  26381. // axis base:
  26382. mAngularAxis(parent),
  26383. mAngle(45),
  26384. mAngleReference(arAngularAxis),
  26385. mSelectableParts(spAxis | spTickLabels | spAxisLabel),
  26386. mSelectedParts(spNone),
  26387. mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  26388. mSelectedBasePen(QPen(Qt::blue, 2)),
  26389. // axis label:
  26390. mLabelPadding(0),
  26391. mLabel(),
  26392. mLabelFont(mParentPlot->font()),
  26393. mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
  26394. mLabelColor(Qt::black),
  26395. mSelectedLabelColor(Qt::blue),
  26396. // tick labels:
  26397. // mTickLabelPadding(0), in label painter
  26398. mTickLabels(true),
  26399. // mTickLabelRotation(0), in label painter
  26400. mTickLabelFont(mParentPlot->font()),
  26401. mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
  26402. mTickLabelColor(Qt::black),
  26403. mSelectedTickLabelColor(Qt::blue),
  26404. mNumberPrecision(6),
  26405. mNumberFormatChar('g'),
  26406. mNumberBeautifulPowers(true),
  26407. mNumberMultiplyCross(false),
  26408. // ticks and subticks:
  26409. mTicks(true),
  26410. mSubTicks(true),
  26411. mTickLengthIn(5),
  26412. mTickLengthOut(0),
  26413. mSubTickLengthIn(2),
  26414. mSubTickLengthOut(0),
  26415. mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  26416. mSelectedTickPen(QPen(Qt::blue, 2)),
  26417. mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  26418. mSelectedSubTickPen(QPen(Qt::blue, 2)),
  26419. // scale and range:
  26420. mRange(0, 5),
  26421. mRangeReversed(false),
  26422. mScaleType(stLinear),
  26423. // internal members:
  26424. mRadius(1), // non-zero initial value, will be overwritten in ::update() according to inner rect
  26425. mTicker(new QCPAxisTicker),
  26426. mLabelPainter(mParentPlot)
  26427. {
  26428. setParent(parent);
  26429. setAntialiased(true);
  26430. setTickLabelPadding(5);
  26431. setTickLabelRotation(0);
  26432. setTickLabelMode(lmUpright);
  26433. mLabelPainter.setAnchorReferenceType(QCPLabelPainterPrivate::artTangent);
  26434. mLabelPainter.setAbbreviateDecimalPowers(false);
  26435. }
  26436. QCPPolarAxisRadial::~QCPPolarAxisRadial()
  26437. {
  26438. }
  26439. QCPPolarAxisRadial::LabelMode QCPPolarAxisRadial::tickLabelMode() const
  26440. {
  26441. switch (mLabelPainter.anchorMode())
  26442. {
  26443. case QCPLabelPainterPrivate::amSkewedUpright: return lmUpright;
  26444. case QCPLabelPainterPrivate::amSkewedRotated: return lmRotated;
  26445. default: qDebug() << Q_FUNC_INFO << "invalid mode for polar axis"; break;
  26446. }
  26447. return lmUpright;
  26448. }
  26449. /* No documentation as it is a property getter */
  26450. QString QCPPolarAxisRadial::numberFormat() const
  26451. {
  26452. QString result;
  26453. result.append(mNumberFormatChar);
  26454. if (mNumberBeautifulPowers)
  26455. {
  26456. result.append(QLatin1Char('b'));
  26457. if (mNumberMultiplyCross)
  26458. result.append(QLatin1Char('c'));
  26459. }
  26460. return result;
  26461. }
  26462. /* No documentation as it is a property getter */
  26463. int QCPPolarAxisRadial::tickLengthIn() const
  26464. {
  26465. return mTickLengthIn;
  26466. }
  26467. /* No documentation as it is a property getter */
  26468. int QCPPolarAxisRadial::tickLengthOut() const
  26469. {
  26470. return mTickLengthOut;
  26471. }
  26472. /* No documentation as it is a property getter */
  26473. int QCPPolarAxisRadial::subTickLengthIn() const
  26474. {
  26475. return mSubTickLengthIn;
  26476. }
  26477. /* No documentation as it is a property getter */
  26478. int QCPPolarAxisRadial::subTickLengthOut() const
  26479. {
  26480. return mSubTickLengthOut;
  26481. }
  26482. /* No documentation as it is a property getter */
  26483. int QCPPolarAxisRadial::labelPadding() const
  26484. {
  26485. return mLabelPadding;
  26486. }
  26487. void QCPPolarAxisRadial::setRangeDrag(bool enabled)
  26488. {
  26489. mRangeDrag = enabled;
  26490. }
  26491. void QCPPolarAxisRadial::setRangeZoom(bool enabled)
  26492. {
  26493. mRangeZoom = enabled;
  26494. }
  26495. void QCPPolarAxisRadial::setRangeZoomFactor(double factor)
  26496. {
  26497. mRangeZoomFactor = factor;
  26498. }
  26499. /*!
  26500. Sets whether the axis uses a linear scale or a logarithmic scale.
  26501. Note that this method controls the coordinate transformation. For logarithmic scales, you will
  26502. likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting
  26503. the axis ticker to an instance of \ref QCPAxisTickerLog :
  26504. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-creation
  26505. See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick
  26506. creation.
  26507. \ref setNumberPrecision
  26508. */
  26509. void QCPPolarAxisRadial::setScaleType(QCPPolarAxisRadial::ScaleType type)
  26510. {
  26511. if (mScaleType != type)
  26512. {
  26513. mScaleType = type;
  26514. if (mScaleType == stLogarithmic)
  26515. setRange(mRange.sanitizedForLogScale());
  26516. //mCachedMarginValid = false;
  26517. emit scaleTypeChanged(mScaleType);
  26518. }
  26519. }
  26520. /*!
  26521. Sets the range of the axis.
  26522. This slot may be connected with the \ref rangeChanged signal of another axis so this axis
  26523. is always synchronized with the other axis range, when it changes.
  26524. To invert the direction of an axis, use \ref setRangeReversed.
  26525. */
  26526. void QCPPolarAxisRadial::setRange(const QCPRange &range)
  26527. {
  26528. if (qFuzzyCompare(range.lower, mRange.lower) && qFuzzyCompare(range.upper, mRange.upper))
  26529. return;
  26530. if (!QCPRange::validRange(range)) return;
  26531. QCPRange oldRange = mRange;
  26532. if (mScaleType == stLogarithmic)
  26533. {
  26534. mRange = range.sanitizedForLogScale();
  26535. } else
  26536. {
  26537. mRange = range.sanitizedForLinScale();
  26538. }
  26539. emit rangeChanged(mRange);
  26540. emit rangeChanged(mRange, oldRange);
  26541. }
  26542. /*!
  26543. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  26544. (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
  26545. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  26546. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  26547. directly.
  26548. \see SelectablePart, setSelectedParts
  26549. */
  26550. void QCPPolarAxisRadial::setSelectableParts(const SelectableParts &selectable)
  26551. {
  26552. if (mSelectableParts != selectable)
  26553. {
  26554. mSelectableParts = selectable;
  26555. emit selectableChanged(mSelectableParts);
  26556. }
  26557. }
  26558. /*!
  26559. Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
  26560. is selected, it uses a different pen/font.
  26561. The entire selection mechanism for axes is handled automatically when \ref
  26562. QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
  26563. wish to change the selection state manually.
  26564. This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
  26565. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  26566. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
  26567. setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
  26568. */
  26569. void QCPPolarAxisRadial::setSelectedParts(const SelectableParts &selected)
  26570. {
  26571. if (mSelectedParts != selected)
  26572. {
  26573. mSelectedParts = selected;
  26574. emit selectionChanged(mSelectedParts);
  26575. }
  26576. }
  26577. /*!
  26578. \overload
  26579. Sets the lower and upper bound of the axis range.
  26580. To invert the direction of an axis, use \ref setRangeReversed.
  26581. There is also a slot to set a range, see \ref setRange(const QCPRange &range).
  26582. */
  26583. void QCPPolarAxisRadial::setRange(double lower, double upper)
  26584. {
  26585. if (qFuzzyCompare(lower, mRange.lower) && qFuzzyCompare(upper, mRange.upper))
  26586. return;
  26587. if (!QCPRange::validRange(lower, upper)) return;
  26588. QCPRange oldRange = mRange;
  26589. mRange.lower = lower;
  26590. mRange.upper = upper;
  26591. if (mScaleType == stLogarithmic)
  26592. {
  26593. mRange = mRange.sanitizedForLogScale();
  26594. } else
  26595. {
  26596. mRange = mRange.sanitizedForLinScale();
  26597. }
  26598. emit rangeChanged(mRange);
  26599. emit rangeChanged(mRange, oldRange);
  26600. }
  26601. /*!
  26602. \overload
  26603. Sets the range of the axis.
  26604. The \a position coordinate indicates together with the \a alignment parameter, where the new
  26605. range will be positioned. \a size defines the size of the new axis range. \a alignment may be
  26606. Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
  26607. or center of the range to be aligned with \a position. Any other values of \a alignment will
  26608. default to Qt::AlignCenter.
  26609. */
  26610. void QCPPolarAxisRadial::setRange(double position, double size, Qt::AlignmentFlag alignment)
  26611. {
  26612. if (alignment == Qt::AlignLeft)
  26613. setRange(position, position+size);
  26614. else if (alignment == Qt::AlignRight)
  26615. setRange(position-size, position);
  26616. else // alignment == Qt::AlignCenter
  26617. setRange(position-size/2.0, position+size/2.0);
  26618. }
  26619. /*!
  26620. Sets the lower bound of the axis range. The upper bound is not changed.
  26621. \see setRange
  26622. */
  26623. void QCPPolarAxisRadial::setRangeLower(double lower)
  26624. {
  26625. if (qFuzzyCompare(mRange.lower, lower))
  26626. return;
  26627. QCPRange oldRange = mRange;
  26628. mRange.lower = lower;
  26629. if (mScaleType == stLogarithmic)
  26630. {
  26631. mRange = mRange.sanitizedForLogScale();
  26632. } else
  26633. {
  26634. mRange = mRange.sanitizedForLinScale();
  26635. }
  26636. emit rangeChanged(mRange);
  26637. emit rangeChanged(mRange, oldRange);
  26638. }
  26639. /*!
  26640. Sets the upper bound of the axis range. The lower bound is not changed.
  26641. \see setRange
  26642. */
  26643. void QCPPolarAxisRadial::setRangeUpper(double upper)
  26644. {
  26645. if (qFuzzyCompare(mRange.upper, upper))
  26646. return;
  26647. QCPRange oldRange = mRange;
  26648. mRange.upper = upper;
  26649. if (mScaleType == stLogarithmic)
  26650. {
  26651. mRange = mRange.sanitizedForLogScale();
  26652. } else
  26653. {
  26654. mRange = mRange.sanitizedForLinScale();
  26655. }
  26656. emit rangeChanged(mRange);
  26657. emit rangeChanged(mRange, oldRange);
  26658. }
  26659. /*!
  26660. Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
  26661. axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
  26662. direction of increasing values is inverted.
  26663. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
  26664. of the \ref setRange interface will still reference the mathematically smaller number than the \a
  26665. upper part.
  26666. */
  26667. void QCPPolarAxisRadial::setRangeReversed(bool reversed)
  26668. {
  26669. mRangeReversed = reversed;
  26670. }
  26671. void QCPPolarAxisRadial::setAngle(double degrees)
  26672. {
  26673. mAngle = degrees;
  26674. }
  26675. void QCPPolarAxisRadial::setAngleReference(AngleReference reference)
  26676. {
  26677. mAngleReference = reference;
  26678. }
  26679. /*!
  26680. The axis ticker is responsible for generating the tick positions and tick labels. See the
  26681. documentation of QCPAxisTicker for details on how to work with axis tickers.
  26682. You can change the tick positioning/labeling behaviour of this axis by setting a different
  26683. QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
  26684. ticker, access it via \ref ticker.
  26685. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  26686. ticker simply by passing the same shared pointer to multiple axes.
  26687. \see ticker
  26688. */
  26689. void QCPPolarAxisRadial::setTicker(QSharedPointer<QCPAxisTicker> ticker)
  26690. {
  26691. if (ticker)
  26692. mTicker = ticker;
  26693. else
  26694. qDebug() << Q_FUNC_INFO << "can not set 0 as axis ticker";
  26695. // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
  26696. }
  26697. /*!
  26698. Sets whether tick marks are displayed.
  26699. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
  26700. that, see \ref setTickLabels.
  26701. \see setSubTicks
  26702. */
  26703. void QCPPolarAxisRadial::setTicks(bool show)
  26704. {
  26705. if (mTicks != show)
  26706. {
  26707. mTicks = show;
  26708. //mCachedMarginValid = false;
  26709. }
  26710. }
  26711. /*!
  26712. Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
  26713. */
  26714. void QCPPolarAxisRadial::setTickLabels(bool show)
  26715. {
  26716. if (mTickLabels != show)
  26717. {
  26718. mTickLabels = show;
  26719. //mCachedMarginValid = false;
  26720. if (!mTickLabels)
  26721. mTickVectorLabels.clear();
  26722. }
  26723. }
  26724. /*!
  26725. Sets the distance between the axis base line (including any outward ticks) and the tick labels.
  26726. \see setLabelPadding, setPadding
  26727. */
  26728. void QCPPolarAxisRadial::setTickLabelPadding(int padding)
  26729. {
  26730. mLabelPainter.setPadding(padding);
  26731. }
  26732. /*!
  26733. Sets the font of the tick labels.
  26734. \see setTickLabels, setTickLabelColor
  26735. */
  26736. void QCPPolarAxisRadial::setTickLabelFont(const QFont &font)
  26737. {
  26738. if (font != mTickLabelFont)
  26739. {
  26740. mTickLabelFont = font;
  26741. //mCachedMarginValid = false;
  26742. }
  26743. }
  26744. /*!
  26745. Sets the color of the tick labels.
  26746. \see setTickLabels, setTickLabelFont
  26747. */
  26748. void QCPPolarAxisRadial::setTickLabelColor(const QColor &color)
  26749. {
  26750. mTickLabelColor = color;
  26751. }
  26752. /*!
  26753. Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
  26754. the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
  26755. from -90 to 90 degrees.
  26756. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
  26757. other angles, the label is drawn with an offset such that it seems to point toward or away from
  26758. the tick mark.
  26759. */
  26760. void QCPPolarAxisRadial::setTickLabelRotation(double degrees)
  26761. {
  26762. mLabelPainter.setRotation(degrees);
  26763. }
  26764. void QCPPolarAxisRadial::setTickLabelMode(LabelMode mode)
  26765. {
  26766. switch (mode)
  26767. {
  26768. case lmUpright: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedUpright); break;
  26769. case lmRotated: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedRotated); break;
  26770. }
  26771. }
  26772. /*!
  26773. Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
  26774. of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
  26775. that, see the "Argument Formats" section in the detailed description of the QString class.
  26776. \a formatCode is a string of one, two or three characters. The first character is identical to
  26777. the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
  26778. format, 'g'/'G' scientific or fixed, whichever is shorter.
  26779. The second and third characters are optional and specific to QCustomPlot:\n
  26780. If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
  26781. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for
  26782. "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
  26783. [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
  26784. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
  26785. be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
  26786. cross and 183 (0xB7) for the dot.
  26787. Examples for \a formatCode:
  26788. \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
  26789. normal scientific format is used
  26790. \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
  26791. beautifully typeset decimal powers and a dot as multiplication sign
  26792. \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
  26793. multiplication sign
  26794. \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
  26795. powers. Format code will be reduced to 'f'.
  26796. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
  26797. code will not be changed.
  26798. */
  26799. void QCPPolarAxisRadial::setNumberFormat(const QString &formatCode)
  26800. {
  26801. if (formatCode.isEmpty())
  26802. {
  26803. qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
  26804. return;
  26805. }
  26806. //mCachedMarginValid = false;
  26807. // interpret first char as number format char:
  26808. QString allowedFormatChars(QLatin1String("eEfgG"));
  26809. if (allowedFormatChars.contains(formatCode.at(0)))
  26810. {
  26811. mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
  26812. } else
  26813. {
  26814. qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
  26815. return;
  26816. }
  26817. if (formatCode.length() < 2)
  26818. {
  26819. mNumberBeautifulPowers = false;
  26820. mNumberMultiplyCross = false;
  26821. } else
  26822. {
  26823. // interpret second char as indicator for beautiful decimal powers:
  26824. if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
  26825. mNumberBeautifulPowers = true;
  26826. else
  26827. qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
  26828. if (formatCode.length() < 3)
  26829. {
  26830. mNumberMultiplyCross = false;
  26831. } else
  26832. {
  26833. // interpret third char as indicator for dot or cross multiplication symbol:
  26834. if (formatCode.at(2) == QLatin1Char('c'))
  26835. mNumberMultiplyCross = true;
  26836. else if (formatCode.at(2) == QLatin1Char('d'))
  26837. mNumberMultiplyCross = false;
  26838. else
  26839. qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
  26840. }
  26841. }
  26842. mLabelPainter.setSubstituteExponent(mNumberBeautifulPowers);
  26843. mLabelPainter.setMultiplicationSymbol(mNumberMultiplyCross ? QCPLabelPainterPrivate::SymbolCross : QCPLabelPainterPrivate::SymbolDot);
  26844. }
  26845. /*!
  26846. Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
  26847. for details. The effect of precisions are most notably for number Formats starting with 'e', see
  26848. \ref setNumberFormat
  26849. */
  26850. void QCPPolarAxisRadial::setNumberPrecision(int precision)
  26851. {
  26852. if (mNumberPrecision != precision)
  26853. {
  26854. mNumberPrecision = precision;
  26855. //mCachedMarginValid = false;
  26856. }
  26857. }
  26858. /*!
  26859. Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
  26860. plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
  26861. zero, the tick labels and axis label will increase their distance to the axis accordingly, so
  26862. they won't collide with the ticks.
  26863. \see setSubTickLength, setTickLengthIn, setTickLengthOut
  26864. */
  26865. void QCPPolarAxisRadial::setTickLength(int inside, int outside)
  26866. {
  26867. setTickLengthIn(inside);
  26868. setTickLengthOut(outside);
  26869. }
  26870. /*!
  26871. Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
  26872. inside the plot.
  26873. \see setTickLengthOut, setTickLength, setSubTickLength
  26874. */
  26875. void QCPPolarAxisRadial::setTickLengthIn(int inside)
  26876. {
  26877. if (mTickLengthIn != inside)
  26878. {
  26879. mTickLengthIn = inside;
  26880. }
  26881. }
  26882. /*!
  26883. Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
  26884. outside the plot. If \a outside is greater than zero, the tick labels and axis label will
  26885. increase their distance to the axis accordingly, so they won't collide with the ticks.
  26886. \see setTickLengthIn, setTickLength, setSubTickLength
  26887. */
  26888. void QCPPolarAxisRadial::setTickLengthOut(int outside)
  26889. {
  26890. if (mTickLengthOut != outside)
  26891. {
  26892. mTickLengthOut = outside;
  26893. //mCachedMarginValid = false; // only outside tick length can change margin
  26894. }
  26895. }
  26896. /*!
  26897. Sets whether sub tick marks are displayed.
  26898. Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
  26899. \see setTicks
  26900. */
  26901. void QCPPolarAxisRadial::setSubTicks(bool show)
  26902. {
  26903. if (mSubTicks != show)
  26904. {
  26905. mSubTicks = show;
  26906. //mCachedMarginValid = false;
  26907. }
  26908. }
  26909. /*!
  26910. Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
  26911. the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
  26912. than zero, the tick labels and axis label will increase their distance to the axis accordingly,
  26913. so they won't collide with the ticks.
  26914. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
  26915. */
  26916. void QCPPolarAxisRadial::setSubTickLength(int inside, int outside)
  26917. {
  26918. setSubTickLengthIn(inside);
  26919. setSubTickLengthOut(outside);
  26920. }
  26921. /*!
  26922. Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
  26923. the plot.
  26924. \see setSubTickLengthOut, setSubTickLength, setTickLength
  26925. */
  26926. void QCPPolarAxisRadial::setSubTickLengthIn(int inside)
  26927. {
  26928. if (mSubTickLengthIn != inside)
  26929. {
  26930. mSubTickLengthIn = inside;
  26931. }
  26932. }
  26933. /*!
  26934. Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
  26935. outside the plot. If \a outside is greater than zero, the tick labels will increase their
  26936. distance to the axis accordingly, so they won't collide with the ticks.
  26937. \see setSubTickLengthIn, setSubTickLength, setTickLength
  26938. */
  26939. void QCPPolarAxisRadial::setSubTickLengthOut(int outside)
  26940. {
  26941. if (mSubTickLengthOut != outside)
  26942. {
  26943. mSubTickLengthOut = outside;
  26944. //mCachedMarginValid = false; // only outside tick length can change margin
  26945. }
  26946. }
  26947. /*!
  26948. Sets the pen, the axis base line is drawn with.
  26949. \see setTickPen, setSubTickPen
  26950. */
  26951. void QCPPolarAxisRadial::setBasePen(const QPen &pen)
  26952. {
  26953. mBasePen = pen;
  26954. }
  26955. /*!
  26956. Sets the pen, tick marks will be drawn with.
  26957. \see setTickLength, setBasePen
  26958. */
  26959. void QCPPolarAxisRadial::setTickPen(const QPen &pen)
  26960. {
  26961. mTickPen = pen;
  26962. }
  26963. /*!
  26964. Sets the pen, subtick marks will be drawn with.
  26965. \see setSubTickCount, setSubTickLength, setBasePen
  26966. */
  26967. void QCPPolarAxisRadial::setSubTickPen(const QPen &pen)
  26968. {
  26969. mSubTickPen = pen;
  26970. }
  26971. /*!
  26972. Sets the font of the axis label.
  26973. \see setLabelColor
  26974. */
  26975. void QCPPolarAxisRadial::setLabelFont(const QFont &font)
  26976. {
  26977. if (mLabelFont != font)
  26978. {
  26979. mLabelFont = font;
  26980. //mCachedMarginValid = false;
  26981. }
  26982. }
  26983. /*!
  26984. Sets the color of the axis label.
  26985. \see setLabelFont
  26986. */
  26987. void QCPPolarAxisRadial::setLabelColor(const QColor &color)
  26988. {
  26989. mLabelColor = color;
  26990. }
  26991. /*!
  26992. Sets the text of the axis label that will be shown below/above or next to the axis, depending on
  26993. its orientation. To disable axis labels, pass an empty string as \a str.
  26994. */
  26995. void QCPPolarAxisRadial::setLabel(const QString &str)
  26996. {
  26997. if (mLabel != str)
  26998. {
  26999. mLabel = str;
  27000. //mCachedMarginValid = false;
  27001. }
  27002. }
  27003. /*!
  27004. Sets the distance between the tick labels and the axis label.
  27005. \see setTickLabelPadding, setPadding
  27006. */
  27007. void QCPPolarAxisRadial::setLabelPadding(int padding)
  27008. {
  27009. if (mLabelPadding != padding)
  27010. {
  27011. mLabelPadding = padding;
  27012. //mCachedMarginValid = false;
  27013. }
  27014. }
  27015. /*!
  27016. Sets the font that is used for tick labels when they are selected.
  27017. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27018. */
  27019. void QCPPolarAxisRadial::setSelectedTickLabelFont(const QFont &font)
  27020. {
  27021. if (font != mSelectedTickLabelFont)
  27022. {
  27023. mSelectedTickLabelFont = font;
  27024. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  27025. }
  27026. }
  27027. /*!
  27028. Sets the font that is used for the axis label when it is selected.
  27029. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27030. */
  27031. void QCPPolarAxisRadial::setSelectedLabelFont(const QFont &font)
  27032. {
  27033. mSelectedLabelFont = font;
  27034. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  27035. }
  27036. /*!
  27037. Sets the color that is used for tick labels when they are selected.
  27038. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27039. */
  27040. void QCPPolarAxisRadial::setSelectedTickLabelColor(const QColor &color)
  27041. {
  27042. if (color != mSelectedTickLabelColor)
  27043. {
  27044. mSelectedTickLabelColor = color;
  27045. }
  27046. }
  27047. /*!
  27048. Sets the color that is used for the axis label when it is selected.
  27049. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27050. */
  27051. void QCPPolarAxisRadial::setSelectedLabelColor(const QColor &color)
  27052. {
  27053. mSelectedLabelColor = color;
  27054. }
  27055. /*!
  27056. Sets the pen that is used to draw the axis base line when selected.
  27057. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27058. */
  27059. void QCPPolarAxisRadial::setSelectedBasePen(const QPen &pen)
  27060. {
  27061. mSelectedBasePen = pen;
  27062. }
  27063. /*!
  27064. Sets the pen that is used to draw the (major) ticks when selected.
  27065. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27066. */
  27067. void QCPPolarAxisRadial::setSelectedTickPen(const QPen &pen)
  27068. {
  27069. mSelectedTickPen = pen;
  27070. }
  27071. /*!
  27072. Sets the pen that is used to draw the subticks when selected.
  27073. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27074. */
  27075. void QCPPolarAxisRadial::setSelectedSubTickPen(const QPen &pen)
  27076. {
  27077. mSelectedSubTickPen = pen;
  27078. }
  27079. /*!
  27080. If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
  27081. bounds of the range. The range is simply moved by \a diff.
  27082. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
  27083. corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
  27084. */
  27085. void QCPPolarAxisRadial::moveRange(double diff)
  27086. {
  27087. QCPRange oldRange = mRange;
  27088. if (mScaleType == stLinear)
  27089. {
  27090. mRange.lower += diff;
  27091. mRange.upper += diff;
  27092. } else // mScaleType == stLogarithmic
  27093. {
  27094. mRange.lower *= diff;
  27095. mRange.upper *= diff;
  27096. }
  27097. emit rangeChanged(mRange);
  27098. emit rangeChanged(mRange, oldRange);
  27099. }
  27100. /*!
  27101. Scales the range of this axis by \a factor around the center of the current axis range. For
  27102. example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
  27103. range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
  27104. the center will have moved symmetrically closer).
  27105. If you wish to scale around a different coordinate than the current axis range center, use the
  27106. overload \ref scaleRange(double factor, double center).
  27107. */
  27108. void QCPPolarAxisRadial::scaleRange(double factor)
  27109. {
  27110. scaleRange(factor, range().center());
  27111. }
  27112. /*! \overload
  27113. Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
  27114. factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
  27115. coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
  27116. around 1.0 will have moved symmetrically closer to 1.0).
  27117. \see scaleRange(double factor)
  27118. */
  27119. void QCPPolarAxisRadial::scaleRange(double factor, double center)
  27120. {
  27121. QCPRange oldRange = mRange;
  27122. if (mScaleType == stLinear)
  27123. {
  27124. QCPRange newRange;
  27125. newRange.lower = (mRange.lower-center)*factor + center;
  27126. newRange.upper = (mRange.upper-center)*factor + center;
  27127. if (QCPRange::validRange(newRange))
  27128. mRange = newRange.sanitizedForLinScale();
  27129. } else // mScaleType == stLogarithmic
  27130. {
  27131. if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range
  27132. {
  27133. QCPRange newRange;
  27134. newRange.lower = qPow(mRange.lower/center, factor)*center;
  27135. newRange.upper = qPow(mRange.upper/center, factor)*center;
  27136. if (QCPRange::validRange(newRange))
  27137. mRange = newRange.sanitizedForLogScale();
  27138. } else
  27139. qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center;
  27140. }
  27141. emit rangeChanged(mRange);
  27142. emit rangeChanged(mRange, oldRange);
  27143. }
  27144. /*!
  27145. Changes the axis range such that all plottables associated with this axis are fully visible in
  27146. that dimension.
  27147. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
  27148. */
  27149. void QCPPolarAxisRadial::rescale(bool onlyVisiblePlottables)
  27150. {
  27151. Q_UNUSED(onlyVisiblePlottables)
  27152. /* TODO
  27153. QList<QCPAbstractPlottable*> p = plottables();
  27154. QCPRange newRange;
  27155. bool haveRange = false;
  27156. for (int i=0; i<p.size(); ++i)
  27157. {
  27158. if (!p.at(i)->realVisibility() && onlyVisiblePlottables)
  27159. continue;
  27160. QCPRange plottableRange;
  27161. bool currentFoundRange;
  27162. QCP::SignDomain signDomain = QCP::sdBoth;
  27163. if (mScaleType == stLogarithmic)
  27164. signDomain = (mRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  27165. if (p.at(i)->keyAxis() == this)
  27166. plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain);
  27167. else
  27168. plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain);
  27169. if (currentFoundRange)
  27170. {
  27171. if (!haveRange)
  27172. newRange = plottableRange;
  27173. else
  27174. newRange.expand(plottableRange);
  27175. haveRange = true;
  27176. }
  27177. }
  27178. if (haveRange)
  27179. {
  27180. 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
  27181. {
  27182. 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
  27183. if (mScaleType == stLinear)
  27184. {
  27185. newRange.lower = center-mRange.size()/2.0;
  27186. newRange.upper = center+mRange.size()/2.0;
  27187. } else // mScaleType == stLogarithmic
  27188. {
  27189. newRange.lower = center/qSqrt(mRange.upper/mRange.lower);
  27190. newRange.upper = center*qSqrt(mRange.upper/mRange.lower);
  27191. }
  27192. }
  27193. setRange(newRange);
  27194. }
  27195. */
  27196. }
  27197. /*!
  27198. Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
  27199. */
  27200. void QCPPolarAxisRadial::pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const
  27201. {
  27202. QCPVector2D posVector(pixelPos-mCenter);
  27203. radiusCoord = radiusToCoord(posVector.length());
  27204. angleCoord = mAngularAxis->angleRadToCoord(posVector.angle());
  27205. }
  27206. /*!
  27207. Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
  27208. */
  27209. QPointF QCPPolarAxisRadial::coordToPixel(double angleCoord, double radiusCoord) const
  27210. {
  27211. const double radiusPixel = coordToRadius(radiusCoord);
  27212. const double angleRad = mAngularAxis->coordToAngleRad(angleCoord);
  27213. return QPointF(mCenter.x()+qCos(angleRad)*radiusPixel, mCenter.y()+qSin(angleRad)*radiusPixel);
  27214. }
  27215. double QCPPolarAxisRadial::coordToRadius(double coord) const
  27216. {
  27217. if (mScaleType == stLinear)
  27218. {
  27219. if (!mRangeReversed)
  27220. return (coord-mRange.lower)/mRange.size()*mRadius;
  27221. else
  27222. return (mRange.upper-coord)/mRange.size()*mRadius;
  27223. } else // mScaleType == stLogarithmic
  27224. {
  27225. if (coord >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just return outside visible range
  27226. return !mRangeReversed ? mRadius+200 : mRadius-200;
  27227. else if (coord <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just return outside visible range
  27228. return !mRangeReversed ? mRadius-200 :mRadius+200;
  27229. else
  27230. {
  27231. if (!mRangeReversed)
  27232. return qLn(coord/mRange.lower)/qLn(mRange.upper/mRange.lower)*mRadius;
  27233. else
  27234. return qLn(mRange.upper/coord)/qLn(mRange.upper/mRange.lower)*mRadius;
  27235. }
  27236. }
  27237. }
  27238. double QCPPolarAxisRadial::radiusToCoord(double radius) const
  27239. {
  27240. if (mScaleType == stLinear)
  27241. {
  27242. if (!mRangeReversed)
  27243. return (radius)/mRadius*mRange.size()+mRange.lower;
  27244. else
  27245. return -(radius)/mRadius*mRange.size()+mRange.upper;
  27246. } else // mScaleType == stLogarithmic
  27247. {
  27248. if (!mRangeReversed)
  27249. return qPow(mRange.upper/mRange.lower, (radius)/mRadius)*mRange.lower;
  27250. else
  27251. return qPow(mRange.upper/mRange.lower, (-radius)/mRadius)*mRange.upper;
  27252. }
  27253. }
  27254. /*!
  27255. Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
  27256. is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
  27257. function does not change the current selection state of the axis.
  27258. If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
  27259. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
  27260. */
  27261. QCPPolarAxisRadial::SelectablePart QCPPolarAxisRadial::getPartAt(const QPointF &pos) const
  27262. {
  27263. Q_UNUSED(pos) // TODO remove later
  27264. if (!mVisible)
  27265. return spNone;
  27266. /*
  27267. TODO:
  27268. if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
  27269. return spAxis;
  27270. else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
  27271. return spTickLabels;
  27272. else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
  27273. return spAxisLabel;
  27274. else */
  27275. return spNone;
  27276. }
  27277. /* inherits documentation from base class */
  27278. double QCPPolarAxisRadial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  27279. {
  27280. if (!mParentPlot) return -1;
  27281. SelectablePart part = getPartAt(pos);
  27282. if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
  27283. return -1;
  27284. if (details)
  27285. details->setValue(part);
  27286. return mParentPlot->selectionTolerance()*0.99;
  27287. }
  27288. /* inherits documentation from base class */
  27289. void QCPPolarAxisRadial::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  27290. {
  27291. Q_UNUSED(event)
  27292. SelectablePart part = details.value<SelectablePart>();
  27293. if (mSelectableParts.testFlag(part))
  27294. {
  27295. SelectableParts selBefore = mSelectedParts;
  27296. setSelectedParts(additive ? mSelectedParts^part : part);
  27297. if (selectionStateChanged)
  27298. *selectionStateChanged = mSelectedParts != selBefore;
  27299. }
  27300. }
  27301. /* inherits documentation from base class */
  27302. void QCPPolarAxisRadial::deselectEvent(bool *selectionStateChanged)
  27303. {
  27304. SelectableParts selBefore = mSelectedParts;
  27305. setSelectedParts(mSelectedParts & ~mSelectableParts);
  27306. if (selectionStateChanged)
  27307. *selectionStateChanged = mSelectedParts != selBefore;
  27308. }
  27309. /*! \internal
  27310. This mouse event reimplementation provides the functionality to let the user drag individual axes
  27311. exclusively, by startig the drag on top of the axis.
  27312. For the axis to accept this event and perform the single axis drag, the parent \ref QCPAxisRect
  27313. must be configured accordingly, i.e. it must allow range dragging in the orientation of this axis
  27314. (\ref QCPAxisRect::setRangeDrag) and this axis must be a draggable axis (\ref
  27315. QCPAxisRect::setRangeDragAxes)
  27316. \seebaseclassmethod
  27317. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  27318. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  27319. */
  27320. void QCPPolarAxisRadial::mousePressEvent(QMouseEvent *event, const QVariant &details)
  27321. {
  27322. Q_UNUSED(details)
  27323. if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  27324. {
  27325. event->ignore();
  27326. return;
  27327. }
  27328. if (event->buttons() & Qt::LeftButton)
  27329. {
  27330. mDragging = true;
  27331. // initialize antialiasing backup in case we start dragging:
  27332. if (mParentPlot->noAntialiasingOnDrag())
  27333. {
  27334. mAADragBackup = mParentPlot->antialiasedElements();
  27335. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  27336. }
  27337. // Mouse range dragging interaction:
  27338. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  27339. mDragStartRange = mRange;
  27340. }
  27341. }
  27342. /*! \internal
  27343. This mouse event reimplementation provides the functionality to let the user drag individual axes
  27344. exclusively, by startig the drag on top of the axis.
  27345. \seebaseclassmethod
  27346. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  27347. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  27348. \see QCPAxis::mousePressEvent
  27349. */
  27350. void QCPPolarAxisRadial::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  27351. {
  27352. Q_UNUSED(event) // TODO remove later
  27353. Q_UNUSED(startPos) // TODO remove later
  27354. if (mDragging)
  27355. {
  27356. /* TODO
  27357. const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y();
  27358. const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y();
  27359. if (mScaleType == QCPPolarAxisRadial::stLinear)
  27360. {
  27361. const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel);
  27362. setRange(mDragStartRange.lower+diff, mDragStartRange.upper+diff);
  27363. } else if (mScaleType == QCPPolarAxisRadial::stLogarithmic)
  27364. {
  27365. const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel);
  27366. setRange(mDragStartRange.lower*diff, mDragStartRange.upper*diff);
  27367. }
  27368. */
  27369. if (mParentPlot->noAntialiasingOnDrag())
  27370. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  27371. mParentPlot->replot(QCustomPlot::rpQueuedReplot);
  27372. }
  27373. }
  27374. /*! \internal
  27375. This mouse event reimplementation provides the functionality to let the user drag individual axes
  27376. exclusively, by startig the drag on top of the axis.
  27377. \seebaseclassmethod
  27378. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  27379. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  27380. \see QCPAxis::mousePressEvent
  27381. */
  27382. void QCPPolarAxisRadial::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  27383. {
  27384. Q_UNUSED(event)
  27385. Q_UNUSED(startPos)
  27386. mDragging = false;
  27387. if (mParentPlot->noAntialiasingOnDrag())
  27388. {
  27389. mParentPlot->setAntialiasedElements(mAADragBackup);
  27390. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  27391. }
  27392. }
  27393. /*! \internal
  27394. This mouse event reimplementation provides the functionality to let the user zoom individual axes
  27395. exclusively, by performing the wheel event on top of the axis.
  27396. For the axis to accept this event and perform the single axis zoom, the parent \ref QCPAxisRect
  27397. must be configured accordingly, i.e. it must allow range zooming in the orientation of this axis
  27398. (\ref QCPAxisRect::setRangeZoom) and this axis must be a zoomable axis (\ref
  27399. QCPAxisRect::setRangeZoomAxes)
  27400. \seebaseclassmethod
  27401. \note The zooming of possibly multiple axes at once by performing the wheel event anywhere in the
  27402. axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::wheelEvent.
  27403. */
  27404. void QCPPolarAxisRadial::wheelEvent(QWheelEvent *event)
  27405. {
  27406. // Mouse range zooming interaction:
  27407. if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom))
  27408. {
  27409. event->ignore();
  27410. return;
  27411. }
  27412. // TODO:
  27413. //const double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually
  27414. //const double factor = qPow(mRangeZoomFactor, wheelSteps);
  27415. //scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y()));
  27416. mParentPlot->replot();
  27417. }
  27418. void QCPPolarAxisRadial::updateGeometry(const QPointF &center, double radius)
  27419. {
  27420. mCenter = center;
  27421. mRadius = radius;
  27422. if (mRadius < 1) mRadius = 1;
  27423. }
  27424. /*! \internal
  27425. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  27426. before drawing axis lines.
  27427. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  27428. This function takes into account the local setting of the antialiasing flag as well as the
  27429. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  27430. QCustomPlot::setNotAntialiasedElements.
  27431. \seebaseclassmethod
  27432. \see setAntialiased
  27433. */
  27434. void QCPPolarAxisRadial::applyDefaultAntialiasingHint(QCPPainter *painter) const
  27435. {
  27436. applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
  27437. }
  27438. /*! \internal
  27439. Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance.
  27440. \seebaseclassmethod
  27441. */
  27442. void QCPPolarAxisRadial::draw(QCPPainter *painter)
  27443. {
  27444. const double axisAngleRad = (mAngle+(mAngleReference==arAngularAxis ? mAngularAxis->angle() : 0))/180.0*M_PI;
  27445. const QPointF axisVector(qCos(axisAngleRad), qSin(axisAngleRad)); // semantically should be QCPVector2D, but we save time in loops when we keep it as QPointF
  27446. const QPointF tickNormal = QCPVector2D(axisVector).perpendicular().toPointF(); // semantically should be QCPVector2D, but we save time in loops when we keep it as QPointF
  27447. // draw baseline:
  27448. painter->setPen(getBasePen());
  27449. painter->drawLine(QLineF(mCenter, mCenter+axisVector*(mRadius-0.5)));
  27450. // draw subticks:
  27451. if (!mSubTickVector.isEmpty())
  27452. {
  27453. painter->setPen(getSubTickPen());
  27454. for (int i=0; i<mSubTickVector.size(); ++i)
  27455. {
  27456. const QPointF tickPosition = mCenter+axisVector*coordToRadius(mSubTickVector.at(i));
  27457. painter->drawLine(QLineF(tickPosition-tickNormal*mSubTickLengthIn, tickPosition+tickNormal*mSubTickLengthOut));
  27458. }
  27459. }
  27460. // draw ticks and labels:
  27461. if (!mTickVector.isEmpty())
  27462. {
  27463. mLabelPainter.setAnchorReference(mCenter-axisVector); // subtract (normalized) axisVector, just to prevent degenerate tangents for tick label at exact lower axis range
  27464. mLabelPainter.setFont(getTickLabelFont());
  27465. mLabelPainter.setColor(getTickLabelColor());
  27466. const QPen ticksPen = getTickPen();
  27467. painter->setPen(ticksPen);
  27468. for (int i=0; i<mTickVector.size(); ++i)
  27469. {
  27470. const double r = coordToRadius(mTickVector.at(i));
  27471. const QPointF tickPosition = mCenter+axisVector*r;
  27472. painter->drawLine(QLineF(tickPosition-tickNormal*mTickLengthIn, tickPosition+tickNormal*mTickLengthOut));
  27473. // possibly draw tick labels:
  27474. if (!mTickVectorLabels.isEmpty())
  27475. {
  27476. if ((!mRangeReversed && (i < mTickVectorLabels.count()-1 || mRadius-r > 10)) ||
  27477. (mRangeReversed && (i > 0 || mRadius-r > 10))) // skip last label if it's closer than 10 pixels to angular axis
  27478. mLabelPainter.drawTickLabel(painter, tickPosition+tickNormal*mSubTickLengthOut, mTickVectorLabels.at(i));
  27479. }
  27480. }
  27481. }
  27482. }
  27483. /*! \internal
  27484. Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
  27485. QCPAxisTicker::generate on the currently installed ticker.
  27486. If a change in the label text/count is detected, the cached axis margin is invalidated to make
  27487. sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
  27488. */
  27489. void QCPPolarAxisRadial::setupTickVectors()
  27490. {
  27491. if (!mParentPlot) return;
  27492. if ((!mTicks && !mTickLabels) || mRange.size() <= 0) return;
  27493. mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : nullptr, mTickLabels ? &mTickVectorLabels : nullptr);
  27494. }
  27495. /*! \internal
  27496. Returns the pen that is used to draw the axis base line. Depending on the selection state, this
  27497. is either mSelectedBasePen or mBasePen.
  27498. */
  27499. QPen QCPPolarAxisRadial::getBasePen() const
  27500. {
  27501. return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
  27502. }
  27503. /*! \internal
  27504. Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
  27505. is either mSelectedTickPen or mTickPen.
  27506. */
  27507. QPen QCPPolarAxisRadial::getTickPen() const
  27508. {
  27509. return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
  27510. }
  27511. /*! \internal
  27512. Returns the pen that is used to draw the subticks. Depending on the selection state, this
  27513. is either mSelectedSubTickPen or mSubTickPen.
  27514. */
  27515. QPen QCPPolarAxisRadial::getSubTickPen() const
  27516. {
  27517. return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
  27518. }
  27519. /*! \internal
  27520. Returns the font that is used to draw the tick labels. Depending on the selection state, this
  27521. is either mSelectedTickLabelFont or mTickLabelFont.
  27522. */
  27523. QFont QCPPolarAxisRadial::getTickLabelFont() const
  27524. {
  27525. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
  27526. }
  27527. /*! \internal
  27528. Returns the font that is used to draw the axis label. Depending on the selection state, this
  27529. is either mSelectedLabelFont or mLabelFont.
  27530. */
  27531. QFont QCPPolarAxisRadial::getLabelFont() const
  27532. {
  27533. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
  27534. }
  27535. /*! \internal
  27536. Returns the color that is used to draw the tick labels. Depending on the selection state, this
  27537. is either mSelectedTickLabelColor or mTickLabelColor.
  27538. */
  27539. QColor QCPPolarAxisRadial::getTickLabelColor() const
  27540. {
  27541. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
  27542. }
  27543. /*! \internal
  27544. Returns the color that is used to draw the axis label. Depending on the selection state, this
  27545. is either mSelectedLabelColor or mLabelColor.
  27546. */
  27547. QColor QCPPolarAxisRadial::getLabelColor() const
  27548. {
  27549. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
  27550. }
  27551. /* inherits documentation from base class */
  27552. QCP::Interaction QCPPolarAxisRadial::selectionCategory() const
  27553. {
  27554. return QCP::iSelectAxes;
  27555. }
  27556. /* end of 'src/polar/radialaxis.cpp' */
  27557. /* including file 'src/polar/layoutelement-angularaxis.cpp' */
  27558. /* modified 2021-03-29T02:30:44, size 57266 */
  27559. ////////////////////////////////////////////////////////////////////////////////////////////////////
  27560. //////////////////// QCPPolarAxisAngular
  27561. ////////////////////////////////////////////////////////////////////////////////////////////////////
  27562. /*! \class QCPPolarAxisAngular
  27563. \brief The main container for polar plots, representing the angular axis as a circle
  27564. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  27565. functionality to be incomplete, as well as changing public interfaces in the future.
  27566. */
  27567. /* start documentation of inline functions */
  27568. /*! \fn QCPLayoutInset *QCPPolarAxisAngular::insetLayout() const
  27569. Returns the inset layout of this axis rect. It can be used to place other layout elements (or
  27570. even layouts with multiple other elements) inside/on top of an axis rect.
  27571. \see QCPLayoutInset
  27572. */
  27573. /*! \fn int QCPPolarAxisAngular::left() const
  27574. Returns the pixel position of the left border of this axis rect. Margins are not taken into
  27575. account here, so the returned value is with respect to the inner \ref rect.
  27576. */
  27577. /*! \fn int QCPPolarAxisAngular::right() const
  27578. Returns the pixel position of the right border of this axis rect. Margins are not taken into
  27579. account here, so the returned value is with respect to the inner \ref rect.
  27580. */
  27581. /*! \fn int QCPPolarAxisAngular::top() const
  27582. Returns the pixel position of the top border of this axis rect. Margins are not taken into
  27583. account here, so the returned value is with respect to the inner \ref rect.
  27584. */
  27585. /*! \fn int QCPPolarAxisAngular::bottom() const
  27586. Returns the pixel position of the bottom border of this axis rect. Margins are not taken into
  27587. account here, so the returned value is with respect to the inner \ref rect.
  27588. */
  27589. /*! \fn int QCPPolarAxisAngular::width() const
  27590. Returns the pixel width of this axis rect. Margins are not taken into account here, so the
  27591. returned value is with respect to the inner \ref rect.
  27592. */
  27593. /*! \fn int QCPPolarAxisAngular::height() const
  27594. Returns the pixel height of this axis rect. Margins are not taken into account here, so the
  27595. returned value is with respect to the inner \ref rect.
  27596. */
  27597. /*! \fn QSize QCPPolarAxisAngular::size() const
  27598. Returns the pixel size of this axis rect. Margins are not taken into account here, so the
  27599. returned value is with respect to the inner \ref rect.
  27600. */
  27601. /*! \fn QPoint QCPPolarAxisAngular::topLeft() const
  27602. Returns the top left corner of this axis rect in pixels. Margins are not taken into account here,
  27603. so the returned value is with respect to the inner \ref rect.
  27604. */
  27605. /*! \fn QPoint QCPPolarAxisAngular::topRight() const
  27606. Returns the top right corner of this axis rect in pixels. Margins are not taken into account
  27607. here, so the returned value is with respect to the inner \ref rect.
  27608. */
  27609. /*! \fn QPoint QCPPolarAxisAngular::bottomLeft() const
  27610. Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account
  27611. here, so the returned value is with respect to the inner \ref rect.
  27612. */
  27613. /*! \fn QPoint QCPPolarAxisAngular::bottomRight() const
  27614. Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account
  27615. here, so the returned value is with respect to the inner \ref rect.
  27616. */
  27617. /*! \fn QPoint QCPPolarAxisAngular::center() const
  27618. Returns the center of this axis rect in pixels. Margins are not taken into account here, so the
  27619. returned value is with respect to the inner \ref rect.
  27620. */
  27621. /* end documentation of inline functions */
  27622. /*!
  27623. Creates a QCPPolarAxis instance and sets default values. An axis is added for each of the four
  27624. sides, the top and right axes are set invisible initially.
  27625. */
  27626. QCPPolarAxisAngular::QCPPolarAxisAngular(QCustomPlot *parentPlot) :
  27627. QCPLayoutElement(parentPlot),
  27628. mBackgroundBrush(Qt::NoBrush),
  27629. mBackgroundScaled(true),
  27630. mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
  27631. mInsetLayout(new QCPLayoutInset),
  27632. mRangeDrag(false),
  27633. mRangeZoom(false),
  27634. mRangeZoomFactor(0.85),
  27635. // axis base:
  27636. mAngle(-90),
  27637. mAngleRad(mAngle/180.0*M_PI),
  27638. mSelectableParts(spAxis | spTickLabels | spAxisLabel),
  27639. mSelectedParts(spNone),
  27640. mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  27641. mSelectedBasePen(QPen(Qt::blue, 2)),
  27642. // axis label:
  27643. mLabelPadding(0),
  27644. mLabel(),
  27645. mLabelFont(mParentPlot->font()),
  27646. mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
  27647. mLabelColor(Qt::black),
  27648. mSelectedLabelColor(Qt::blue),
  27649. // tick labels:
  27650. //mTickLabelPadding(0), in label painter
  27651. mTickLabels(true),
  27652. //mTickLabelRotation(0), in label painter
  27653. mTickLabelFont(mParentPlot->font()),
  27654. mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
  27655. mTickLabelColor(Qt::black),
  27656. mSelectedTickLabelColor(Qt::blue),
  27657. mNumberPrecision(6),
  27658. mNumberFormatChar('g'),
  27659. mNumberBeautifulPowers(true),
  27660. mNumberMultiplyCross(false),
  27661. // ticks and subticks:
  27662. mTicks(true),
  27663. mSubTicks(true),
  27664. mTickLengthIn(5),
  27665. mTickLengthOut(0),
  27666. mSubTickLengthIn(2),
  27667. mSubTickLengthOut(0),
  27668. mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  27669. mSelectedTickPen(QPen(Qt::blue, 2)),
  27670. mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  27671. mSelectedSubTickPen(QPen(Qt::blue, 2)),
  27672. // scale and range:
  27673. mRange(0, 360),
  27674. mRangeReversed(false),
  27675. // internal members:
  27676. mRadius(1), // non-zero initial value, will be overwritten in ::update() according to inner rect
  27677. mGrid(new QCPPolarGrid(this)),
  27678. mTicker(new QCPAxisTickerFixed),
  27679. mDragging(false),
  27680. mLabelPainter(parentPlot)
  27681. {
  27682. // TODO:
  27683. //mInsetLayout->initializeParentPlot(mParentPlot);
  27684. //mInsetLayout->setParentLayerable(this);
  27685. //mInsetLayout->setParent(this);
  27686. if (QCPAxisTickerFixed *fixedTicker = mTicker.dynamicCast<QCPAxisTickerFixed>().data())
  27687. {
  27688. fixedTicker->setTickStep(30);
  27689. }
  27690. setAntialiased(true);
  27691. 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
  27692. setTickLabelPadding(5);
  27693. setTickLabelRotation(0);
  27694. setTickLabelMode(lmUpright);
  27695. mLabelPainter.setAnchorReferenceType(QCPLabelPainterPrivate::artNormal);
  27696. mLabelPainter.setAbbreviateDecimalPowers(false);
  27697. mLabelPainter.setCacheSize(24); // so we can cache up to 15-degree intervals, polar angular axis uses a bit larger cache than normal axes
  27698. setMinimumSize(50, 50);
  27699. setMinimumMargins(QMargins(30, 30, 30, 30));
  27700. addRadialAxis();
  27701. mGrid->setRadialAxis(radialAxis());
  27702. }
  27703. QCPPolarAxisAngular::~QCPPolarAxisAngular()
  27704. {
  27705. delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order
  27706. mGrid = nullptr;
  27707. delete mInsetLayout;
  27708. mInsetLayout = nullptr;
  27709. QList<QCPPolarAxisRadial*> radialAxesList = radialAxes();
  27710. for (int i=0; i<radialAxesList.size(); ++i)
  27711. removeRadialAxis(radialAxesList.at(i));
  27712. }
  27713. QCPPolarAxisAngular::LabelMode QCPPolarAxisAngular::tickLabelMode() const
  27714. {
  27715. switch (mLabelPainter.anchorMode())
  27716. {
  27717. case QCPLabelPainterPrivate::amSkewedUpright: return lmUpright;
  27718. case QCPLabelPainterPrivate::amSkewedRotated: return lmRotated;
  27719. default: qDebug() << Q_FUNC_INFO << "invalid mode for polar axis"; break;
  27720. }
  27721. return lmUpright;
  27722. }
  27723. /* No documentation as it is a property getter */
  27724. QString QCPPolarAxisAngular::numberFormat() const
  27725. {
  27726. QString result;
  27727. result.append(mNumberFormatChar);
  27728. if (mNumberBeautifulPowers)
  27729. {
  27730. result.append(QLatin1Char('b'));
  27731. if (mLabelPainter.multiplicationSymbol() == QCPLabelPainterPrivate::SymbolCross)
  27732. result.append(QLatin1Char('c'));
  27733. }
  27734. return result;
  27735. }
  27736. /*!
  27737. Returns the number of axes on the axis rect side specified with \a type.
  27738. \see axis
  27739. */
  27740. int QCPPolarAxisAngular::radialAxisCount() const
  27741. {
  27742. return mRadialAxes.size();
  27743. }
  27744. /*!
  27745. Returns the axis with the given \a index on the axis rect side specified with \a type.
  27746. \see axisCount, axes
  27747. */
  27748. QCPPolarAxisRadial *QCPPolarAxisAngular::radialAxis(int index) const
  27749. {
  27750. if (index >= 0 && index < mRadialAxes.size())
  27751. {
  27752. return mRadialAxes.at(index);
  27753. } else
  27754. {
  27755. qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index;
  27756. return nullptr;
  27757. }
  27758. }
  27759. /*!
  27760. Returns all axes on the axis rect sides specified with \a types.
  27761. \a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of
  27762. multiple sides.
  27763. \see axis
  27764. */
  27765. QList<QCPPolarAxisRadial*> QCPPolarAxisAngular::radialAxes() const
  27766. {
  27767. return mRadialAxes;
  27768. }
  27769. /*!
  27770. Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a
  27771. new QCPAxis instance is created internally. QCustomPlot owns the returned axis, so if you want to
  27772. remove an axis, use \ref removeAxis instead of deleting it manually.
  27773. You may inject QCPAxis instances (or subclasses of QCPAxis) by setting \a axis to an axis that was
  27774. previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership
  27775. of the axis, so you may not delete it afterwards. Further, the \a axis must have been created
  27776. with this axis rect as parent and with the same axis type as specified in \a type. If this is not
  27777. the case, a debug output is generated, the axis is not added, and the method returns 0.
  27778. This method can not be used to move \a axis between axis rects. The same \a axis instance must
  27779. not be added multiple times to the same or different axis rects.
  27780. If an axis rect side already contains one or more axes, the lower and upper endings of the new
  27781. axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref
  27782. QCPLineEnding::esHalfBar.
  27783. \see addAxes, setupFullAxesBox
  27784. */
  27785. QCPPolarAxisRadial *QCPPolarAxisAngular::addRadialAxis(QCPPolarAxisRadial *axis)
  27786. {
  27787. QCPPolarAxisRadial *newAxis = axis;
  27788. if (!newAxis)
  27789. {
  27790. newAxis = new QCPPolarAxisRadial(this);
  27791. } else // user provided existing axis instance, do some sanity checks
  27792. {
  27793. if (newAxis->angularAxis() != this)
  27794. {
  27795. qDebug() << Q_FUNC_INFO << "passed radial axis doesn't have this angular axis as parent angular axis";
  27796. return nullptr;
  27797. }
  27798. if (radialAxes().contains(newAxis))
  27799. {
  27800. qDebug() << Q_FUNC_INFO << "passed axis is already owned by this angular axis";
  27801. return nullptr;
  27802. }
  27803. }
  27804. mRadialAxes.append(newAxis);
  27805. return newAxis;
  27806. }
  27807. /*!
  27808. Removes the specified \a axis from the axis rect and deletes it.
  27809. Returns true on success, i.e. if \a axis was a valid axis in this axis rect.
  27810. \see addAxis
  27811. */
  27812. bool QCPPolarAxisAngular::removeRadialAxis(QCPPolarAxisRadial *radialAxis)
  27813. {
  27814. if (mRadialAxes.contains(radialAxis))
  27815. {
  27816. mRadialAxes.removeOne(radialAxis);
  27817. delete radialAxis;
  27818. return true;
  27819. } else
  27820. {
  27821. qDebug() << Q_FUNC_INFO << "Radial axis isn't associated with this angular axis:" << reinterpret_cast<quintptr>(radialAxis);
  27822. return false;
  27823. }
  27824. }
  27825. QRegion QCPPolarAxisAngular::exactClipRegion() const
  27826. {
  27827. return QRegion(mCenter.x()-mRadius, mCenter.y()-mRadius, qRound(2*mRadius), qRound(2*mRadius), QRegion::Ellipse);
  27828. }
  27829. /*!
  27830. If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
  27831. bounds of the range. The range is simply moved by \a diff.
  27832. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
  27833. corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
  27834. */
  27835. void QCPPolarAxisAngular::moveRange(double diff)
  27836. {
  27837. QCPRange oldRange = mRange;
  27838. mRange.lower += diff;
  27839. mRange.upper += diff;
  27840. emit rangeChanged(mRange);
  27841. emit rangeChanged(mRange, oldRange);
  27842. }
  27843. /*!
  27844. Scales the range of this axis by \a factor around the center of the current axis range. For
  27845. example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
  27846. range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
  27847. the center will have moved symmetrically closer).
  27848. If you wish to scale around a different coordinate than the current axis range center, use the
  27849. overload \ref scaleRange(double factor, double center).
  27850. */
  27851. void QCPPolarAxisAngular::scaleRange(double factor)
  27852. {
  27853. scaleRange(factor, range().center());
  27854. }
  27855. /*! \overload
  27856. Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
  27857. factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
  27858. coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
  27859. around 1.0 will have moved symmetrically closer to 1.0).
  27860. \see scaleRange(double factor)
  27861. */
  27862. void QCPPolarAxisAngular::scaleRange(double factor, double center)
  27863. {
  27864. QCPRange oldRange = mRange;
  27865. QCPRange newRange;
  27866. newRange.lower = (mRange.lower-center)*factor + center;
  27867. newRange.upper = (mRange.upper-center)*factor + center;
  27868. if (QCPRange::validRange(newRange))
  27869. mRange = newRange.sanitizedForLinScale();
  27870. emit rangeChanged(mRange);
  27871. emit rangeChanged(mRange, oldRange);
  27872. }
  27873. /*!
  27874. Changes the axis range such that all plottables associated with this axis are fully visible in
  27875. that dimension.
  27876. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
  27877. */
  27878. void QCPPolarAxisAngular::rescale(bool onlyVisiblePlottables)
  27879. {
  27880. QCPRange newRange;
  27881. bool haveRange = false;
  27882. for (int i=0; i<mGraphs.size(); ++i)
  27883. {
  27884. if (!mGraphs.at(i)->realVisibility() && onlyVisiblePlottables)
  27885. continue;
  27886. QCPRange range;
  27887. bool currentFoundRange;
  27888. if (mGraphs.at(i)->keyAxis() == this)
  27889. range = mGraphs.at(i)->getKeyRange(currentFoundRange, QCP::sdBoth);
  27890. else
  27891. range = mGraphs.at(i)->getValueRange(currentFoundRange, QCP::sdBoth);
  27892. if (currentFoundRange)
  27893. {
  27894. if (!haveRange)
  27895. newRange = range;
  27896. else
  27897. newRange.expand(range);
  27898. haveRange = true;
  27899. }
  27900. }
  27901. if (haveRange)
  27902. {
  27903. 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
  27904. {
  27905. 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
  27906. newRange.lower = center-mRange.size()/2.0;
  27907. newRange.upper = center+mRange.size()/2.0;
  27908. }
  27909. setRange(newRange);
  27910. }
  27911. }
  27912. /*!
  27913. Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
  27914. */
  27915. void QCPPolarAxisAngular::pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const
  27916. {
  27917. if (!mRadialAxes.isEmpty())
  27918. mRadialAxes.first()->pixelToCoord(pixelPos, angleCoord, radiusCoord);
  27919. else
  27920. qDebug() << Q_FUNC_INFO << "no radial axis configured";
  27921. }
  27922. /*!
  27923. Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
  27924. */
  27925. QPointF QCPPolarAxisAngular::coordToPixel(double angleCoord, double radiusCoord) const
  27926. {
  27927. if (!mRadialAxes.isEmpty())
  27928. {
  27929. return mRadialAxes.first()->coordToPixel(angleCoord, radiusCoord);
  27930. } else
  27931. {
  27932. qDebug() << Q_FUNC_INFO << "no radial axis configured";
  27933. return QPointF();
  27934. }
  27935. }
  27936. /*!
  27937. Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
  27938. is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
  27939. function does not change the current selection state of the axis.
  27940. If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
  27941. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
  27942. */
  27943. QCPPolarAxisAngular::SelectablePart QCPPolarAxisAngular::getPartAt(const QPointF &pos) const
  27944. {
  27945. Q_UNUSED(pos) // TODO remove later
  27946. if (!mVisible)
  27947. return spNone;
  27948. /*
  27949. TODO:
  27950. if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
  27951. return spAxis;
  27952. else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
  27953. return spTickLabels;
  27954. else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
  27955. return spAxisLabel;
  27956. else */
  27957. return spNone;
  27958. }
  27959. /* inherits documentation from base class */
  27960. double QCPPolarAxisAngular::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  27961. {
  27962. /*
  27963. if (!mParentPlot) return -1;
  27964. SelectablePart part = getPartAt(pos);
  27965. if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
  27966. return -1;
  27967. if (details)
  27968. details->setValue(part);
  27969. return mParentPlot->selectionTolerance()*0.99;
  27970. */
  27971. Q_UNUSED(details)
  27972. if (onlySelectable)
  27973. return -1;
  27974. if (QRectF(mOuterRect).contains(pos))
  27975. {
  27976. if (mParentPlot)
  27977. return mParentPlot->selectionTolerance()*0.99;
  27978. else
  27979. {
  27980. qDebug() << Q_FUNC_INFO << "parent plot not defined";
  27981. return -1;
  27982. }
  27983. } else
  27984. return -1;
  27985. }
  27986. /*!
  27987. This method is called automatically upon replot and doesn't need to be called by users of
  27988. QCPPolarAxisAngular.
  27989. Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
  27990. and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
  27991. QCPInsetLayout::update function.
  27992. \seebaseclassmethod
  27993. */
  27994. void QCPPolarAxisAngular::update(UpdatePhase phase)
  27995. {
  27996. QCPLayoutElement::update(phase);
  27997. switch (phase)
  27998. {
  27999. case upPreparation:
  28000. {
  28001. setupTickVectors();
  28002. for (int i=0; i<mRadialAxes.size(); ++i)
  28003. mRadialAxes.at(i)->setupTickVectors();
  28004. break;
  28005. }
  28006. case upLayout:
  28007. {
  28008. mCenter = mRect.center();
  28009. mRadius = 0.5*qMin(qAbs(mRect.width()), qAbs(mRect.height()));
  28010. if (mRadius < 1) mRadius = 1; // prevent cases where radius might become 0 which causes trouble
  28011. for (int i=0; i<mRadialAxes.size(); ++i)
  28012. mRadialAxes.at(i)->updateGeometry(mCenter, mRadius);
  28013. mInsetLayout->setOuterRect(rect());
  28014. break;
  28015. }
  28016. default: break;
  28017. }
  28018. // pass update call on to inset layout (doesn't happen automatically, because QCPPolarAxis doesn't derive from QCPLayout):
  28019. mInsetLayout->update(phase);
  28020. }
  28021. /* inherits documentation from base class */
  28022. QList<QCPLayoutElement*> QCPPolarAxisAngular::elements(bool recursive) const
  28023. {
  28024. QList<QCPLayoutElement*> result;
  28025. if (mInsetLayout)
  28026. {
  28027. result << mInsetLayout;
  28028. if (recursive)
  28029. result << mInsetLayout->elements(recursive);
  28030. }
  28031. return result;
  28032. }
  28033. bool QCPPolarAxisAngular::removeGraph(QCPPolarGraph *graph)
  28034. {
  28035. if (!mGraphs.contains(graph))
  28036. {
  28037. qDebug() << Q_FUNC_INFO << "graph not in list:" << reinterpret_cast<quintptr>(graph);
  28038. return false;
  28039. }
  28040. // remove plottable from legend:
  28041. graph->removeFromLegend();
  28042. // remove plottable:
  28043. delete graph;
  28044. mGraphs.removeOne(graph);
  28045. return true;
  28046. }
  28047. /* inherits documentation from base class */
  28048. void QCPPolarAxisAngular::applyDefaultAntialiasingHint(QCPPainter *painter) const
  28049. {
  28050. applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
  28051. }
  28052. /* inherits documentation from base class */
  28053. void QCPPolarAxisAngular::draw(QCPPainter *painter)
  28054. {
  28055. drawBackground(painter, mCenter, mRadius);
  28056. // draw baseline circle:
  28057. painter->setPen(getBasePen());
  28058. painter->drawEllipse(mCenter, mRadius, mRadius);
  28059. // draw subticks:
  28060. if (!mSubTickVector.isEmpty())
  28061. {
  28062. painter->setPen(getSubTickPen());
  28063. for (int i=0; i<mSubTickVector.size(); ++i)
  28064. {
  28065. painter->drawLine(mCenter+mSubTickVectorCosSin.at(i)*(mRadius-mSubTickLengthIn),
  28066. mCenter+mSubTickVectorCosSin.at(i)*(mRadius+mSubTickLengthOut));
  28067. }
  28068. }
  28069. // draw ticks and labels:
  28070. if (!mTickVector.isEmpty())
  28071. {
  28072. mLabelPainter.setAnchorReference(mCenter);
  28073. mLabelPainter.setFont(getTickLabelFont());
  28074. mLabelPainter.setColor(getTickLabelColor());
  28075. const QPen ticksPen = getTickPen();
  28076. painter->setPen(ticksPen);
  28077. for (int i=0; i<mTickVector.size(); ++i)
  28078. {
  28079. const QPointF outerTick = mCenter+mTickVectorCosSin.at(i)*(mRadius+mTickLengthOut);
  28080. painter->drawLine(mCenter+mTickVectorCosSin.at(i)*(mRadius-mTickLengthIn), outerTick);
  28081. // draw tick labels:
  28082. if (!mTickVectorLabels.isEmpty())
  28083. {
  28084. 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
  28085. mLabelPainter.drawTickLabel(painter, outerTick, mTickVectorLabels.at(i));
  28086. }
  28087. }
  28088. }
  28089. }
  28090. /* inherits documentation from base class */
  28091. QCP::Interaction QCPPolarAxisAngular::selectionCategory() const
  28092. {
  28093. return QCP::iSelectAxes;
  28094. }
  28095. /*!
  28096. Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the
  28097. axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect
  28098. backgrounds are usually drawn below everything else.
  28099. For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be
  28100. enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio
  28101. is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  28102. consider using the overloaded version of this function.
  28103. Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref
  28104. setBackground(const QBrush &brush).
  28105. \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush)
  28106. */
  28107. void QCPPolarAxisAngular::setBackground(const QPixmap &pm)
  28108. {
  28109. mBackgroundPixmap = pm;
  28110. mScaledBackgroundPixmap = QPixmap();
  28111. }
  28112. /*! \overload
  28113. Sets \a brush as the background brush. The axis rect background will be filled with this brush.
  28114. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds
  28115. are usually drawn below everything else.
  28116. The brush will be drawn before (under) any background pixmap, which may be specified with \ref
  28117. setBackground(const QPixmap &pm).
  28118. To disable drawing of a background brush, set \a brush to Qt::NoBrush.
  28119. \see setBackground(const QPixmap &pm)
  28120. */
  28121. void QCPPolarAxisAngular::setBackground(const QBrush &brush)
  28122. {
  28123. mBackgroundBrush = brush;
  28124. }
  28125. /*! \overload
  28126. Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it
  28127. shall be scaled in one call.
  28128. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  28129. */
  28130. void QCPPolarAxisAngular::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
  28131. {
  28132. mBackgroundPixmap = pm;
  28133. mScaledBackgroundPixmap = QPixmap();
  28134. mBackgroundScaled = scaled;
  28135. mBackgroundScaledMode = mode;
  28136. }
  28137. /*!
  28138. Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled
  28139. is set to true, you may control whether and how the aspect ratio of the original pixmap is
  28140. preserved with \ref setBackgroundScaledMode.
  28141. Note that the scaled version of the original pixmap is buffered, so there is no performance
  28142. penalty on replots. (Except when the axis rect dimensions are changed continuously.)
  28143. \see setBackground, setBackgroundScaledMode
  28144. */
  28145. void QCPPolarAxisAngular::setBackgroundScaled(bool scaled)
  28146. {
  28147. mBackgroundScaled = scaled;
  28148. }
  28149. /*!
  28150. If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to
  28151. define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved.
  28152. \see setBackground, setBackgroundScaled
  28153. */
  28154. void QCPPolarAxisAngular::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  28155. {
  28156. mBackgroundScaledMode = mode;
  28157. }
  28158. void QCPPolarAxisAngular::setRangeDrag(bool enabled)
  28159. {
  28160. mRangeDrag = enabled;
  28161. }
  28162. void QCPPolarAxisAngular::setRangeZoom(bool enabled)
  28163. {
  28164. mRangeZoom = enabled;
  28165. }
  28166. void QCPPolarAxisAngular::setRangeZoomFactor(double factor)
  28167. {
  28168. mRangeZoomFactor = factor;
  28169. }
  28170. /*!
  28171. Sets the range of the axis.
  28172. This slot may be connected with the \ref rangeChanged signal of another axis so this axis
  28173. is always synchronized with the other axis range, when it changes.
  28174. To invert the direction of an axis, use \ref setRangeReversed.
  28175. */
  28176. void QCPPolarAxisAngular::setRange(const QCPRange &range)
  28177. {
  28178. if (qFuzzyCompare(range.lower, mRange.lower) && qFuzzyCompare(range.upper, mRange.upper))
  28179. return;
  28180. if (!QCPRange::validRange(range)) return;
  28181. QCPRange oldRange = mRange;
  28182. mRange = range.sanitizedForLinScale();
  28183. emit rangeChanged(mRange);
  28184. emit rangeChanged(mRange, oldRange);
  28185. }
  28186. /*!
  28187. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  28188. (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
  28189. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  28190. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  28191. directly.
  28192. \see SelectablePart, setSelectedParts
  28193. */
  28194. void QCPPolarAxisAngular::setSelectableParts(const SelectableParts &selectable)
  28195. {
  28196. if (mSelectableParts != selectable)
  28197. {
  28198. mSelectableParts = selectable;
  28199. emit selectableChanged(mSelectableParts);
  28200. }
  28201. }
  28202. /*!
  28203. Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
  28204. is selected, it uses a different pen/font.
  28205. The entire selection mechanism for axes is handled automatically when \ref
  28206. QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
  28207. wish to change the selection state manually.
  28208. This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
  28209. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  28210. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
  28211. setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
  28212. */
  28213. void QCPPolarAxisAngular::setSelectedParts(const SelectableParts &selected)
  28214. {
  28215. if (mSelectedParts != selected)
  28216. {
  28217. mSelectedParts = selected;
  28218. emit selectionChanged(mSelectedParts);
  28219. }
  28220. }
  28221. /*!
  28222. \overload
  28223. Sets the lower and upper bound of the axis range.
  28224. To invert the direction of an axis, use \ref setRangeReversed.
  28225. There is also a slot to set a range, see \ref setRange(const QCPRange &range).
  28226. */
  28227. void QCPPolarAxisAngular::setRange(double lower, double upper)
  28228. {
  28229. if (qFuzzyCompare(lower, mRange.lower) && qFuzzyCompare(upper, mRange.upper))
  28230. return;
  28231. if (!QCPRange::validRange(lower, upper)) return;
  28232. QCPRange oldRange = mRange;
  28233. mRange.lower = lower;
  28234. mRange.upper = upper;
  28235. mRange = mRange.sanitizedForLinScale();
  28236. emit rangeChanged(mRange);
  28237. emit rangeChanged(mRange, oldRange);
  28238. }
  28239. /*!
  28240. \overload
  28241. Sets the range of the axis.
  28242. The \a position coordinate indicates together with the \a alignment parameter, where the new
  28243. range will be positioned. \a size defines the size of the new axis range. \a alignment may be
  28244. Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
  28245. or center of the range to be aligned with \a position. Any other values of \a alignment will
  28246. default to Qt::AlignCenter.
  28247. */
  28248. void QCPPolarAxisAngular::setRange(double position, double size, Qt::AlignmentFlag alignment)
  28249. {
  28250. if (alignment == Qt::AlignLeft)
  28251. setRange(position, position+size);
  28252. else if (alignment == Qt::AlignRight)
  28253. setRange(position-size, position);
  28254. else // alignment == Qt::AlignCenter
  28255. setRange(position-size/2.0, position+size/2.0);
  28256. }
  28257. /*!
  28258. Sets the lower bound of the axis range. The upper bound is not changed.
  28259. \see setRange
  28260. */
  28261. void QCPPolarAxisAngular::setRangeLower(double lower)
  28262. {
  28263. if (qFuzzyCompare(mRange.lower, lower))
  28264. return;
  28265. QCPRange oldRange = mRange;
  28266. mRange.lower = lower;
  28267. mRange = mRange.sanitizedForLinScale();
  28268. emit rangeChanged(mRange);
  28269. emit rangeChanged(mRange, oldRange);
  28270. }
  28271. /*!
  28272. Sets the upper bound of the axis range. The lower bound is not changed.
  28273. \see setRange
  28274. */
  28275. void QCPPolarAxisAngular::setRangeUpper(double upper)
  28276. {
  28277. if (qFuzzyCompare(mRange.upper, upper))
  28278. return;
  28279. QCPRange oldRange = mRange;
  28280. mRange.upper = upper;
  28281. mRange = mRange.sanitizedForLinScale();
  28282. emit rangeChanged(mRange);
  28283. emit rangeChanged(mRange, oldRange);
  28284. }
  28285. /*!
  28286. Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
  28287. axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
  28288. direction of increasing values is inverted.
  28289. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
  28290. of the \ref setRange interface will still reference the mathematically smaller number than the \a
  28291. upper part.
  28292. */
  28293. void QCPPolarAxisAngular::setRangeReversed(bool reversed)
  28294. {
  28295. mRangeReversed = reversed;
  28296. }
  28297. void QCPPolarAxisAngular::setAngle(double degrees)
  28298. {
  28299. mAngle = degrees;
  28300. mAngleRad = mAngle/180.0*M_PI;
  28301. }
  28302. /*!
  28303. The axis ticker is responsible for generating the tick positions and tick labels. See the
  28304. documentation of QCPAxisTicker for details on how to work with axis tickers.
  28305. You can change the tick positioning/labeling behaviour of this axis by setting a different
  28306. QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
  28307. ticker, access it via \ref ticker.
  28308. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  28309. ticker simply by passing the same shared pointer to multiple axes.
  28310. \see ticker
  28311. */
  28312. void QCPPolarAxisAngular::setTicker(QSharedPointer<QCPAxisTicker> ticker)
  28313. {
  28314. if (ticker)
  28315. mTicker = ticker;
  28316. else
  28317. qDebug() << Q_FUNC_INFO << "can not set 0 as axis ticker";
  28318. // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
  28319. }
  28320. /*!
  28321. Sets whether tick marks are displayed.
  28322. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
  28323. that, see \ref setTickLabels.
  28324. \see setSubTicks
  28325. */
  28326. void QCPPolarAxisAngular::setTicks(bool show)
  28327. {
  28328. if (mTicks != show)
  28329. {
  28330. mTicks = show;
  28331. //mCachedMarginValid = false;
  28332. }
  28333. }
  28334. /*!
  28335. Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
  28336. */
  28337. void QCPPolarAxisAngular::setTickLabels(bool show)
  28338. {
  28339. if (mTickLabels != show)
  28340. {
  28341. mTickLabels = show;
  28342. //mCachedMarginValid = false;
  28343. if (!mTickLabels)
  28344. mTickVectorLabels.clear();
  28345. }
  28346. }
  28347. /*!
  28348. Sets the distance between the axis base line (including any outward ticks) and the tick labels.
  28349. \see setLabelPadding, setPadding
  28350. */
  28351. void QCPPolarAxisAngular::setTickLabelPadding(int padding)
  28352. {
  28353. mLabelPainter.setPadding(padding);
  28354. }
  28355. /*!
  28356. Sets the font of the tick labels.
  28357. \see setTickLabels, setTickLabelColor
  28358. */
  28359. void QCPPolarAxisAngular::setTickLabelFont(const QFont &font)
  28360. {
  28361. mTickLabelFont = font;
  28362. }
  28363. /*!
  28364. Sets the color of the tick labels.
  28365. \see setTickLabels, setTickLabelFont
  28366. */
  28367. void QCPPolarAxisAngular::setTickLabelColor(const QColor &color)
  28368. {
  28369. mTickLabelColor = color;
  28370. }
  28371. /*!
  28372. Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
  28373. the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
  28374. from -90 to 90 degrees.
  28375. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
  28376. other angles, the label is drawn with an offset such that it seems to point toward or away from
  28377. the tick mark.
  28378. */
  28379. void QCPPolarAxisAngular::setTickLabelRotation(double degrees)
  28380. {
  28381. mLabelPainter.setRotation(degrees);
  28382. }
  28383. void QCPPolarAxisAngular::setTickLabelMode(LabelMode mode)
  28384. {
  28385. switch (mode)
  28386. {
  28387. case lmUpright: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedUpright); break;
  28388. case lmRotated: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedRotated); break;
  28389. }
  28390. }
  28391. /*!
  28392. Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
  28393. of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
  28394. that, see the "Argument Formats" section in the detailed description of the QString class.
  28395. \a formatCode is a string of one, two or three characters. The first character is identical to
  28396. the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
  28397. format, 'g'/'G' scientific or fixed, whichever is shorter.
  28398. The second and third characters are optional and specific to QCustomPlot:\n If the first char was
  28399. 'e' or 'g', numbers are/might be displayed in the scientific format, e.g. "5.5e9", which might be
  28400. visually unappealing in a plot. So when the second char of \a formatCode is set to 'b' (for
  28401. "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
  28402. [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
  28403. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
  28404. be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
  28405. cross and 183 (0xB7) for the dot.
  28406. Examples for \a formatCode:
  28407. \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
  28408. normal scientific format is used
  28409. \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
  28410. beautifully typeset decimal powers and a dot as multiplication sign
  28411. \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
  28412. multiplication sign
  28413. \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
  28414. powers. Format code will be reduced to 'f'.
  28415. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
  28416. code will not be changed.
  28417. */
  28418. void QCPPolarAxisAngular::setNumberFormat(const QString &formatCode)
  28419. {
  28420. if (formatCode.isEmpty())
  28421. {
  28422. qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
  28423. return;
  28424. }
  28425. //mCachedMarginValid = false;
  28426. // interpret first char as number format char:
  28427. QString allowedFormatChars(QLatin1String("eEfgG"));
  28428. if (allowedFormatChars.contains(formatCode.at(0)))
  28429. {
  28430. mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
  28431. } else
  28432. {
  28433. qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
  28434. return;
  28435. }
  28436. if (formatCode.length() < 2)
  28437. {
  28438. mNumberBeautifulPowers = false;
  28439. mNumberMultiplyCross = false;
  28440. } else
  28441. {
  28442. // interpret second char as indicator for beautiful decimal powers:
  28443. if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
  28444. mNumberBeautifulPowers = true;
  28445. else
  28446. qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
  28447. if (formatCode.length() < 3)
  28448. {
  28449. mNumberMultiplyCross = false;
  28450. } else
  28451. {
  28452. // interpret third char as indicator for dot or cross multiplication symbol:
  28453. if (formatCode.at(2) == QLatin1Char('c'))
  28454. mNumberMultiplyCross = true;
  28455. else if (formatCode.at(2) == QLatin1Char('d'))
  28456. mNumberMultiplyCross = false;
  28457. else
  28458. qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
  28459. }
  28460. }
  28461. mLabelPainter.setSubstituteExponent(mNumberBeautifulPowers);
  28462. mLabelPainter.setMultiplicationSymbol(mNumberMultiplyCross ? QCPLabelPainterPrivate::SymbolCross : QCPLabelPainterPrivate::SymbolDot);
  28463. }
  28464. /*!
  28465. Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
  28466. for details. The effect of precisions are most notably for number Formats starting with 'e', see
  28467. \ref setNumberFormat
  28468. */
  28469. void QCPPolarAxisAngular::setNumberPrecision(int precision)
  28470. {
  28471. if (mNumberPrecision != precision)
  28472. {
  28473. mNumberPrecision = precision;
  28474. //mCachedMarginValid = false;
  28475. }
  28476. }
  28477. /*!
  28478. Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
  28479. plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
  28480. zero, the tick labels and axis label will increase their distance to the axis accordingly, so
  28481. they won't collide with the ticks.
  28482. \see setSubTickLength, setTickLengthIn, setTickLengthOut
  28483. */
  28484. void QCPPolarAxisAngular::setTickLength(int inside, int outside)
  28485. {
  28486. setTickLengthIn(inside);
  28487. setTickLengthOut(outside);
  28488. }
  28489. /*!
  28490. Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
  28491. inside the plot.
  28492. \see setTickLengthOut, setTickLength, setSubTickLength
  28493. */
  28494. void QCPPolarAxisAngular::setTickLengthIn(int inside)
  28495. {
  28496. if (mTickLengthIn != inside)
  28497. {
  28498. mTickLengthIn = inside;
  28499. }
  28500. }
  28501. /*!
  28502. Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
  28503. outside the plot. If \a outside is greater than zero, the tick labels and axis label will
  28504. increase their distance to the axis accordingly, so they won't collide with the ticks.
  28505. \see setTickLengthIn, setTickLength, setSubTickLength
  28506. */
  28507. void QCPPolarAxisAngular::setTickLengthOut(int outside)
  28508. {
  28509. if (mTickLengthOut != outside)
  28510. {
  28511. mTickLengthOut = outside;
  28512. //mCachedMarginValid = false; // only outside tick length can change margin
  28513. }
  28514. }
  28515. /*!
  28516. Sets whether sub tick marks are displayed.
  28517. Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
  28518. \see setTicks
  28519. */
  28520. void QCPPolarAxisAngular::setSubTicks(bool show)
  28521. {
  28522. if (mSubTicks != show)
  28523. {
  28524. mSubTicks = show;
  28525. //mCachedMarginValid = false;
  28526. }
  28527. }
  28528. /*!
  28529. Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
  28530. the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
  28531. than zero, the tick labels and axis label will increase their distance to the axis accordingly,
  28532. so they won't collide with the ticks.
  28533. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
  28534. */
  28535. void QCPPolarAxisAngular::setSubTickLength(int inside, int outside)
  28536. {
  28537. setSubTickLengthIn(inside);
  28538. setSubTickLengthOut(outside);
  28539. }
  28540. /*!
  28541. Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
  28542. the plot.
  28543. \see setSubTickLengthOut, setSubTickLength, setTickLength
  28544. */
  28545. void QCPPolarAxisAngular::setSubTickLengthIn(int inside)
  28546. {
  28547. if (mSubTickLengthIn != inside)
  28548. {
  28549. mSubTickLengthIn = inside;
  28550. }
  28551. }
  28552. /*!
  28553. Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
  28554. outside the plot. If \a outside is greater than zero, the tick labels will increase their
  28555. distance to the axis accordingly, so they won't collide with the ticks.
  28556. \see setSubTickLengthIn, setSubTickLength, setTickLength
  28557. */
  28558. void QCPPolarAxisAngular::setSubTickLengthOut(int outside)
  28559. {
  28560. if (mSubTickLengthOut != outside)
  28561. {
  28562. mSubTickLengthOut = outside;
  28563. //mCachedMarginValid = false; // only outside tick length can change margin
  28564. }
  28565. }
  28566. /*!
  28567. Sets the pen, the axis base line is drawn with.
  28568. \see setTickPen, setSubTickPen
  28569. */
  28570. void QCPPolarAxisAngular::setBasePen(const QPen &pen)
  28571. {
  28572. mBasePen = pen;
  28573. }
  28574. /*!
  28575. Sets the pen, tick marks will be drawn with.
  28576. \see setTickLength, setBasePen
  28577. */
  28578. void QCPPolarAxisAngular::setTickPen(const QPen &pen)
  28579. {
  28580. mTickPen = pen;
  28581. }
  28582. /*!
  28583. Sets the pen, subtick marks will be drawn with.
  28584. \see setSubTickCount, setSubTickLength, setBasePen
  28585. */
  28586. void QCPPolarAxisAngular::setSubTickPen(const QPen &pen)
  28587. {
  28588. mSubTickPen = pen;
  28589. }
  28590. /*!
  28591. Sets the font of the axis label.
  28592. \see setLabelColor
  28593. */
  28594. void QCPPolarAxisAngular::setLabelFont(const QFont &font)
  28595. {
  28596. if (mLabelFont != font)
  28597. {
  28598. mLabelFont = font;
  28599. //mCachedMarginValid = false;
  28600. }
  28601. }
  28602. /*!
  28603. Sets the color of the axis label.
  28604. \see setLabelFont
  28605. */
  28606. void QCPPolarAxisAngular::setLabelColor(const QColor &color)
  28607. {
  28608. mLabelColor = color;
  28609. }
  28610. /*!
  28611. Sets the text of the axis label that will be shown below/above or next to the axis, depending on
  28612. its orientation. To disable axis labels, pass an empty string as \a str.
  28613. */
  28614. void QCPPolarAxisAngular::setLabel(const QString &str)
  28615. {
  28616. if (mLabel != str)
  28617. {
  28618. mLabel = str;
  28619. //mCachedMarginValid = false;
  28620. }
  28621. }
  28622. /*!
  28623. Sets the distance between the tick labels and the axis label.
  28624. \see setTickLabelPadding, setPadding
  28625. */
  28626. void QCPPolarAxisAngular::setLabelPadding(int padding)
  28627. {
  28628. if (mLabelPadding != padding)
  28629. {
  28630. mLabelPadding = padding;
  28631. //mCachedMarginValid = false;
  28632. }
  28633. }
  28634. /*!
  28635. Sets the font that is used for tick labels when they are selected.
  28636. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28637. */
  28638. void QCPPolarAxisAngular::setSelectedTickLabelFont(const QFont &font)
  28639. {
  28640. if (font != mSelectedTickLabelFont)
  28641. {
  28642. mSelectedTickLabelFont = font;
  28643. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  28644. }
  28645. }
  28646. /*!
  28647. Sets the font that is used for the axis label when it is selected.
  28648. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28649. */
  28650. void QCPPolarAxisAngular::setSelectedLabelFont(const QFont &font)
  28651. {
  28652. mSelectedLabelFont = font;
  28653. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  28654. }
  28655. /*!
  28656. Sets the color that is used for tick labels when they are selected.
  28657. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28658. */
  28659. void QCPPolarAxisAngular::setSelectedTickLabelColor(const QColor &color)
  28660. {
  28661. if (color != mSelectedTickLabelColor)
  28662. {
  28663. mSelectedTickLabelColor = color;
  28664. }
  28665. }
  28666. /*!
  28667. Sets the color that is used for the axis label when it is selected.
  28668. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28669. */
  28670. void QCPPolarAxisAngular::setSelectedLabelColor(const QColor &color)
  28671. {
  28672. mSelectedLabelColor = color;
  28673. }
  28674. /*!
  28675. Sets the pen that is used to draw the axis base line when selected.
  28676. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28677. */
  28678. void QCPPolarAxisAngular::setSelectedBasePen(const QPen &pen)
  28679. {
  28680. mSelectedBasePen = pen;
  28681. }
  28682. /*!
  28683. Sets the pen that is used to draw the (major) ticks when selected.
  28684. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28685. */
  28686. void QCPPolarAxisAngular::setSelectedTickPen(const QPen &pen)
  28687. {
  28688. mSelectedTickPen = pen;
  28689. }
  28690. /*!
  28691. Sets the pen that is used to draw the subticks when selected.
  28692. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28693. */
  28694. void QCPPolarAxisAngular::setSelectedSubTickPen(const QPen &pen)
  28695. {
  28696. mSelectedSubTickPen = pen;
  28697. }
  28698. /*! \internal
  28699. Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a
  28700. pixmap.
  28701. If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an
  28702. according filling inside the axis rect with the provided \a painter.
  28703. Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version
  28704. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  28705. the axis rect with the provided \a painter. The scaled version is buffered in
  28706. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  28707. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  28708. dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
  28709. set.
  28710. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  28711. */
  28712. void QCPPolarAxisAngular::drawBackground(QCPPainter *painter, const QPointF &center, double radius)
  28713. {
  28714. // draw background fill (don't use circular clip, looks bad):
  28715. if (mBackgroundBrush != Qt::NoBrush)
  28716. {
  28717. QPainterPath ellipsePath;
  28718. ellipsePath.addEllipse(center, radius, radius);
  28719. painter->fillPath(ellipsePath, mBackgroundBrush);
  28720. }
  28721. // draw background pixmap (on top of fill, if brush specified):
  28722. if (!mBackgroundPixmap.isNull())
  28723. {
  28724. QRegion clipCircle(int(center.x()-radius), int(center.y()-radius), qRound(2*radius), qRound(2*radius), QRegion::Ellipse);
  28725. QRegion originalClip = painter->clipRegion();
  28726. painter->setClipRegion(clipCircle);
  28727. if (mBackgroundScaled)
  28728. {
  28729. // check whether mScaledBackground needs to be updated:
  28730. QSizeF scaledSize(mBackgroundPixmap.size());
  28731. scaledSize.scale(mRect.size(), mBackgroundScaledMode);
  28732. if (mScaledBackgroundPixmap.size() != scaledSize)
  28733. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size().toSize(), mBackgroundScaledMode, Qt::SmoothTransformation);
  28734. painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRectF(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect());
  28735. } else
  28736. {
  28737. painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRectF(0, 0, mRect.width(), mRect.height()));
  28738. }
  28739. painter->setClipRegion(originalClip);
  28740. }
  28741. }
  28742. /*! \internal
  28743. Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
  28744. QCPAxisTicker::generate on the currently installed ticker.
  28745. If a change in the label text/count is detected, the cached axis margin is invalidated to make
  28746. sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
  28747. */
  28748. void QCPPolarAxisAngular::setupTickVectors()
  28749. {
  28750. if (!mParentPlot) return;
  28751. if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
  28752. mSubTickVector.clear(); // since we might not pass it to mTicker->generate(), and we don't want old data in there
  28753. mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : nullptr, mTickLabels ? &mTickVectorLabels : nullptr);
  28754. // fill cos/sin buffers which will be used by draw() and QCPPolarGrid::draw(), so we don't have to calculate it twice:
  28755. mTickVectorCosSin.resize(mTickVector.size());
  28756. for (int i=0; i<mTickVector.size(); ++i)
  28757. {
  28758. const double theta = coordToAngleRad(mTickVector.at(i));
  28759. mTickVectorCosSin[i] = QPointF(qCos(theta), qSin(theta));
  28760. }
  28761. mSubTickVectorCosSin.resize(mSubTickVector.size());
  28762. for (int i=0; i<mSubTickVector.size(); ++i)
  28763. {
  28764. const double theta = coordToAngleRad(mSubTickVector.at(i));
  28765. mSubTickVectorCosSin[i] = QPointF(qCos(theta), qSin(theta));
  28766. }
  28767. }
  28768. /*! \internal
  28769. Returns the pen that is used to draw the axis base line. Depending on the selection state, this
  28770. is either mSelectedBasePen or mBasePen.
  28771. */
  28772. QPen QCPPolarAxisAngular::getBasePen() const
  28773. {
  28774. return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
  28775. }
  28776. /*! \internal
  28777. Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
  28778. is either mSelectedTickPen or mTickPen.
  28779. */
  28780. QPen QCPPolarAxisAngular::getTickPen() const
  28781. {
  28782. return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
  28783. }
  28784. /*! \internal
  28785. Returns the pen that is used to draw the subticks. Depending on the selection state, this
  28786. is either mSelectedSubTickPen or mSubTickPen.
  28787. */
  28788. QPen QCPPolarAxisAngular::getSubTickPen() const
  28789. {
  28790. return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
  28791. }
  28792. /*! \internal
  28793. Returns the font that is used to draw the tick labels. Depending on the selection state, this
  28794. is either mSelectedTickLabelFont or mTickLabelFont.
  28795. */
  28796. QFont QCPPolarAxisAngular::getTickLabelFont() const
  28797. {
  28798. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
  28799. }
  28800. /*! \internal
  28801. Returns the font that is used to draw the axis label. Depending on the selection state, this
  28802. is either mSelectedLabelFont or mLabelFont.
  28803. */
  28804. QFont QCPPolarAxisAngular::getLabelFont() const
  28805. {
  28806. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
  28807. }
  28808. /*! \internal
  28809. Returns the color that is used to draw the tick labels. Depending on the selection state, this
  28810. is either mSelectedTickLabelColor or mTickLabelColor.
  28811. */
  28812. QColor QCPPolarAxisAngular::getTickLabelColor() const
  28813. {
  28814. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
  28815. }
  28816. /*! \internal
  28817. Returns the color that is used to draw the axis label. Depending on the selection state, this
  28818. is either mSelectedLabelColor or mLabelColor.
  28819. */
  28820. QColor QCPPolarAxisAngular::getLabelColor() const
  28821. {
  28822. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
  28823. }
  28824. /*! \internal
  28825. Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
  28826. pressed, the range dragging interaction is initialized (the actual range manipulation happens in
  28827. the \ref mouseMoveEvent).
  28828. The mDragging flag is set to true and some anchor points are set that are needed to determine the
  28829. distance the mouse was dragged in the mouse move/release events later.
  28830. \see mouseMoveEvent, mouseReleaseEvent
  28831. */
  28832. void QCPPolarAxisAngular::mousePressEvent(QMouseEvent *event, const QVariant &details)
  28833. {
  28834. Q_UNUSED(details)
  28835. if (event->buttons() & Qt::LeftButton)
  28836. {
  28837. mDragging = true;
  28838. // initialize antialiasing backup in case we start dragging:
  28839. if (mParentPlot->noAntialiasingOnDrag())
  28840. {
  28841. mAADragBackup = mParentPlot->antialiasedElements();
  28842. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  28843. }
  28844. // Mouse range dragging interaction:
  28845. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  28846. {
  28847. mDragAngularStart = range();
  28848. mDragRadialStart.clear();
  28849. for (int i=0; i<mRadialAxes.size(); ++i)
  28850. mDragRadialStart.append(mRadialAxes.at(i)->range());
  28851. }
  28852. }
  28853. }
  28854. /*! \internal
  28855. Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a
  28856. preceding \ref mousePressEvent, the range is moved accordingly.
  28857. \see mousePressEvent, mouseReleaseEvent
  28858. */
  28859. void QCPPolarAxisAngular::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  28860. {
  28861. Q_UNUSED(startPos)
  28862. bool doReplot = false;
  28863. // Mouse range dragging interaction:
  28864. if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  28865. {
  28866. if (mRangeDrag)
  28867. {
  28868. doReplot = true;
  28869. double angleCoordStart, radiusCoordStart;
  28870. double angleCoord, radiusCoord;
  28871. pixelToCoord(startPos, angleCoordStart, radiusCoordStart);
  28872. pixelToCoord(event->pos(), angleCoord, radiusCoord);
  28873. double diff = angleCoordStart - angleCoord;
  28874. setRange(mDragAngularStart.lower+diff, mDragAngularStart.upper+diff);
  28875. }
  28876. for (int i=0; i<mRadialAxes.size(); ++i)
  28877. {
  28878. QCPPolarAxisRadial *ax = mRadialAxes.at(i);
  28879. if (!ax->rangeDrag())
  28880. continue;
  28881. doReplot = true;
  28882. double angleCoordStart, radiusCoordStart;
  28883. double angleCoord, radiusCoord;
  28884. ax->pixelToCoord(startPos, angleCoordStart, radiusCoordStart);
  28885. ax->pixelToCoord(event->pos(), angleCoord, radiusCoord);
  28886. if (ax->scaleType() == QCPPolarAxisRadial::stLinear)
  28887. {
  28888. double diff = radiusCoordStart - radiusCoord;
  28889. ax->setRange(mDragRadialStart.at(i).lower+diff, mDragRadialStart.at(i).upper+diff);
  28890. } else if (ax->scaleType() == QCPPolarAxisRadial::stLogarithmic)
  28891. {
  28892. if (!qFuzzyCompare(radiusCoord, 0))
  28893. {
  28894. double diff = radiusCoordStart/radiusCoord;
  28895. ax->setRange(mDragRadialStart.at(i).lower*diff, mDragRadialStart.at(i).upper*diff);
  28896. }
  28897. }
  28898. }
  28899. if (doReplot) // if either vertical or horizontal drag was enabled, do a replot
  28900. {
  28901. if (mParentPlot->noAntialiasingOnDrag())
  28902. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  28903. mParentPlot->replot(QCustomPlot::rpQueuedReplot);
  28904. }
  28905. }
  28906. }
  28907. /* inherits documentation from base class */
  28908. void QCPPolarAxisAngular::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  28909. {
  28910. Q_UNUSED(event)
  28911. Q_UNUSED(startPos)
  28912. mDragging = false;
  28913. if (mParentPlot->noAntialiasingOnDrag())
  28914. {
  28915. mParentPlot->setAntialiasedElements(mAADragBackup);
  28916. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  28917. }
  28918. }
  28919. /*! \internal
  28920. Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
  28921. ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
  28922. the scaling operation is the current cursor position inside the axis rect. The scaling factor is
  28923. dependent on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
  28924. zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
  28925. Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse
  28926. wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be
  28927. multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as
  28928. exponent of the range zoom factor. This takes care of the wheel direction automatically, by
  28929. inverting the factor, when the wheel step is negative (f^-1 = 1/f).
  28930. */
  28931. void QCPPolarAxisAngular::wheelEvent(QWheelEvent *event)
  28932. {
  28933. bool doReplot = false;
  28934. // Mouse range zooming interaction:
  28935. if (mParentPlot->interactions().testFlag(QCP::iRangeZoom))
  28936. {
  28937. #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  28938. const double delta = event->delta();
  28939. #else
  28940. const double delta = event->angleDelta().y();
  28941. #endif
  28942. #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  28943. const QPointF pos = event->pos();
  28944. #else
  28945. const QPointF pos = event->position();
  28946. #endif
  28947. const double wheelSteps = delta/120.0; // a single step delta is +/-120 usually
  28948. if (mRangeZoom)
  28949. {
  28950. double angleCoord, radiusCoord;
  28951. pixelToCoord(pos, angleCoord, radiusCoord);
  28952. scaleRange(qPow(mRangeZoomFactor, wheelSteps), angleCoord);
  28953. }
  28954. for (int i=0; i<mRadialAxes.size(); ++i)
  28955. {
  28956. QCPPolarAxisRadial *ax = mRadialAxes.at(i);
  28957. if (!ax->rangeZoom())
  28958. continue;
  28959. doReplot = true;
  28960. double angleCoord, radiusCoord;
  28961. ax->pixelToCoord(pos, angleCoord, radiusCoord);
  28962. ax->scaleRange(qPow(ax->rangeZoomFactor(), wheelSteps), radiusCoord);
  28963. }
  28964. }
  28965. if (doReplot)
  28966. mParentPlot->replot();
  28967. }
  28968. bool QCPPolarAxisAngular::registerPolarGraph(QCPPolarGraph *graph)
  28969. {
  28970. if (mGraphs.contains(graph))
  28971. {
  28972. qDebug() << Q_FUNC_INFO << "plottable already added:" << reinterpret_cast<quintptr>(graph);
  28973. return false;
  28974. }
  28975. if (graph->keyAxis() != this)
  28976. {
  28977. qDebug() << Q_FUNC_INFO << "plottable not created with this as axis:" << reinterpret_cast<quintptr>(graph);
  28978. return false;
  28979. }
  28980. mGraphs.append(graph);
  28981. // possibly add plottable to legend:
  28982. if (mParentPlot->autoAddPlottableToLegend())
  28983. graph->addToLegend();
  28984. if (!graph->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
  28985. graph->setLayer(mParentPlot->currentLayer());
  28986. return true;
  28987. }
  28988. /* end of 'src/polar/layoutelement-angularaxis.cpp' */
  28989. /* including file 'src/polar/polargrid.cpp' */
  28990. /* modified 2021-03-29T02:30:44, size 7493 */
  28991. ////////////////////////////////////////////////////////////////////////////////////////////////////
  28992. //////////////////// QCPPolarGrid
  28993. ////////////////////////////////////////////////////////////////////////////////////////////////////
  28994. /*! \class QCPPolarGrid
  28995. \brief The grid in both angular and radial dimensions for polar plots
  28996. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  28997. functionality to be incomplete, as well as changing public interfaces in the future.
  28998. */
  28999. /*!
  29000. Creates a QCPPolarGrid instance and sets default values.
  29001. You shouldn't instantiate grids on their own, since every axis brings its own grid.
  29002. */
  29003. QCPPolarGrid::QCPPolarGrid(QCPPolarAxisAngular *parentAxis) :
  29004. QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis),
  29005. mType(gtNone),
  29006. mSubGridType(gtNone),
  29007. mAntialiasedSubGrid(true),
  29008. mAntialiasedZeroLine(true),
  29009. mParentAxis(parentAxis)
  29010. {
  29011. // warning: this is called in QCPPolarAxisAngular constructor, so parentAxis members should not be accessed/called
  29012. setParent(parentAxis);
  29013. setType(gtAll);
  29014. setSubGridType(gtNone);
  29015. setAngularPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
  29016. setAngularSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
  29017. setRadialPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
  29018. setRadialSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
  29019. setRadialZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine));
  29020. setAntialiased(true);
  29021. }
  29022. void QCPPolarGrid::setRadialAxis(QCPPolarAxisRadial *axis)
  29023. {
  29024. mRadialAxis = axis;
  29025. }
  29026. void QCPPolarGrid::setType(GridTypes type)
  29027. {
  29028. mType = type;
  29029. }
  29030. void QCPPolarGrid::setSubGridType(GridTypes type)
  29031. {
  29032. mSubGridType = type;
  29033. }
  29034. /*!
  29035. Sets whether sub grid lines are drawn antialiased.
  29036. */
  29037. void QCPPolarGrid::setAntialiasedSubGrid(bool enabled)
  29038. {
  29039. mAntialiasedSubGrid = enabled;
  29040. }
  29041. /*!
  29042. Sets whether zero lines are drawn antialiased.
  29043. */
  29044. void QCPPolarGrid::setAntialiasedZeroLine(bool enabled)
  29045. {
  29046. mAntialiasedZeroLine = enabled;
  29047. }
  29048. /*!
  29049. Sets the pen with which (major) grid lines are drawn.
  29050. */
  29051. void QCPPolarGrid::setAngularPen(const QPen &pen)
  29052. {
  29053. mAngularPen = pen;
  29054. }
  29055. /*!
  29056. Sets the pen with which sub grid lines are drawn.
  29057. */
  29058. void QCPPolarGrid::setAngularSubGridPen(const QPen &pen)
  29059. {
  29060. mAngularSubGridPen = pen;
  29061. }
  29062. void QCPPolarGrid::setRadialPen(const QPen &pen)
  29063. {
  29064. mRadialPen = pen;
  29065. }
  29066. void QCPPolarGrid::setRadialSubGridPen(const QPen &pen)
  29067. {
  29068. mRadialSubGridPen = pen;
  29069. }
  29070. void QCPPolarGrid::setRadialZeroLinePen(const QPen &pen)
  29071. {
  29072. mRadialZeroLinePen = pen;
  29073. }
  29074. /*! \internal
  29075. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  29076. before drawing the major grid lines.
  29077. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  29078. This function takes into account the local setting of the antialiasing flag as well as the
  29079. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  29080. QCustomPlot::setNotAntialiasedElements.
  29081. \see setAntialiased
  29082. */
  29083. void QCPPolarGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const
  29084. {
  29085. applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid);
  29086. }
  29087. /*! \internal
  29088. Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning
  29089. over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen).
  29090. */
  29091. void QCPPolarGrid::draw(QCPPainter *painter)
  29092. {
  29093. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  29094. const QPointF center = mParentAxis->mCenter;
  29095. const double radius = mParentAxis->mRadius;
  29096. painter->setBrush(Qt::NoBrush);
  29097. // draw main angular grid:
  29098. if (mType.testFlag(gtAngular))
  29099. drawAngularGrid(painter, center, radius, mParentAxis->mTickVectorCosSin, mAngularPen);
  29100. // draw main radial grid:
  29101. if (mType.testFlag(gtRadial) && mRadialAxis)
  29102. drawRadialGrid(painter, center, mRadialAxis->tickVector(), mRadialPen, mRadialZeroLinePen);
  29103. applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeGrid);
  29104. // draw sub angular grid:
  29105. if (mSubGridType.testFlag(gtAngular))
  29106. drawAngularGrid(painter, center, radius, mParentAxis->mSubTickVectorCosSin, mAngularSubGridPen);
  29107. // draw sub radial grid:
  29108. if (mSubGridType.testFlag(gtRadial) && mRadialAxis)
  29109. drawRadialGrid(painter, center, mRadialAxis->subTickVector(), mRadialSubGridPen);
  29110. }
  29111. void QCPPolarGrid::drawRadialGrid(QCPPainter *painter, const QPointF &center, const QVector<double> &coords, const QPen &pen, const QPen &zeroPen)
  29112. {
  29113. if (!mRadialAxis) return;
  29114. if (coords.isEmpty()) return;
  29115. const bool drawZeroLine = zeroPen != Qt::NoPen;
  29116. const double zeroLineEpsilon = qAbs(coords.last()-coords.first())*1e-6;
  29117. painter->setPen(pen);
  29118. for (int i=0; i<coords.size(); ++i)
  29119. {
  29120. const double r = mRadialAxis->coordToRadius(coords.at(i));
  29121. if (drawZeroLine && qAbs(coords.at(i)) < zeroLineEpsilon)
  29122. {
  29123. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  29124. painter->setPen(zeroPen);
  29125. painter->drawEllipse(center, r, r);
  29126. painter->setPen(pen);
  29127. applyDefaultAntialiasingHint(painter);
  29128. } else
  29129. {
  29130. painter->drawEllipse(center, r, r);
  29131. }
  29132. }
  29133. }
  29134. void QCPPolarGrid::drawAngularGrid(QCPPainter *painter, const QPointF &center, double radius, const QVector<QPointF> &ticksCosSin, const QPen &pen)
  29135. {
  29136. if (ticksCosSin.isEmpty()) return;
  29137. painter->setPen(pen);
  29138. for (int i=0; i<ticksCosSin.size(); ++i)
  29139. painter->drawLine(center, center+ticksCosSin.at(i)*radius);
  29140. }
  29141. /* end of 'src/polar/polargrid.cpp' */
  29142. /* including file 'src/polar/polargraph.cpp' */
  29143. /* modified 2021-03-29T02:30:44, size 44035 */
  29144. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29145. //////////////////// QCPPolarLegendItem
  29146. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29147. /*! \class QCPPolarLegendItem
  29148. \brief A legend item for polar plots
  29149. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  29150. functionality to be incomplete, as well as changing public interfaces in the future.
  29151. */
  29152. QCPPolarLegendItem::QCPPolarLegendItem(QCPLegend *parent, QCPPolarGraph *graph) :
  29153. QCPAbstractLegendItem(parent),
  29154. mPolarGraph(graph)
  29155. {
  29156. setAntialiased(false);
  29157. }
  29158. void QCPPolarLegendItem::draw(QCPPainter *painter)
  29159. {
  29160. if (!mPolarGraph) return;
  29161. painter->setFont(getFont());
  29162. painter->setPen(QPen(getTextColor()));
  29163. QSizeF iconSize = mParentLegend->iconSize();
  29164. QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPolarGraph->name());
  29165. QRectF iconRect(mRect.topLeft(), iconSize);
  29166. int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops
  29167. painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPolarGraph->name());
  29168. // draw icon:
  29169. painter->save();
  29170. painter->setClipRect(iconRect, Qt::IntersectClip);
  29171. mPolarGraph->drawLegendIcon(painter, iconRect);
  29172. painter->restore();
  29173. // draw icon border:
  29174. if (getIconBorderPen().style() != Qt::NoPen)
  29175. {
  29176. painter->setPen(getIconBorderPen());
  29177. painter->setBrush(Qt::NoBrush);
  29178. int halfPen = qCeil(painter->pen().widthF()*0.5)+1;
  29179. painter->setClipRect(mOuterRect.adjusted(-halfPen, -halfPen, halfPen, halfPen)); // extend default clip rect so thicker pens (especially during selection) are not clipped
  29180. painter->drawRect(iconRect);
  29181. }
  29182. }
  29183. QSizeF QCPPolarLegendItem::minimumOuterSizeHint() const
  29184. {
  29185. if (!mPolarGraph) return QSize();
  29186. QSizeF result(0, 0);
  29187. QRectF textRect;
  29188. QFontMetrics fontMetrics(getFont());
  29189. QSizeF iconSize = mParentLegend->iconSize();
  29190. textRect = fontMetrics.boundingRect(0, 0, 0, int(iconSize.height()), Qt::TextDontClip, mPolarGraph->name());
  29191. result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width());
  29192. result.setHeight(qMax(textRect.height(), iconSize.height()));
  29193. result.rwidth() += mMargins.left()+mMargins.right();
  29194. result.rheight() += mMargins.top()+mMargins.bottom();
  29195. return result;
  29196. }
  29197. QPen QCPPolarLegendItem::getIconBorderPen() const
  29198. {
  29199. return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen();
  29200. }
  29201. QColor QCPPolarLegendItem::getTextColor() const
  29202. {
  29203. return mSelected ? mSelectedTextColor : mTextColor;
  29204. }
  29205. QFont QCPPolarLegendItem::getFont() const
  29206. {
  29207. return mSelected ? mSelectedFont : mFont;
  29208. }
  29209. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29210. //////////////////// QCPPolarGraph
  29211. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29212. /*! \class QCPPolarGraph
  29213. \brief A radial graph used to display data in polar plots
  29214. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  29215. functionality to be incomplete, as well as changing public interfaces in the future.
  29216. */
  29217. /* start of documentation of inline functions */
  29218. // TODO
  29219. /* end of documentation of inline functions */
  29220. /*!
  29221. Constructs a graph which uses \a keyAxis as its angular and \a valueAxis as its radial axis. \a
  29222. keyAxis and \a valueAxis must reside in the same QCustomPlot, and the radial axis must be
  29223. associated with the angular axis. If either of these restrictions is violated, a corresponding
  29224. message is printed to the debug output (qDebug), the construction is not aborted, though.
  29225. The created QCPPolarGraph is automatically registered with the QCustomPlot instance inferred from
  29226. \a keyAxis. This QCustomPlot instance takes ownership of the QCPPolarGraph, so do not delete it
  29227. manually but use QCPPolarAxisAngular::removeGraph() instead.
  29228. To directly create a QCPPolarGraph inside a plot, you shoud use the QCPPolarAxisAngular::addGraph
  29229. method.
  29230. */
  29231. QCPPolarGraph::QCPPolarGraph(QCPPolarAxisAngular *keyAxis, QCPPolarAxisRadial *valueAxis) :
  29232. QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis),
  29233. mDataContainer(new QCPGraphDataContainer),
  29234. mName(),
  29235. mAntialiasedFill(true),
  29236. mAntialiasedScatters(true),
  29237. mPen(Qt::black),
  29238. mBrush(Qt::NoBrush),
  29239. mPeriodic(true),
  29240. mKeyAxis(keyAxis),
  29241. mValueAxis(valueAxis),
  29242. mSelectable(QCP::stWhole)
  29243. //mSelectionDecorator(0) // TODO
  29244. {
  29245. if (keyAxis->parentPlot() != valueAxis->parentPlot())
  29246. qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
  29247. mKeyAxis->registerPolarGraph(this);
  29248. //setSelectionDecorator(new QCPSelectionDecorator); // TODO
  29249. setPen(QPen(Qt::blue, 0));
  29250. setBrush(Qt::NoBrush);
  29251. setLineStyle(lsLine);
  29252. }
  29253. QCPPolarGraph::~QCPPolarGraph()
  29254. {
  29255. /* TODO
  29256. if (mSelectionDecorator)
  29257. {
  29258. delete mSelectionDecorator;
  29259. mSelectionDecorator = 0;
  29260. }
  29261. */
  29262. }
  29263. /*!
  29264. The name is the textual representation of this plottable as it is displayed in the legend
  29265. (\ref QCPLegend). It may contain any UTF-8 characters, including newlines.
  29266. */
  29267. void QCPPolarGraph::setName(const QString &name)
  29268. {
  29269. mName = name;
  29270. }
  29271. /*!
  29272. Sets whether fills of this plottable are drawn antialiased or not.
  29273. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  29274. QCustomPlot::setNotAntialiasedElements.
  29275. */
  29276. void QCPPolarGraph::setAntialiasedFill(bool enabled)
  29277. {
  29278. mAntialiasedFill = enabled;
  29279. }
  29280. /*!
  29281. Sets whether the scatter symbols of this plottable are drawn antialiased or not.
  29282. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  29283. QCustomPlot::setNotAntialiasedElements.
  29284. */
  29285. void QCPPolarGraph::setAntialiasedScatters(bool enabled)
  29286. {
  29287. mAntialiasedScatters = enabled;
  29288. }
  29289. /*!
  29290. The pen is used to draw basic lines that make up the plottable representation in the
  29291. plot.
  29292. For example, the \ref QCPGraph subclass draws its graph lines with this pen.
  29293. \see setBrush
  29294. */
  29295. void QCPPolarGraph::setPen(const QPen &pen)
  29296. {
  29297. mPen = pen;
  29298. }
  29299. /*!
  29300. The brush is used to draw basic fills of the plottable representation in the
  29301. plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
  29302. For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when
  29303. it's not set to Qt::NoBrush.
  29304. \see setPen
  29305. */
  29306. void QCPPolarGraph::setBrush(const QBrush &brush)
  29307. {
  29308. mBrush = brush;
  29309. }
  29310. void QCPPolarGraph::setPeriodic(bool enabled)
  29311. {
  29312. mPeriodic = enabled;
  29313. }
  29314. /*!
  29315. The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
  29316. to the plottable's value axis. This function performs no checks to make sure this is the case.
  29317. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
  29318. y-axis (QCustomPlot::yAxis) as value axis.
  29319. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  29320. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  29321. \see setValueAxis
  29322. */
  29323. void QCPPolarGraph::setKeyAxis(QCPPolarAxisAngular *axis)
  29324. {
  29325. mKeyAxis = axis;
  29326. }
  29327. /*!
  29328. The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is
  29329. orthogonal to the plottable's key axis. This function performs no checks to make sure this is the
  29330. case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and
  29331. the y-axis (QCustomPlot::yAxis) as value axis.
  29332. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  29333. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  29334. \see setKeyAxis
  29335. */
  29336. void QCPPolarGraph::setValueAxis(QCPPolarAxisRadial *axis)
  29337. {
  29338. mValueAxis = axis;
  29339. }
  29340. /*!
  29341. Sets whether and to which granularity this plottable can be selected.
  29342. A selection can happen by clicking on the QCustomPlot surface (When \ref
  29343. QCustomPlot::setInteractions contains \ref QCP::iSelectPlottables), by dragging a selection rect
  29344. (When \ref QCustomPlot::setSelectionRectMode is \ref QCP::srmSelect), or programmatically by
  29345. calling \ref setSelection.
  29346. \see setSelection, QCP::SelectionType
  29347. */
  29348. void QCPPolarGraph::setSelectable(QCP::SelectionType selectable)
  29349. {
  29350. if (mSelectable != selectable)
  29351. {
  29352. mSelectable = selectable;
  29353. QCPDataSelection oldSelection = mSelection;
  29354. mSelection.enforceType(mSelectable);
  29355. emit selectableChanged(mSelectable);
  29356. if (mSelection != oldSelection)
  29357. {
  29358. emit selectionChanged(selected());
  29359. emit selectionChanged(mSelection);
  29360. }
  29361. }
  29362. }
  29363. /*!
  29364. Sets which data ranges of this plottable are selected. Selected data ranges are drawn differently
  29365. (e.g. color) in the plot. This can be controlled via the selection decorator (see \ref
  29366. selectionDecorator).
  29367. The entire selection mechanism for plottables is handled automatically when \ref
  29368. QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
  29369. you wish to change the selection state programmatically.
  29370. Using \ref setSelectable you can further specify for each plottable whether and to which
  29371. granularity it is selectable. If \a selection is not compatible with the current \ref
  29372. QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted
  29373. accordingly (see \ref QCPDataSelection::enforceType).
  29374. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  29375. \see setSelectable, selectTest
  29376. */
  29377. void QCPPolarGraph::setSelection(QCPDataSelection selection)
  29378. {
  29379. selection.enforceType(mSelectable);
  29380. if (mSelection != selection)
  29381. {
  29382. mSelection = selection;
  29383. emit selectionChanged(selected());
  29384. emit selectionChanged(mSelection);
  29385. }
  29386. }
  29387. /*! \overload
  29388. Replaces the current data container with the provided \a data container.
  29389. Since a QSharedPointer is used, multiple QCPPolarGraphs may share the same data container safely.
  29390. Modifying the data in the container will then affect all graphs that share the container. Sharing
  29391. can be achieved by simply exchanging the data containers wrapped in shared pointers:
  29392. \snippet documentation/doc-code-snippets/mainwindow.cpp QCPPolarGraph-datasharing-1
  29393. If you do not wish to share containers, but create a copy from an existing container, rather use
  29394. the \ref QCPDataContainer<DataType>::set method on the graph's data container directly:
  29395. \snippet documentation/doc-code-snippets/mainwindow.cpp QCPPolarGraph-datasharing-2
  29396. \see addData
  29397. */
  29398. void QCPPolarGraph::setData(QSharedPointer<QCPGraphDataContainer> data)
  29399. {
  29400. mDataContainer = data;
  29401. }
  29402. /*! \overload
  29403. Replaces the current data with the provided points in \a keys and \a values. The provided
  29404. vectors should have equal length. Else, the number of added points will be the size of the
  29405. smallest vector.
  29406. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  29407. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  29408. \see addData
  29409. */
  29410. void QCPPolarGraph::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  29411. {
  29412. mDataContainer->clear();
  29413. addData(keys, values, alreadySorted);
  29414. }
  29415. /*!
  29416. Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
  29417. \ref lsNone and \ref setScatterStyle to the desired scatter style.
  29418. \see setScatterStyle
  29419. */
  29420. void QCPPolarGraph::setLineStyle(LineStyle ls)
  29421. {
  29422. mLineStyle = ls;
  29423. }
  29424. /*!
  29425. Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points
  29426. are drawn (e.g. for line-only-plots with appropriate line style).
  29427. \see QCPScatterStyle, setLineStyle
  29428. */
  29429. void QCPPolarGraph::setScatterStyle(const QCPScatterStyle &style)
  29430. {
  29431. mScatterStyle = style;
  29432. }
  29433. void QCPPolarGraph::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  29434. {
  29435. if (keys.size() != values.size())
  29436. qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
  29437. const int n = qMin(keys.size(), values.size());
  29438. QVector<QCPGraphData> tempData(n);
  29439. QVector<QCPGraphData>::iterator it = tempData.begin();
  29440. const QVector<QCPGraphData>::iterator itEnd = tempData.end();
  29441. int i = 0;
  29442. while (it != itEnd)
  29443. {
  29444. it->key = keys[i];
  29445. it->value = values[i];
  29446. ++it;
  29447. ++i;
  29448. }
  29449. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  29450. }
  29451. void QCPPolarGraph::addData(double key, double value)
  29452. {
  29453. mDataContainer->add(QCPGraphData(key, value));
  29454. }
  29455. /*!
  29456. Use this method to set an own QCPSelectionDecorator (subclass) instance. This allows you to
  29457. customize the visual representation of selected data ranges further than by using the default
  29458. QCPSelectionDecorator.
  29459. The plottable takes ownership of the \a decorator.
  29460. The currently set decorator can be accessed via \ref selectionDecorator.
  29461. */
  29462. /*
  29463. void QCPPolarGraph::setSelectionDecorator(QCPSelectionDecorator *decorator)
  29464. {
  29465. if (decorator)
  29466. {
  29467. if (decorator->registerWithPlottable(this))
  29468. {
  29469. if (mSelectionDecorator) // delete old decorator if necessary
  29470. delete mSelectionDecorator;
  29471. mSelectionDecorator = decorator;
  29472. }
  29473. } else if (mSelectionDecorator) // just clear decorator
  29474. {
  29475. delete mSelectionDecorator;
  29476. mSelectionDecorator = 0;
  29477. }
  29478. }
  29479. */
  29480. void QCPPolarGraph::coordsToPixels(double key, double value, double &x, double &y) const
  29481. {
  29482. if (mValueAxis)
  29483. {
  29484. const QPointF point = mValueAxis->coordToPixel(key, value);
  29485. x = point.x();
  29486. y = point.y();
  29487. } else
  29488. {
  29489. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  29490. }
  29491. }
  29492. const QPointF QCPPolarGraph::coordsToPixels(double key, double value) const
  29493. {
  29494. if (mValueAxis)
  29495. {
  29496. return mValueAxis->coordToPixel(key, value);
  29497. } else
  29498. {
  29499. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  29500. return QPointF();
  29501. }
  29502. }
  29503. void QCPPolarGraph::pixelsToCoords(double x, double y, double &key, double &value) const
  29504. {
  29505. if (mValueAxis)
  29506. {
  29507. mValueAxis->pixelToCoord(QPointF(x, y), key, value);
  29508. } else
  29509. {
  29510. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  29511. }
  29512. }
  29513. void QCPPolarGraph::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
  29514. {
  29515. if (mValueAxis)
  29516. {
  29517. mValueAxis->pixelToCoord(pixelPos, key, value);
  29518. } else
  29519. {
  29520. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  29521. }
  29522. }
  29523. void QCPPolarGraph::rescaleAxes(bool onlyEnlarge) const
  29524. {
  29525. rescaleKeyAxis(onlyEnlarge);
  29526. rescaleValueAxis(onlyEnlarge);
  29527. }
  29528. void QCPPolarGraph::rescaleKeyAxis(bool onlyEnlarge) const
  29529. {
  29530. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  29531. if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
  29532. bool foundRange;
  29533. QCPRange newRange = getKeyRange(foundRange, QCP::sdBoth);
  29534. if (foundRange)
  29535. {
  29536. if (onlyEnlarge)
  29537. newRange.expand(keyAxis->range());
  29538. 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
  29539. {
  29540. 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
  29541. newRange.lower = center-keyAxis->range().size()/2.0;
  29542. newRange.upper = center+keyAxis->range().size()/2.0;
  29543. }
  29544. keyAxis->setRange(newRange);
  29545. }
  29546. }
  29547. void QCPPolarGraph::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const
  29548. {
  29549. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  29550. QCPPolarAxisRadial *valueAxis = mValueAxis.data();
  29551. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  29552. QCP::SignDomain signDomain = QCP::sdBoth;
  29553. if (valueAxis->scaleType() == QCPPolarAxisRadial::stLogarithmic)
  29554. signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  29555. bool foundRange;
  29556. QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange());
  29557. if (foundRange)
  29558. {
  29559. if (onlyEnlarge)
  29560. newRange.expand(valueAxis->range());
  29561. 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
  29562. {
  29563. 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
  29564. if (valueAxis->scaleType() == QCPPolarAxisRadial::stLinear)
  29565. {
  29566. newRange.lower = center-valueAxis->range().size()/2.0;
  29567. newRange.upper = center+valueAxis->range().size()/2.0;
  29568. } else // scaleType() == stLogarithmic
  29569. {
  29570. newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  29571. newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  29572. }
  29573. }
  29574. valueAxis->setRange(newRange);
  29575. }
  29576. }
  29577. bool QCPPolarGraph::addToLegend(QCPLegend *legend)
  29578. {
  29579. if (!legend)
  29580. {
  29581. qDebug() << Q_FUNC_INFO << "passed legend is null";
  29582. return false;
  29583. }
  29584. if (legend->parentPlot() != mParentPlot)
  29585. {
  29586. qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable";
  29587. return false;
  29588. }
  29589. //if (!legend->hasItemWithPlottable(this)) // TODO
  29590. //{
  29591. legend->addItem(new QCPPolarLegendItem(legend, this));
  29592. return true;
  29593. //} else
  29594. // return false;
  29595. }
  29596. bool QCPPolarGraph::addToLegend()
  29597. {
  29598. if (!mParentPlot || !mParentPlot->legend)
  29599. return false;
  29600. else
  29601. return addToLegend(mParentPlot->legend);
  29602. }
  29603. bool QCPPolarGraph::removeFromLegend(QCPLegend *legend) const
  29604. {
  29605. if (!legend)
  29606. {
  29607. qDebug() << Q_FUNC_INFO << "passed legend is null";
  29608. return false;
  29609. }
  29610. QCPPolarLegendItem *removableItem = nullptr;
  29611. for (int i=0; i<legend->itemCount(); ++i) // TODO: reduce this to code in QCPAbstractPlottable::removeFromLegend once unified
  29612. {
  29613. if (QCPPolarLegendItem *pli = qobject_cast<QCPPolarLegendItem*>(legend->item(i)))
  29614. {
  29615. if (pli->polarGraph() == this)
  29616. {
  29617. removableItem = pli;
  29618. break;
  29619. }
  29620. }
  29621. }
  29622. if (removableItem)
  29623. return legend->removeItem(removableItem);
  29624. else
  29625. return false;
  29626. }
  29627. bool QCPPolarGraph::removeFromLegend() const
  29628. {
  29629. if (!mParentPlot || !mParentPlot->legend)
  29630. return false;
  29631. else
  29632. return removeFromLegend(mParentPlot->legend);
  29633. }
  29634. double QCPPolarGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  29635. {
  29636. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  29637. return -1;
  29638. if (!mKeyAxis || !mValueAxis)
  29639. return -1;
  29640. if (mKeyAxis->rect().contains(pos.toPoint()))
  29641. {
  29642. QCPGraphDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  29643. double result = pointDistance(pos, closestDataPoint);
  29644. if (details)
  29645. {
  29646. int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
  29647. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  29648. }
  29649. return result;
  29650. } else
  29651. return -1;
  29652. }
  29653. /* inherits documentation from base class */
  29654. QCPRange QCPPolarGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  29655. {
  29656. return mDataContainer->keyRange(foundRange, inSignDomain);
  29657. }
  29658. /* inherits documentation from base class */
  29659. QCPRange QCPPolarGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  29660. {
  29661. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  29662. }
  29663. /* inherits documentation from base class */
  29664. QRectF QCPPolarGraph::clipRect() const
  29665. {
  29666. if (mKeyAxis)
  29667. return mKeyAxis.data()->rect();
  29668. else
  29669. return {};
  29670. }
  29671. void QCPPolarGraph::draw(QCPPainter *painter)
  29672. {
  29673. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  29674. if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
  29675. if (mLineStyle == lsNone && mScatterStyle.isNone()) return;
  29676. painter->setClipRegion(mKeyAxis->exactClipRegion());
  29677. QVector<QPointF> lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments
  29678. // loop over and draw segments of unselected/selected data:
  29679. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  29680. getDataSegments(selectedSegments, unselectedSegments);
  29681. allSegments << unselectedSegments << selectedSegments;
  29682. for (int i=0; i<allSegments.size(); ++i)
  29683. {
  29684. bool isSelectedSegment = i >= unselectedSegments.size();
  29685. // get line pixel points appropriate to line style:
  29686. 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)
  29687. getLines(&lines, lineDataRange);
  29688. // check data validity if flag set:
  29689. #ifdef QCUSTOMPLOT_CHECK_DATA
  29690. QCPGraphDataContainer::const_iterator it;
  29691. for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  29692. {
  29693. if (QCP::isInvalidData(it->key, it->value))
  29694. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
  29695. }
  29696. #endif
  29697. // draw fill of graph:
  29698. //if (isSelectedSegment && mSelectionDecorator)
  29699. // mSelectionDecorator->applyBrush(painter);
  29700. //else
  29701. painter->setBrush(mBrush);
  29702. painter->setPen(Qt::NoPen);
  29703. drawFill(painter, &lines);
  29704. // draw line:
  29705. if (mLineStyle != lsNone)
  29706. {
  29707. //if (isSelectedSegment && mSelectionDecorator)
  29708. // mSelectionDecorator->applyPen(painter);
  29709. //else
  29710. painter->setPen(mPen);
  29711. painter->setBrush(Qt::NoBrush);
  29712. drawLinePlot(painter, lines);
  29713. }
  29714. // draw scatters:
  29715. QCPScatterStyle finalScatterStyle = mScatterStyle;
  29716. //if (isSelectedSegment && mSelectionDecorator)
  29717. // finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
  29718. if (!finalScatterStyle.isNone())
  29719. {
  29720. getScatters(&scatters, allSegments.at(i));
  29721. drawScatterPlot(painter, scatters, finalScatterStyle);
  29722. }
  29723. }
  29724. // draw other selection decoration that isn't just line/scatter pens and brushes:
  29725. //if (mSelectionDecorator)
  29726. // mSelectionDecorator->drawDecoration(painter, selection());
  29727. }
  29728. QCP::Interaction QCPPolarGraph::selectionCategory() const
  29729. {
  29730. return QCP::iSelectPlottables;
  29731. }
  29732. void QCPPolarGraph::applyDefaultAntialiasingHint(QCPPainter *painter) const
  29733. {
  29734. applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables);
  29735. }
  29736. /* inherits documentation from base class */
  29737. void QCPPolarGraph::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  29738. {
  29739. Q_UNUSED(event)
  29740. if (mSelectable != QCP::stNone)
  29741. {
  29742. QCPDataSelection newSelection = details.value<QCPDataSelection>();
  29743. QCPDataSelection selectionBefore = mSelection;
  29744. if (additive)
  29745. {
  29746. if (mSelectable == QCP::stWhole) // in whole selection mode, we toggle to no selection even if currently unselected point was hit
  29747. {
  29748. if (selected())
  29749. setSelection(QCPDataSelection());
  29750. else
  29751. setSelection(newSelection);
  29752. } else // in all other selection modes we toggle selections of homogeneously selected/unselected segments
  29753. {
  29754. if (mSelection.contains(newSelection)) // if entire newSelection is already selected, toggle selection
  29755. setSelection(mSelection-newSelection);
  29756. else
  29757. setSelection(mSelection+newSelection);
  29758. }
  29759. } else
  29760. setSelection(newSelection);
  29761. if (selectionStateChanged)
  29762. *selectionStateChanged = mSelection != selectionBefore;
  29763. }
  29764. }
  29765. /* inherits documentation from base class */
  29766. void QCPPolarGraph::deselectEvent(bool *selectionStateChanged)
  29767. {
  29768. if (mSelectable != QCP::stNone)
  29769. {
  29770. QCPDataSelection selectionBefore = mSelection;
  29771. setSelection(QCPDataSelection());
  29772. if (selectionStateChanged)
  29773. *selectionStateChanged = mSelection != selectionBefore;
  29774. }
  29775. }
  29776. /*! \internal
  29777. Draws lines between the points in \a lines, given in pixel coordinates.
  29778. \see drawScatterPlot, drawImpulsePlot, QCPAbstractPlottable1D::drawPolyline
  29779. */
  29780. void QCPPolarGraph::drawLinePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
  29781. {
  29782. if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
  29783. {
  29784. applyDefaultAntialiasingHint(painter);
  29785. drawPolyline(painter, lines);
  29786. }
  29787. }
  29788. /*! \internal
  29789. Draws the fill of the graph using the specified \a painter, with the currently set brush.
  29790. Depending on whether a normal fill or a channel fill (\ref setChannelFillGraph) is needed, \ref
  29791. getFillPolygon or \ref getChannelFillPolygon are used to find the according fill polygons.
  29792. In order to handle NaN Data points correctly (the fill needs to be split into disjoint areas),
  29793. this method first determines a list of non-NaN segments with \ref getNonNanSegments, on which to
  29794. operate. In the channel fill case, \ref getOverlappingSegments is used to consolidate the non-NaN
  29795. segments of the two involved graphs, before passing the overlapping pairs to \ref
  29796. getChannelFillPolygon.
  29797. Pass the points of this graph's line as \a lines, in pixel coordinates.
  29798. \see drawLinePlot, drawImpulsePlot, drawScatterPlot
  29799. */
  29800. void QCPPolarGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lines) const
  29801. {
  29802. applyFillAntialiasingHint(painter);
  29803. if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0)
  29804. painter->drawPolygon(QPolygonF(*lines));
  29805. }
  29806. /*! \internal
  29807. Draws scatter symbols at every point passed in \a scatters, given in pixel coordinates. The
  29808. scatters will be drawn with \a painter and have the appearance as specified in \a style.
  29809. \see drawLinePlot, drawImpulsePlot
  29810. */
  29811. void QCPPolarGraph::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &scatters, const QCPScatterStyle &style) const
  29812. {
  29813. applyScattersAntialiasingHint(painter);
  29814. style.applyTo(painter, mPen);
  29815. for (int i=0; i<scatters.size(); ++i)
  29816. style.drawShape(painter, scatters.at(i).x(), scatters.at(i).y());
  29817. }
  29818. void QCPPolarGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  29819. {
  29820. // draw fill:
  29821. if (mBrush.style() != Qt::NoBrush)
  29822. {
  29823. applyFillAntialiasingHint(painter);
  29824. painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
  29825. }
  29826. // draw line vertically centered:
  29827. if (mLineStyle != lsNone)
  29828. {
  29829. applyDefaultAntialiasingHint(painter);
  29830. painter->setPen(mPen);
  29831. 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
  29832. }
  29833. // draw scatter symbol:
  29834. if (!mScatterStyle.isNone())
  29835. {
  29836. applyScattersAntialiasingHint(painter);
  29837. // scale scatter pixmap if it's too large to fit in legend icon rect:
  29838. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
  29839. {
  29840. QCPScatterStyle scaledStyle(mScatterStyle);
  29841. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  29842. scaledStyle.applyTo(painter, mPen);
  29843. scaledStyle.drawShape(painter, QRectF(rect).center());
  29844. } else
  29845. {
  29846. mScatterStyle.applyTo(painter, mPen);
  29847. mScatterStyle.drawShape(painter, QRectF(rect).center());
  29848. }
  29849. }
  29850. }
  29851. void QCPPolarGraph::applyFillAntialiasingHint(QCPPainter *painter) const
  29852. {
  29853. applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills);
  29854. }
  29855. void QCPPolarGraph::applyScattersAntialiasingHint(QCPPainter *painter) const
  29856. {
  29857. applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
  29858. }
  29859. double QCPPolarGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const
  29860. {
  29861. closestData = mDataContainer->constEnd();
  29862. if (mDataContainer->isEmpty())
  29863. return -1.0;
  29864. if (mLineStyle == lsNone && mScatterStyle.isNone())
  29865. return -1.0;
  29866. // calculate minimum distances to graph data points and find closestData iterator:
  29867. double minDistSqr = (std::numeric_limits<double>::max)();
  29868. // determine which key range comes into question, taking selection tolerance around pos into account:
  29869. double posKeyMin, posKeyMax, dummy;
  29870. pixelsToCoords(pixelPoint-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy);
  29871. pixelsToCoords(pixelPoint+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy);
  29872. if (posKeyMin > posKeyMax)
  29873. qSwap(posKeyMin, posKeyMax);
  29874. // iterate over found data points and then choose the one with the shortest distance to pos:
  29875. QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true);
  29876. QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true);
  29877. for (QCPGraphDataContainer::const_iterator it=begin; it!=end; ++it)
  29878. {
  29879. const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
  29880. if (currentDistSqr < minDistSqr)
  29881. {
  29882. minDistSqr = currentDistSqr;
  29883. closestData = it;
  29884. }
  29885. }
  29886. // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point):
  29887. if (mLineStyle != lsNone)
  29888. {
  29889. // line displayed, calculate distance to line segments:
  29890. QVector<QPointF> lineData;
  29891. getLines(&lineData, QCPDataRange(0, dataCount()));
  29892. QCPVector2D p(pixelPoint);
  29893. for (int i=0; i<lineData.size()-1; ++i)
  29894. {
  29895. const double currentDistSqr = p.distanceSquaredToLine(lineData.at(i), lineData.at(i+1));
  29896. if (currentDistSqr < minDistSqr)
  29897. minDistSqr = currentDistSqr;
  29898. }
  29899. }
  29900. return qSqrt(minDistSqr);
  29901. }
  29902. int QCPPolarGraph::dataCount() const
  29903. {
  29904. return mDataContainer->size();
  29905. }
  29906. void QCPPolarGraph::getDataSegments(QList<QCPDataRange> &selectedSegments, QList<QCPDataRange> &unselectedSegments) const
  29907. {
  29908. selectedSegments.clear();
  29909. unselectedSegments.clear();
  29910. if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty
  29911. {
  29912. if (selected())
  29913. selectedSegments << QCPDataRange(0, dataCount());
  29914. else
  29915. unselectedSegments << QCPDataRange(0, dataCount());
  29916. } else
  29917. {
  29918. QCPDataSelection sel(selection());
  29919. sel.simplify();
  29920. selectedSegments = sel.dataRanges();
  29921. unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges();
  29922. }
  29923. }
  29924. void QCPPolarGraph::drawPolyline(QCPPainter *painter, const QVector<QPointF> &lineData) const
  29925. {
  29926. // if drawing solid line and not in PDF, use much faster line drawing instead of polyline:
  29927. if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) &&
  29928. painter->pen().style() == Qt::SolidLine &&
  29929. !painter->modes().testFlag(QCPPainter::pmVectorized) &&
  29930. !painter->modes().testFlag(QCPPainter::pmNoCaching))
  29931. {
  29932. int i = 0;
  29933. bool lastIsNan = false;
  29934. const int lineDataSize = lineData.size();
  29935. while (i < lineDataSize && (qIsNaN(lineData.at(i).y()) || qIsNaN(lineData.at(i).x()))) // make sure first point is not NaN
  29936. ++i;
  29937. ++i; // because drawing works in 1 point retrospect
  29938. while (i < lineDataSize)
  29939. {
  29940. if (!qIsNaN(lineData.at(i).y()) && !qIsNaN(lineData.at(i).x())) // NaNs create a gap in the line
  29941. {
  29942. if (!lastIsNan)
  29943. painter->drawLine(lineData.at(i-1), lineData.at(i));
  29944. else
  29945. lastIsNan = false;
  29946. } else
  29947. lastIsNan = true;
  29948. ++i;
  29949. }
  29950. } else
  29951. {
  29952. int segmentStart = 0;
  29953. int i = 0;
  29954. const int lineDataSize = lineData.size();
  29955. while (i < lineDataSize)
  29956. {
  29957. 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
  29958. {
  29959. painter->drawPolyline(lineData.constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point
  29960. segmentStart = i+1;
  29961. }
  29962. ++i;
  29963. }
  29964. // draw last segment:
  29965. painter->drawPolyline(lineData.constData()+segmentStart, lineDataSize-segmentStart);
  29966. }
  29967. }
  29968. void QCPPolarGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
  29969. {
  29970. if (rangeRestriction.isEmpty())
  29971. {
  29972. end = mDataContainer->constEnd();
  29973. begin = end;
  29974. } else
  29975. {
  29976. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  29977. QCPPolarAxisRadial *valueAxis = mValueAxis.data();
  29978. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  29979. // get visible data range:
  29980. if (mPeriodic)
  29981. {
  29982. begin = mDataContainer->constBegin();
  29983. end = mDataContainer->constEnd();
  29984. } else
  29985. {
  29986. begin = mDataContainer->findBegin(keyAxis->range().lower);
  29987. end = mDataContainer->findEnd(keyAxis->range().upper);
  29988. }
  29989. // limit lower/upperEnd to rangeRestriction:
  29990. mDataContainer->limitIteratorsToDataRange(begin, end, rangeRestriction); // this also ensures rangeRestriction outside data bounds doesn't break anything
  29991. }
  29992. }
  29993. /*! \internal
  29994. This method retrieves an optimized set of data points via \ref getOptimizedLineData, an branches
  29995. out to the line style specific functions such as \ref dataToLines, \ref dataToStepLeftLines, etc.
  29996. according to the line style of the graph.
  29997. \a lines will be filled with points in pixel coordinates, that can be drawn with the according
  29998. draw functions like \ref drawLinePlot and \ref drawImpulsePlot. The points returned in \a lines
  29999. aren't necessarily the original data points. For example, step line styles require additional
  30000. points to form the steps when drawn. If the line style of the graph is \ref lsNone, the \a
  30001. lines vector will be empty.
  30002. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  30003. conversion. In this function, the specified range may exceed the total data bounds without harm:
  30004. a correspondingly trimmed data range will be used. This takes the burden off the user of this
  30005. function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
  30006. getDataSegments.
  30007. \see getScatters
  30008. */
  30009. void QCPPolarGraph::getLines(QVector<QPointF> *lines, const QCPDataRange &dataRange) const
  30010. {
  30011. if (!lines) return;
  30012. QCPGraphDataContainer::const_iterator begin, end;
  30013. getVisibleDataBounds(begin, end, dataRange);
  30014. if (begin == end)
  30015. {
  30016. lines->clear();
  30017. return;
  30018. }
  30019. QVector<QCPGraphData> lineData;
  30020. if (mLineStyle != lsNone)
  30021. getOptimizedLineData(&lineData, begin, end);
  30022. switch (mLineStyle)
  30023. {
  30024. case lsNone: lines->clear(); break;
  30025. case lsLine: *lines = dataToLines(lineData); break;
  30026. }
  30027. }
  30028. void QCPPolarGraph::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange) const
  30029. {
  30030. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  30031. QCPPolarAxisRadial *valueAxis = mValueAxis.data();
  30032. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  30033. if (!scatters) return;
  30034. QCPGraphDataContainer::const_iterator begin, end;
  30035. getVisibleDataBounds(begin, end, dataRange);
  30036. if (begin == end)
  30037. {
  30038. scatters->clear();
  30039. return;
  30040. }
  30041. QVector<QCPGraphData> data;
  30042. getOptimizedScatterData(&data, begin, end);
  30043. scatters->resize(data.size());
  30044. for (int i=0; i<data.size(); ++i)
  30045. {
  30046. if (!qIsNaN(data.at(i).value))
  30047. (*scatters)[i] = valueAxis->coordToPixel(data.at(i).key, data.at(i).value);
  30048. }
  30049. }
  30050. void QCPPolarGraph::getOptimizedLineData(QVector<QCPGraphData> *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const
  30051. {
  30052. lineData->clear();
  30053. // TODO: fix for log axes and thick line style
  30054. const QCPRange range = mValueAxis->range();
  30055. bool reversed = mValueAxis->rangeReversed();
  30056. 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
  30057. 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
  30058. 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
  30059. 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)
  30060. double skipBegin = 0;
  30061. bool belowRange = false;
  30062. bool aboveRange = false;
  30063. QCPGraphDataContainer::const_iterator it = begin;
  30064. while (it != end)
  30065. {
  30066. if (it->value < lowerClipValue)
  30067. {
  30068. if (aboveRange) // jumped directly from above to below visible range, draw previous point so entry angle is correct
  30069. {
  30070. aboveRange = false;
  30071. if (!reversed) // TODO: with inner radius, we'll need else case here with projected border point
  30072. lineData->append(*(it-1));
  30073. }
  30074. if (!belowRange)
  30075. {
  30076. skipBegin = it->key;
  30077. lineData->append(QCPGraphData(it->key, lowerClipValue));
  30078. belowRange = true;
  30079. }
  30080. if (it->key-skipBegin > maxKeySkip) // add dummy point if we're exceeding the maximum skippable angle (to prevent unintentional intersections with visible circle)
  30081. {
  30082. skipBegin += maxKeySkip;
  30083. lineData->append(QCPGraphData(skipBegin, lowerClipValue));
  30084. }
  30085. } else if (it->value > upperClipValue)
  30086. {
  30087. 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)
  30088. {
  30089. belowRange = false;
  30090. if (reversed)
  30091. lineData->append(*(it-1));
  30092. }
  30093. if (!aboveRange)
  30094. {
  30095. skipBegin = it->key;
  30096. lineData->append(QCPGraphData(it->key, upperClipValue));
  30097. aboveRange = true;
  30098. }
  30099. if (it->key-skipBegin > maxKeySkip) // add dummy point if we're exceeding the maximum skippable angle (to prevent unintentional intersections with visible circle)
  30100. {
  30101. skipBegin += maxKeySkip;
  30102. lineData->append(QCPGraphData(skipBegin, upperClipValue));
  30103. }
  30104. } else // value within bounds where we don't optimize away points
  30105. {
  30106. if (aboveRange)
  30107. {
  30108. aboveRange = false;
  30109. if (!reversed)
  30110. 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)
  30111. }
  30112. if (belowRange)
  30113. {
  30114. belowRange = false;
  30115. if (reversed)
  30116. lineData->append(*(it-1)); // just entered from below, draw previous point so entry angle is correct (if below means outer, so if reversed axis)
  30117. }
  30118. lineData->append(*it); // inside visible circle, add point normally
  30119. }
  30120. ++it;
  30121. }
  30122. // to make fill not erratic, add last point normally if it was outside visible circle:
  30123. if (aboveRange)
  30124. {
  30125. aboveRange = false;
  30126. if (!reversed)
  30127. 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)
  30128. }
  30129. if (belowRange)
  30130. {
  30131. belowRange = false;
  30132. if (reversed)
  30133. lineData->append(*(it-1)); // just entered from below, draw previous point so entry angle is correct (if below means outer, so if reversed axis)
  30134. }
  30135. }
  30136. void QCPPolarGraph::getOptimizedScatterData(QVector<QCPGraphData> *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const
  30137. {
  30138. scatterData->clear();
  30139. const QCPRange range = mValueAxis->range();
  30140. bool reversed = mValueAxis->rangeReversed();
  30141. const double clipMargin = range.size()*0.05;
  30142. const double upperClipValue = range.upper + (reversed ? 0 : clipMargin); // clip slightly outside of actual range to avoid scatter size to peek into visible circle
  30143. const double lowerClipValue = range.lower - (reversed ? clipMargin : 0); // clip slightly outside of actual range to avoid scatter size to peek into visible circle
  30144. QCPGraphDataContainer::const_iterator it = begin;
  30145. while (it != end)
  30146. {
  30147. if (it->value > lowerClipValue && it->value < upperClipValue)
  30148. scatterData->append(*it);
  30149. ++it;
  30150. }
  30151. }
  30152. /*! \internal
  30153. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  30154. coordinate points which are suitable for drawing the line style \ref lsLine.
  30155. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  30156. getLines if the line style is set accordingly.
  30157. \see dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
  30158. */
  30159. QVector<QPointF> QCPPolarGraph::dataToLines(const QVector<QCPGraphData> &data) const
  30160. {
  30161. QVector<QPointF> result;
  30162. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  30163. QCPPolarAxisRadial *valueAxis = mValueAxis.data();
  30164. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  30165. // transform data points to pixels:
  30166. result.resize(data.size());
  30167. for (int i=0; i<data.size(); ++i)
  30168. result[i] = mValueAxis->coordToPixel(data.at(i).key, data.at(i).value);
  30169. return result;
  30170. }
  30171. /* end of 'src/polar/polargraph.cpp' */