qcustomplot.cpp 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121
  1. /***************************************************************************
  2. ** **
  3. ** QCustomPlot, an easy to use, modern plotting widget for Qt **
  4. ** Copyright (C) 2011-2017 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: 04.09.17 **
  23. ** Version: 2.0.0 **
  24. ****************************************************************************/
  25. #include "qcustomplot.h"
  26. /* including file 'src/vector2d.cpp', size 7340 */
  27. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  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 QPoint QCPVector2D::toPoint() const
  56. Returns a QPoint which has the x and y coordinates of this vector, truncating any floating point
  57. information.
  58. \see toPointF
  59. */
  60. /*! \fn QPointF QCPVector2D::toPointF() const
  61. Returns a QPointF which has the x and y coordinates of this vector.
  62. \see toPoint
  63. */
  64. /*! \fn bool QCPVector2D::isNull() const
  65. Returns whether this vector is null. A vector is null if \c qIsNull returns true for both x and y
  66. coordinates, i.e. if both are binary equal to 0.
  67. */
  68. /*! \fn QCPVector2D QCPVector2D::perpendicular() const
  69. Returns a vector perpendicular to this vector, with the same length.
  70. */
  71. /*! \fn double QCPVector2D::dot() const
  72. Returns the dot/scalar product of this vector with the specified vector \a vec.
  73. */
  74. /* end documentation of inline functions */
  75. /*!
  76. Creates a QCPVector2D object and initializes the x and y coordinates to 0.
  77. */
  78. QCPVector2D::QCPVector2D() :
  79. mX(0),
  80. mY(0)
  81. {
  82. }
  83. /*!
  84. Creates a QCPVector2D object and initializes the \a x and \a y coordinates with the specified
  85. values.
  86. */
  87. QCPVector2D::QCPVector2D(double x, double y) :
  88. mX(x),
  89. mY(y)
  90. {
  91. }
  92. /*!
  93. Creates a QCPVector2D object and initializes the x and y coordinates respective coordinates of
  94. the specified \a point.
  95. */
  96. QCPVector2D::QCPVector2D(const QPoint &point) :
  97. mX(point.x()),
  98. mY(point.y())
  99. {
  100. }
  101. /*!
  102. Creates a QCPVector2D object and initializes the x and y coordinates respective coordinates of
  103. the specified \a point.
  104. */
  105. QCPVector2D::QCPVector2D(const QPointF &point) :
  106. mX(point.x()),
  107. mY(point.y())
  108. {
  109. }
  110. /*!
  111. Normalizes this vector. After this operation, the length of the vector is equal to 1.
  112. \see normalized, length, lengthSquared
  113. */
  114. void QCPVector2D::normalize()
  115. {
  116. double len = length();
  117. mX /= len;
  118. mY /= len;
  119. }
  120. /*!
  121. Returns a normalized version of this vector. The length of the returned vector is equal to 1.
  122. \see normalize, length, lengthSquared
  123. */
  124. QCPVector2D QCPVector2D::normalized() const
  125. {
  126. QCPVector2D result(mX, mY);
  127. result.normalize();
  128. return result;
  129. }
  130. /*! \overload
  131. Returns the squared shortest distance of this vector (interpreted as a point) to the finite line
  132. segment given by \a start and \a end.
  133. \see distanceToStraightLine
  134. */
  135. double QCPVector2D::distanceSquaredToLine(const QCPVector2D &start, const QCPVector2D &end) const
  136. {
  137. QCPVector2D v(end-start);
  138. double vLengthSqr = v.lengthSquared();
  139. if (!qFuzzyIsNull(vLengthSqr))
  140. {
  141. double mu = v.dot(*this-start)/vLengthSqr;
  142. if (mu < 0)
  143. return (*this-start).lengthSquared();
  144. else if (mu > 1)
  145. return (*this-end).lengthSquared();
  146. else
  147. return ((start + mu*v)-*this).lengthSquared();
  148. } else
  149. return (*this-start).lengthSquared();
  150. }
  151. /*! \overload
  152. Returns the squared shortest distance of this vector (interpreted as a point) to the finite line
  153. segment given by \a line.
  154. \see distanceToStraightLine
  155. */
  156. double QCPVector2D::distanceSquaredToLine(const QLineF &line) const
  157. {
  158. return distanceSquaredToLine(QCPVector2D(line.p1()), QCPVector2D(line.p2()));
  159. }
  160. /*!
  161. Returns the shortest distance of this vector (interpreted as a point) to the infinite straight
  162. line given by a \a base point and a \a direction vector.
  163. \see distanceSquaredToLine
  164. */
  165. double QCPVector2D::distanceToStraightLine(const QCPVector2D &base, const QCPVector2D &direction) const
  166. {
  167. return qAbs((*this-base).dot(direction.perpendicular()))/direction.length();
  168. }
  169. /*!
  170. Scales this vector by the given \a factor, i.e. the x and y components are multiplied by \a
  171. factor.
  172. */
  173. QCPVector2D &QCPVector2D::operator*=(double factor)
  174. {
  175. mX *= factor;
  176. mY *= factor;
  177. return *this;
  178. }
  179. /*!
  180. Scales this vector by the given \a divisor, i.e. the x and y components are divided by \a
  181. divisor.
  182. */
  183. QCPVector2D &QCPVector2D::operator/=(double divisor)
  184. {
  185. mX /= divisor;
  186. mY /= divisor;
  187. return *this;
  188. }
  189. /*!
  190. Adds the given \a vector to this vector component-wise.
  191. */
  192. QCPVector2D &QCPVector2D::operator+=(const QCPVector2D &vector)
  193. {
  194. mX += vector.mX;
  195. mY += vector.mY;
  196. return *this;
  197. }
  198. /*!
  199. subtracts the given \a vector from this vector component-wise.
  200. */
  201. QCPVector2D &QCPVector2D::operator-=(const QCPVector2D &vector)
  202. {
  203. mX -= vector.mX;
  204. mY -= vector.mY;
  205. return *this;
  206. }
  207. /* end of 'src/vector2d.cpp' */
  208. /* including file 'src/painter.cpp', size 8670 */
  209. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  210. ////////////////////////////////////////////////////////////////////////////////////////////////////
  211. //////////////////// QCPPainter
  212. ////////////////////////////////////////////////////////////////////////////////////////////////////
  213. /*! \class QCPPainter
  214. \brief QPainter subclass used internally
  215. This QPainter subclass is used to provide some extended functionality e.g. for tweaking position
  216. consistency between antialiased and non-antialiased painting. Further it provides workarounds
  217. for QPainter quirks.
  218. \warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and
  219. restore. So while it is possible to pass a QCPPainter instance to a function that expects a
  220. QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because
  221. it will call the base class implementations of the functions actually hidden by QCPPainter).
  222. */
  223. /*!
  224. Creates a new QCPPainter instance and sets default values
  225. */
  226. QCPPainter::QCPPainter() :
  227. QPainter(),
  228. mModes(pmDefault),
  229. mIsAntialiasing(false)
  230. {
  231. // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and
  232. // a call to begin() will follow
  233. }
  234. /*!
  235. Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just
  236. like the analogous QPainter constructor, begins painting on \a device immediately.
  237. Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5.
  238. */
  239. QCPPainter::QCPPainter(QPaintDevice *device) :
  240. QPainter(device),
  241. mModes(pmDefault),
  242. mIsAntialiasing(false)
  243. {
  244. #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.
  245. if (isActive())
  246. setRenderHint(QPainter::NonCosmeticDefaultPen);
  247. #endif
  248. }
  249. /*!
  250. Sets the pen of the painter and applies certain fixes to it, depending on the mode of this
  251. QCPPainter.
  252. \note this function hides the non-virtual base class implementation.
  253. */
  254. void QCPPainter::setPen(const QPen &pen)
  255. {
  256. QPainter::setPen(pen);
  257. if (mModes.testFlag(pmNonCosmetic))
  258. makeNonCosmetic();
  259. }
  260. /*! \overload
  261. Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of
  262. this QCPPainter.
  263. \note this function hides the non-virtual base class implementation.
  264. */
  265. void QCPPainter::setPen(const QColor &color)
  266. {
  267. QPainter::setPen(color);
  268. if (mModes.testFlag(pmNonCosmetic))
  269. makeNonCosmetic();
  270. }
  271. /*! \overload
  272. Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of
  273. this QCPPainter.
  274. \note this function hides the non-virtual base class implementation.
  275. */
  276. void QCPPainter::setPen(Qt::PenStyle penStyle)
  277. {
  278. QPainter::setPen(penStyle);
  279. if (mModes.testFlag(pmNonCosmetic))
  280. makeNonCosmetic();
  281. }
  282. /*! \overload
  283. Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when
  284. antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to
  285. integer coordinates and then passes it to the original drawLine.
  286. \note this function hides the non-virtual base class implementation.
  287. */
  288. void QCPPainter::drawLine(const QLineF &line)
  289. {
  290. if (mIsAntialiasing || mModes.testFlag(pmVectorized))
  291. QPainter::drawLine(line);
  292. else
  293. QPainter::drawLine(line.toLine());
  294. }
  295. /*!
  296. Sets whether painting uses antialiasing or not. Use this method instead of using setRenderHint
  297. with QPainter::Antialiasing directly, as it allows QCPPainter to regain pixel exactness between
  298. antialiased and non-antialiased painting (Since Qt < 5.0 uses slightly different coordinate systems for
  299. AA/Non-AA painting).
  300. */
  301. void QCPPainter::setAntialiasing(bool enabled)
  302. {
  303. setRenderHint(QPainter::Antialiasing, enabled);
  304. if (mIsAntialiasing != enabled)
  305. {
  306. mIsAntialiasing = enabled;
  307. if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs
  308. {
  309. if (mIsAntialiasing)
  310. translate(0.5, 0.5);
  311. else
  312. translate(-0.5, -0.5);
  313. }
  314. }
  315. }
  316. /*!
  317. Sets the mode of the painter. This controls whether the painter shall adjust its
  318. fixes/workarounds optimized for certain output devices.
  319. */
  320. void QCPPainter::setModes(QCPPainter::PainterModes modes)
  321. {
  322. mModes = modes;
  323. }
  324. /*!
  325. Sets the QPainter::NonCosmeticDefaultPen in Qt versions before Qt5 after beginning painting on \a
  326. device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5,
  327. all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that
  328. behaviour.
  329. The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets
  330. the render hint as appropriate.
  331. \note this function hides the non-virtual base class implementation.
  332. */
  333. bool QCPPainter::begin(QPaintDevice *device)
  334. {
  335. bool result = QPainter::begin(device);
  336. #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.
  337. if (result)
  338. setRenderHint(QPainter::NonCosmeticDefaultPen);
  339. #endif
  340. return result;
  341. }
  342. /*! \overload
  343. Sets the mode of the painter. This controls whether the painter shall adjust its
  344. fixes/workarounds optimized for certain output devices.
  345. */
  346. void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled)
  347. {
  348. if (!enabled && mModes.testFlag(mode))
  349. mModes &= ~mode;
  350. else if (enabled && !mModes.testFlag(mode))
  351. mModes |= mode;
  352. }
  353. /*!
  354. Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to
  355. QPainter, the save/restore functions are reimplemented to also save/restore those members.
  356. \note this function hides the non-virtual base class implementation.
  357. \see restore
  358. */
  359. void QCPPainter::save()
  360. {
  361. mAntialiasingStack.push(mIsAntialiasing);
  362. QPainter::save();
  363. }
  364. /*!
  365. Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to
  366. QPainter, the save/restore functions are reimplemented to also save/restore those members.
  367. \note this function hides the non-virtual base class implementation.
  368. \see save
  369. */
  370. void QCPPainter::restore()
  371. {
  372. if (!mAntialiasingStack.isEmpty())
  373. mIsAntialiasing = mAntialiasingStack.pop();
  374. else
  375. qDebug() << Q_FUNC_INFO << "Unbalanced save/restore";
  376. QPainter::restore();
  377. }
  378. /*!
  379. Changes the pen width to 1 if it currently is 0. This function is called in the \ref setPen
  380. overrides when the \ref pmNonCosmetic mode is set.
  381. */
  382. void QCPPainter::makeNonCosmetic()
  383. {
  384. if (qFuzzyIsNull(pen().widthF()))
  385. {
  386. QPen p = pen();
  387. p.setWidth(1);
  388. QPainter::setPen(p);
  389. }
  390. }
  391. /* end of 'src/painter.cpp' */
  392. /* including file 'src/paintbuffer.cpp', size 18502 */
  393. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  394. ////////////////////////////////////////////////////////////////////////////////////////////////////
  395. //////////////////// QCPAbstractPaintBuffer
  396. ////////////////////////////////////////////////////////////////////////////////////////////////////
  397. /*! \class QCPAbstractPaintBuffer
  398. \brief The abstract base class for paint buffers, which define the rendering backend
  399. This abstract base class defines the basic interface that a paint buffer needs to provide in
  400. order to be usable by QCustomPlot.
  401. A paint buffer manages both a surface to draw onto, and the matching paint device. The size of
  402. the surface can be changed via \ref setSize. External classes (\ref QCustomPlot and \ref
  403. QCPLayer) request a painter via \ref startPainting and then perform the draw calls. Once the
  404. painting is complete, \ref donePainting is called, so the paint buffer implementation can do
  405. clean up if necessary. Before rendering a frame, each paint buffer is usually filled with a color
  406. using \ref clear (usually the color is \c Qt::transparent), to remove the contents of the
  407. previous frame.
  408. The simplest paint buffer implementation is \ref QCPPaintBufferPixmap which allows regular
  409. software rendering via the raster engine. Hardware accelerated rendering via pixel buffers and
  410. frame buffer objects is provided by \ref QCPPaintBufferGlPbuffer and \ref QCPPaintBufferGlFbo.
  411. They are used automatically if \ref QCustomPlot::setOpenGl is enabled.
  412. */
  413. /* start documentation of pure virtual functions */
  414. /*! \fn virtual QCPPainter *QCPAbstractPaintBuffer::startPainting() = 0
  415. Returns a \ref QCPPainter which is ready to draw to this buffer. The ownership and thus the
  416. responsibility to delete the painter after the painting operations are complete is given to the
  417. caller of this method.
  418. Once you are done using the painter, delete the painter and call \ref donePainting.
  419. While a painter generated with this method is active, you must not call \ref setSize, \ref
  420. setDevicePixelRatio or \ref clear.
  421. This method may return 0, if a painter couldn't be activated on the buffer. This usually
  422. indicates a problem with the respective painting backend.
  423. */
  424. /*! \fn virtual void QCPAbstractPaintBuffer::draw(QCPPainter *painter) const = 0
  425. Draws the contents of this buffer with the provided \a painter. This is the method that is used
  426. to finally join all paint buffers and draw them onto the screen.
  427. */
  428. /*! \fn virtual void QCPAbstractPaintBuffer::clear(const QColor &color) = 0
  429. Fills the entire buffer with the provided \a color. To have an empty transparent buffer, use the
  430. named color \c Qt::transparent.
  431. This method must not be called if there is currently a painter (acquired with \ref startPainting)
  432. active.
  433. */
  434. /*! \fn virtual void QCPAbstractPaintBuffer::reallocateBuffer() = 0
  435. Reallocates the internal buffer with the currently configured size (\ref setSize) and device
  436. pixel ratio, if applicable (\ref setDevicePixelRatio). It is called as soon as any of those
  437. properties are changed on this paint buffer.
  438. \note Subclasses of \ref QCPAbstractPaintBuffer must call their reimplementation of this method
  439. in their constructor, to perform the first allocation (this can not be done by the base class
  440. because calling pure virtual methods in base class constructors is not possible).
  441. */
  442. /* end documentation of pure virtual functions */
  443. /* start documentation of inline functions */
  444. /*! \fn virtual void QCPAbstractPaintBuffer::donePainting()
  445. If you have acquired a \ref QCPPainter to paint onto this paint buffer via \ref startPainting,
  446. call this method as soon as you are done with the painting operations and have deleted the
  447. painter.
  448. paint buffer subclasses may use this method to perform any type of cleanup that is necessary. The
  449. default implementation does nothing.
  450. */
  451. /* end documentation of inline functions */
  452. /*!
  453. Creates a paint buffer and initializes it with the provided \a size and \a devicePixelRatio.
  454. Subclasses must call their \ref reallocateBuffer implementation in their respective constructors.
  455. */
  456. QCPAbstractPaintBuffer::QCPAbstractPaintBuffer(const QSize &size, double devicePixelRatio) :
  457. mSize(size),
  458. mDevicePixelRatio(devicePixelRatio),
  459. mInvalidated(true)
  460. {
  461. }
  462. QCPAbstractPaintBuffer::~QCPAbstractPaintBuffer()
  463. {
  464. }
  465. /*!
  466. Sets the paint buffer size.
  467. The buffer is reallocated (by calling \ref reallocateBuffer), so any painters that were obtained
  468. by \ref startPainting are invalidated and must not be used after calling this method.
  469. If \a size is already the current buffer size, this method does nothing.
  470. */
  471. void QCPAbstractPaintBuffer::setSize(const QSize &size)
  472. {
  473. if (mSize != size)
  474. {
  475. mSize = size;
  476. reallocateBuffer();
  477. }
  478. }
  479. /*!
  480. Sets the invalidated flag to \a invalidated.
  481. This mechanism is used internally in conjunction with isolated replotting of \ref QCPLayer
  482. instances (in \ref QCPLayer::lmBuffered mode). If \ref QCPLayer::replot is called on a buffered
  483. layer, i.e. an isolated repaint of only that layer (and its dedicated paint buffer) is requested,
  484. QCustomPlot will decide depending on the invalidated flags of other paint buffers whether it also
  485. replots them, instead of only the layer on which the replot was called.
  486. The invalidated flag is set to true when \ref QCPLayer association has changed, i.e. if layers
  487. were added or removed from this buffer, or if they were reordered. It is set to false as soon as
  488. all associated \ref QCPLayer instances are drawn onto the buffer.
  489. Under normal circumstances, it is not necessary to manually call this method.
  490. */
  491. void QCPAbstractPaintBuffer::setInvalidated(bool invalidated)
  492. {
  493. mInvalidated = invalidated;
  494. }
  495. /*!
  496. Sets the the device pixel ratio to \a ratio. This is useful to render on high-DPI output devices.
  497. The ratio is automatically set to the device pixel ratio used by the parent QCustomPlot instance.
  498. The buffer is reallocated (by calling \ref reallocateBuffer), so any painters that were obtained
  499. by \ref startPainting are invalidated and must not be used after calling this method.
  500. \note This method is only available for Qt versions 5.4 and higher.
  501. */
  502. void QCPAbstractPaintBuffer::setDevicePixelRatio(double ratio)
  503. {
  504. if (!qFuzzyCompare(ratio, mDevicePixelRatio))
  505. {
  506. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  507. mDevicePixelRatio = ratio;
  508. reallocateBuffer();
  509. #else
  510. qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
  511. mDevicePixelRatio = 1.0;
  512. #endif
  513. }
  514. }
  515. ////////////////////////////////////////////////////////////////////////////////////////////////////
  516. //////////////////// QCPPaintBufferPixmap
  517. ////////////////////////////////////////////////////////////////////////////////////////////////////
  518. /*! \class QCPPaintBufferPixmap
  519. \brief A paint buffer based on QPixmap, using software raster rendering
  520. This paint buffer is the default and fall-back paint buffer which uses software rendering and
  521. QPixmap as internal buffer. It is used if \ref QCustomPlot::setOpenGl is false.
  522. */
  523. /*!
  524. Creates a pixmap paint buffer instancen with the specified \a size and \a devicePixelRatio, if
  525. applicable.
  526. */
  527. QCPPaintBufferPixmap::QCPPaintBufferPixmap(const QSize &size, double devicePixelRatio) :
  528. QCPAbstractPaintBuffer(size, devicePixelRatio)
  529. {
  530. QCPPaintBufferPixmap::reallocateBuffer();
  531. }
  532. QCPPaintBufferPixmap::~QCPPaintBufferPixmap()
  533. {
  534. }
  535. /* inherits documentation from base class */
  536. QCPPainter *QCPPaintBufferPixmap::startPainting()
  537. {
  538. QCPPainter *result = new QCPPainter(&mBuffer);
  539. result->setRenderHint(QPainter::HighQualityAntialiasing);
  540. return result;
  541. }
  542. /* inherits documentation from base class */
  543. void QCPPaintBufferPixmap::draw(QCPPainter *painter) const
  544. {
  545. if (painter && painter->isActive())
  546. painter->drawPixmap(0, 0, mBuffer);
  547. else
  548. qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
  549. }
  550. /* inherits documentation from base class */
  551. void QCPPaintBufferPixmap::clear(const QColor &color)
  552. {
  553. mBuffer.fill(color);
  554. }
  555. /* inherits documentation from base class */
  556. void QCPPaintBufferPixmap::reallocateBuffer()
  557. {
  558. setInvalidated();
  559. if (!qFuzzyCompare(1.0, mDevicePixelRatio))
  560. {
  561. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  562. mBuffer = QPixmap(mSize*mDevicePixelRatio);
  563. mBuffer.setDevicePixelRatio(mDevicePixelRatio);
  564. #else
  565. qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
  566. mDevicePixelRatio = 1.0;
  567. mBuffer = QPixmap(mSize);
  568. #endif
  569. } else
  570. {
  571. mBuffer = QPixmap(mSize);
  572. }
  573. }
  574. #ifdef QCP_OPENGL_PBUFFER
  575. ////////////////////////////////////////////////////////////////////////////////////////////////////
  576. //////////////////// QCPPaintBufferGlPbuffer
  577. ////////////////////////////////////////////////////////////////////////////////////////////////////
  578. /*! \class QCPPaintBufferGlPbuffer
  579. \brief A paint buffer based on OpenGL pixel buffers, using hardware accelerated rendering
  580. This paint buffer is one of the OpenGL paint buffers which facilitate hardware accelerated plot
  581. rendering. It is based on OpenGL pixel buffers (pbuffer) and is used in Qt versions before 5.0.
  582. (See \ref QCPPaintBufferGlFbo used in newer Qt versions.)
  583. The OpenGL paint buffers are used if \ref QCustomPlot::setOpenGl is set to true, and if they are
  584. supported by the system.
  585. */
  586. /*!
  587. Creates a \ref QCPPaintBufferGlPbuffer instance with the specified \a size and \a
  588. devicePixelRatio, if applicable.
  589. The parameter \a multisamples defines how many samples are used per pixel. Higher values thus
  590. result in higher quality antialiasing. If the specified \a multisamples value exceeds the
  591. capability of the graphics hardware, the highest supported multisampling is used.
  592. */
  593. QCPPaintBufferGlPbuffer::QCPPaintBufferGlPbuffer(const QSize &size, double devicePixelRatio, int multisamples) :
  594. QCPAbstractPaintBuffer(size, devicePixelRatio),
  595. mGlPBuffer(0),
  596. mMultisamples(qMax(0, multisamples))
  597. {
  598. QCPPaintBufferGlPbuffer::reallocateBuffer();
  599. }
  600. QCPPaintBufferGlPbuffer::~QCPPaintBufferGlPbuffer()
  601. {
  602. if (mGlPBuffer)
  603. delete mGlPBuffer;
  604. }
  605. /* inherits documentation from base class */
  606. QCPPainter *QCPPaintBufferGlPbuffer::startPainting()
  607. {
  608. if (!mGlPBuffer->isValid())
  609. {
  610. qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
  611. return 0;
  612. }
  613. QCPPainter *result = new QCPPainter(mGlPBuffer);
  614. result->setRenderHint(QPainter::HighQualityAntialiasing);
  615. return result;
  616. }
  617. /* inherits documentation from base class */
  618. void QCPPaintBufferGlPbuffer::draw(QCPPainter *painter) const
  619. {
  620. if (!painter || !painter->isActive())
  621. {
  622. qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
  623. return;
  624. }
  625. if (!mGlPBuffer->isValid())
  626. {
  627. qDebug() << Q_FUNC_INFO << "OpenGL pbuffer isn't valid, reallocateBuffer was not called?";
  628. return;
  629. }
  630. painter->drawImage(0, 0, mGlPBuffer->toImage());
  631. }
  632. /* inherits documentation from base class */
  633. void QCPPaintBufferGlPbuffer::clear(const QColor &color)
  634. {
  635. if (mGlPBuffer->isValid())
  636. {
  637. mGlPBuffer->makeCurrent();
  638. glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
  639. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  640. mGlPBuffer->doneCurrent();
  641. } else
  642. qDebug() << Q_FUNC_INFO << "OpenGL pbuffer invalid or context not current";
  643. }
  644. /* inherits documentation from base class */
  645. void QCPPaintBufferGlPbuffer::reallocateBuffer()
  646. {
  647. if (mGlPBuffer)
  648. delete mGlPBuffer;
  649. QGLFormat format;
  650. format.setAlpha(true);
  651. format.setSamples(mMultisamples);
  652. mGlPBuffer = new QGLPixelBuffer(mSize, format);
  653. }
  654. #endif // QCP_OPENGL_PBUFFER
  655. #ifdef QCP_OPENGL_FBO
  656. ////////////////////////////////////////////////////////////////////////////////////////////////////
  657. //////////////////// QCPPaintBufferGlFbo
  658. ////////////////////////////////////////////////////////////////////////////////////////////////////
  659. /*! \class QCPPaintBufferGlFbo
  660. \brief A paint buffer based on OpenGL frame buffers objects, using hardware accelerated rendering
  661. This paint buffer is one of the OpenGL paint buffers which facilitate hardware accelerated plot
  662. rendering. It is based on OpenGL frame buffer objects (fbo) and is used in Qt versions 5.0 and
  663. higher. (See \ref QCPPaintBufferGlPbuffer used in older Qt versions.)
  664. The OpenGL paint buffers are used if \ref QCustomPlot::setOpenGl is set to true, and if they are
  665. supported by the system.
  666. */
  667. /*!
  668. Creates a \ref QCPPaintBufferGlFbo instance with the specified \a size and \a devicePixelRatio,
  669. if applicable.
  670. All frame buffer objects shall share one OpenGL context and paint device, which need to be set up
  671. externally and passed via \a glContext and \a glPaintDevice. The set-up is done in \ref
  672. QCustomPlot::setupOpenGl and the context and paint device are managed by the parent QCustomPlot
  673. instance.
  674. */
  675. QCPPaintBufferGlFbo::QCPPaintBufferGlFbo(const QSize &size, double devicePixelRatio, QWeakPointer<QOpenGLContext> glContext, QWeakPointer<QOpenGLPaintDevice> glPaintDevice) :
  676. QCPAbstractPaintBuffer(size, devicePixelRatio),
  677. mGlContext(glContext),
  678. mGlPaintDevice(glPaintDevice),
  679. mGlFrameBuffer(0)
  680. {
  681. QCPPaintBufferGlFbo::reallocateBuffer();
  682. }
  683. QCPPaintBufferGlFbo::~QCPPaintBufferGlFbo()
  684. {
  685. if (mGlFrameBuffer)
  686. delete mGlFrameBuffer;
  687. }
  688. /* inherits documentation from base class */
  689. QCPPainter *QCPPaintBufferGlFbo::startPainting()
  690. {
  691. if (mGlPaintDevice.isNull())
  692. {
  693. qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist";
  694. return 0;
  695. }
  696. if (!mGlFrameBuffer)
  697. {
  698. qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
  699. return 0;
  700. }
  701. if (QOpenGLContext::currentContext() != mGlContext.data())
  702. mGlContext.data()->makeCurrent(mGlContext.data()->surface());
  703. mGlFrameBuffer->bind();
  704. QCPPainter *result = new QCPPainter(mGlPaintDevice.data());
  705. result->setRenderHint(QPainter::HighQualityAntialiasing);
  706. return result;
  707. }
  708. /* inherits documentation from base class */
  709. void QCPPaintBufferGlFbo::donePainting()
  710. {
  711. if (mGlFrameBuffer && mGlFrameBuffer->isBound())
  712. mGlFrameBuffer->release();
  713. else
  714. qDebug() << Q_FUNC_INFO << "Either OpenGL frame buffer not valid or was not bound";
  715. }
  716. /* inherits documentation from base class */
  717. void QCPPaintBufferGlFbo::draw(QCPPainter *painter) const
  718. {
  719. if (!painter || !painter->isActive())
  720. {
  721. qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
  722. return;
  723. }
  724. if (!mGlFrameBuffer)
  725. {
  726. qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
  727. return;
  728. }
  729. painter->drawImage(0, 0, mGlFrameBuffer->toImage());
  730. }
  731. /* inherits documentation from base class */
  732. void QCPPaintBufferGlFbo::clear(const QColor &color)
  733. {
  734. if (mGlContext.isNull())
  735. {
  736. qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist";
  737. return;
  738. }
  739. if (!mGlFrameBuffer)
  740. {
  741. qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
  742. return;
  743. }
  744. if (QOpenGLContext::currentContext() != mGlContext.data())
  745. mGlContext.data()->makeCurrent(mGlContext.data()->surface());
  746. mGlFrameBuffer->bind();
  747. glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
  748. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  749. mGlFrameBuffer->release();
  750. }
  751. /* inherits documentation from base class */
  752. void QCPPaintBufferGlFbo::reallocateBuffer()
  753. {
  754. // release and delete possibly existing framebuffer:
  755. if (mGlFrameBuffer)
  756. {
  757. if (mGlFrameBuffer->isBound())
  758. mGlFrameBuffer->release();
  759. delete mGlFrameBuffer;
  760. mGlFrameBuffer = 0;
  761. }
  762. if (mGlContext.isNull())
  763. {
  764. qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist";
  765. return;
  766. }
  767. if (mGlPaintDevice.isNull())
  768. {
  769. qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist";
  770. return;
  771. }
  772. // create new fbo with appropriate size:
  773. mGlContext.data()->makeCurrent(mGlContext.data()->surface());
  774. QOpenGLFramebufferObjectFormat frameBufferFormat;
  775. frameBufferFormat.setSamples(mGlContext.data()->format().samples());
  776. frameBufferFormat.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
  777. mGlFrameBuffer = new QOpenGLFramebufferObject(mSize*mDevicePixelRatio, frameBufferFormat);
  778. if (mGlPaintDevice.data()->size() != mSize*mDevicePixelRatio)
  779. mGlPaintDevice.data()->setSize(mSize*mDevicePixelRatio);
  780. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  781. mGlPaintDevice.data()->setDevicePixelRatio(mDevicePixelRatio);
  782. #endif
  783. }
  784. #endif // QCP_OPENGL_FBO
  785. /* end of 'src/paintbuffer.cpp' */
  786. /* including file 'src/layer.cpp', size 37064 */
  787. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  788. ////////////////////////////////////////////////////////////////////////////////////////////////////
  789. //////////////////// QCPLayer
  790. ////////////////////////////////////////////////////////////////////////////////////////////////////
  791. /*! \class QCPLayer
  792. \brief A layer that may contain objects, to control the rendering order
  793. The Layering system of QCustomPlot is the mechanism to control the rendering order of the
  794. elements inside the plot.
  795. It is based on the two classes QCPLayer and QCPLayerable. QCustomPlot holds an ordered list of
  796. one or more instances of QCPLayer (see QCustomPlot::addLayer, QCustomPlot::layer,
  797. QCustomPlot::moveLayer, etc.). When replotting, QCustomPlot goes through the list of layers
  798. bottom to top and successively draws the layerables of the layers into the paint buffer(s).
  799. A QCPLayer contains an ordered list of QCPLayerable instances. QCPLayerable is an abstract base
  800. class from which almost all visible objects derive, like axes, grids, graphs, items, etc.
  801. \section qcplayer-defaultlayers Default layers
  802. Initially, QCustomPlot has six layers: "background", "grid", "main", "axes", "legend" and
  803. "overlay" (in that order). On top is the "overlay" layer, which only contains the QCustomPlot's
  804. selection rect (\ref QCustomPlot::selectionRect). The next two layers "axes" and "legend" contain
  805. the default axes and legend, so they will be drawn above plottables. In the middle, there is the
  806. "main" layer. It is initially empty and set as the current layer (see
  807. QCustomPlot::setCurrentLayer). This means, all new plottables, items etc. are created on this
  808. layer by default. Then comes the "grid" layer which contains the QCPGrid instances (which belong
  809. tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background shall be drawn behind
  810. everything else, thus the default QCPAxisRect instance is placed on the "background" layer. Of
  811. course, the layer affiliation of the individual objects can be changed as required (\ref
  812. QCPLayerable::setLayer).
  813. \section qcplayer-ordering Controlling the rendering order via layers
  814. Controlling the ordering of layerables in the plot is easy: Create a new layer in the position
  815. you want the layerable to be in, e.g. above "main", with \ref QCustomPlot::addLayer. Then set the
  816. current layer with \ref QCustomPlot::setCurrentLayer to that new layer and finally create the
  817. objects normally. They will be placed on the new layer automatically, due to the current layer
  818. setting. Alternatively you could have also ignored the current layer setting and just moved the
  819. objects with \ref QCPLayerable::setLayer to the desired layer after creating them.
  820. It is also possible to move whole layers. For example, If you want the grid to be shown in front
  821. of all plottables/items on the "main" layer, just move it above "main" with
  822. QCustomPlot::moveLayer.
  823. The rendering order within one layer is simply by order of creation or insertion. The item
  824. created last (or added last to the layer), is drawn on top of all other objects on that layer.
  825. When a layer is deleted, the objects on it are not deleted with it, but fall on the layer below
  826. the deleted layer, see QCustomPlot::removeLayer.
  827. \section qcplayer-buffering Replotting only a specific layer
  828. If the layer mode (\ref setMode) is set to \ref lmBuffered, you can replot only this specific
  829. layer by calling \ref replot. In certain situations this can provide better replot performance,
  830. compared with a full replot of all layers. Upon creation of a new layer, the layer mode is
  831. initialized to \ref lmLogical. The only layer that is set to \ref lmBuffered in a new \ref
  832. QCustomPlot instance is the "overlay" layer, containing the selection rect.
  833. */
  834. /* start documentation of inline functions */
  835. /*! \fn QList<QCPLayerable*> QCPLayer::children() const
  836. Returns a list of all layerables on this layer. The order corresponds to the rendering order:
  837. layerables with higher indices are drawn above layerables with lower indices.
  838. */
  839. /*! \fn int QCPLayer::index() const
  840. Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be
  841. accessed via \ref QCustomPlot::layer.
  842. Layers with higher indices will be drawn above layers with lower indices.
  843. */
  844. /* end documentation of inline functions */
  845. /*!
  846. Creates a new QCPLayer instance.
  847. Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead.
  848. \warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot.
  849. This check is only performed by \ref QCustomPlot::addLayer.
  850. */
  851. QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) :
  852. QObject(parentPlot),
  853. mParentPlot(parentPlot),
  854. mName(layerName),
  855. mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function
  856. mVisible(true),
  857. mMode(lmLogical)
  858. {
  859. // Note: no need to make sure layerName is unique, because layer
  860. // management is done with QCustomPlot functions.
  861. }
  862. QCPLayer::~QCPLayer()
  863. {
  864. // If child layerables are still on this layer, detach them, so they don't try to reach back to this
  865. // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted
  866. // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to
  867. // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.)
  868. while (!mChildren.isEmpty())
  869. mChildren.last()->setLayer(0); // removes itself from mChildren via removeChild()
  870. if (mParentPlot->currentLayer() == this)
  871. qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or 0 beforehand.";
  872. }
  873. /*!
  874. Sets whether this layer is visible or not. If \a visible is set to false, all layerables on this
  875. layer will be invisible.
  876. This function doesn't change the visibility property of the layerables (\ref
  877. QCPLayerable::setVisible), but the \ref QCPLayerable::realVisibility of each layerable takes the
  878. visibility of the parent layer into account.
  879. */
  880. void QCPLayer::setVisible(bool visible)
  881. {
  882. mVisible = visible;
  883. }
  884. /*!
  885. Sets the rendering mode of this layer.
  886. If \a mode is set to \ref lmBuffered for a layer, it will be given a dedicated paint buffer by
  887. the parent QCustomPlot instance. This means it may be replotted individually by calling \ref
  888. QCPLayer::replot, without needing to replot all other layers.
  889. Layers which are set to \ref lmLogical (the default) are used only to define the rendering order
  890. and can't be replotted individually.
  891. Note that each layer which is set to \ref lmBuffered requires additional paint buffers for the
  892. layers below, above and for the layer itself. This increases the memory consumption and
  893. (slightly) decreases the repainting speed because multiple paint buffers need to be joined. So
  894. you should carefully choose which layers benefit from having their own paint buffer. A typical
  895. example would be a layer which contains certain layerables (e.g. items) that need to be changed
  896. and thus replotted regularly, while all other layerables on other layers stay static. By default,
  897. only the topmost layer called "overlay" is in mode \ref lmBuffered, and contains the selection
  898. rect.
  899. \see replot
  900. */
  901. void QCPLayer::setMode(QCPLayer::LayerMode mode)
  902. {
  903. if (mMode != mode)
  904. {
  905. mMode = mode;
  906. if (!mPaintBuffer.isNull())
  907. mPaintBuffer.data()->setInvalidated();
  908. }
  909. }
  910. /*! \internal
  911. Draws the contents of this layer with the provided \a painter.
  912. \see replot, drawToPaintBuffer
  913. */
  914. void QCPLayer::draw(QCPPainter *painter)
  915. {
  916. foreach (QCPLayerable *child, mChildren)
  917. {
  918. if (child->realVisibility())
  919. {
  920. painter->save();
  921. painter->setClipRect(child->clipRect().translated(0, -1));
  922. child->applyDefaultAntialiasingHint(painter);
  923. child->draw(painter);
  924. painter->restore();
  925. }
  926. }
  927. }
  928. /*! \internal
  929. Draws the contents of this layer into the paint buffer which is associated with this layer. The
  930. association is established by the parent QCustomPlot, which manages all paint buffers (see \ref
  931. QCustomPlot::setupPaintBuffers).
  932. \see draw
  933. */
  934. void QCPLayer::drawToPaintBuffer()
  935. {
  936. if (!mPaintBuffer.isNull())
  937. {
  938. if (QCPPainter *painter = mPaintBuffer.data()->startPainting())
  939. {
  940. if (painter->isActive())
  941. draw(painter);
  942. else
  943. qDebug() << Q_FUNC_INFO << "paint buffer returned inactive painter";
  944. delete painter;
  945. mPaintBuffer.data()->donePainting();
  946. } else
  947. qDebug() << Q_FUNC_INFO << "paint buffer returned zero painter";
  948. } else
  949. qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer";
  950. }
  951. /*!
  952. If the layer mode (\ref setMode) is set to \ref lmBuffered, this method allows replotting only
  953. the layerables on this specific layer, without the need to replot all other layers (as a call to
  954. \ref QCustomPlot::replot would do).
  955. If the layer mode is \ref lmLogical however, this method simply calls \ref QCustomPlot::replot on
  956. the parent QCustomPlot instance.
  957. QCustomPlot also makes sure to replot all layers instead of only this one, if the layer ordering
  958. has changed since the last full replot and the other paint buffers were thus invalidated.
  959. \see draw
  960. */
  961. void QCPLayer::replot()
  962. {
  963. if (mMode == lmBuffered && !mParentPlot->hasInvalidatedPaintBuffers())
  964. {
  965. if (!mPaintBuffer.isNull())
  966. {
  967. mPaintBuffer.data()->clear(Qt::transparent);
  968. drawToPaintBuffer();
  969. mPaintBuffer.data()->setInvalidated(false);
  970. mParentPlot->update();
  971. } else
  972. qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer";
  973. } else if (mMode == lmLogical)
  974. mParentPlot->replot();
  975. }
  976. /*! \internal
  977. Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will
  978. be prepended to the list, i.e. be drawn beneath the other layerables already in the list.
  979. This function does not change the \a mLayer member of \a layerable to this layer. (Use
  980. QCPLayerable::setLayer to change the layer of an object, not this function.)
  981. \see removeChild
  982. */
  983. void QCPLayer::addChild(QCPLayerable *layerable, bool prepend)
  984. {
  985. if (!mChildren.contains(layerable))
  986. {
  987. if (prepend)
  988. mChildren.prepend(layerable);
  989. else
  990. mChildren.append(layerable);
  991. if (!mPaintBuffer.isNull())
  992. mPaintBuffer.data()->setInvalidated();
  993. } else
  994. qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast<quintptr>(layerable);
  995. }
  996. /*! \internal
  997. Removes the \a layerable from the list of this layer.
  998. This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer
  999. to change the layer of an object, not this function.)
  1000. \see addChild
  1001. */
  1002. void QCPLayer::removeChild(QCPLayerable *layerable)
  1003. {
  1004. if (mChildren.removeOne(layerable))
  1005. {
  1006. if (!mPaintBuffer.isNull())
  1007. mPaintBuffer.data()->setInvalidated();
  1008. } else
  1009. qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast<quintptr>(layerable);
  1010. }
  1011. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1012. //////////////////// QCPLayerable
  1013. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1014. /*! \class QCPLayerable
  1015. \brief Base class for all drawable objects
  1016. This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid
  1017. etc.
  1018. Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking
  1019. the layers accordingly.
  1020. For details about the layering mechanism, see the QCPLayer documentation.
  1021. */
  1022. /* start documentation of inline functions */
  1023. /*! \fn QCPLayerable *QCPLayerable::parentLayerable() const
  1024. Returns the parent layerable of this layerable. The parent layerable is used to provide
  1025. visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables
  1026. only get drawn if their parent layerables are visible, too.
  1027. Note that a parent layerable is not necessarily also the QObject parent for memory management.
  1028. Further, a layerable doesn't always have a parent layerable, so this function may return 0.
  1029. A parent layerable is set implicitly when placed inside layout elements and doesn't need to be
  1030. set manually by the user.
  1031. */
  1032. /* end documentation of inline functions */
  1033. /* start documentation of pure virtual functions */
  1034. /*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0
  1035. \internal
  1036. This function applies the default antialiasing setting to the specified \a painter, using the
  1037. function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when
  1038. \ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing
  1039. setting may be specified individually, this function should set the antialiasing state of the
  1040. most prominent entity. In this case however, the \ref draw function usually calls the specialized
  1041. versions of this function before drawing each entity, effectively overriding the setting of the
  1042. default antialiasing hint.
  1043. <b>First example:</b> QCPGraph has multiple entities that have an antialiasing setting: The graph
  1044. line, fills and scatters. Those can be configured via QCPGraph::setAntialiased,
  1045. QCPGraph::setAntialiasedFill and QCPGraph::setAntialiasedScatters. Consequently, there isn't only
  1046. the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's
  1047. antialiasing), but specialized ones like QCPGraph::applyFillAntialiasingHint and
  1048. QCPGraph::applyScattersAntialiasingHint. So before drawing one of those entities, QCPGraph::draw
  1049. calls the respective specialized applyAntialiasingHint function.
  1050. <b>Second example:</b> QCPItemLine consists only of a line so there is only one antialiasing
  1051. setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by
  1052. all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the
  1053. respective layerable subclass.) Consequently it only has the normal
  1054. QCPItemLine::applyDefaultAntialiasingHint. The \ref QCPItemLine::draw function doesn't need to
  1055. care about setting any antialiasing states, because the default antialiasing hint is already set
  1056. on the painter when the \ref draw function is called, and that's the state it wants to draw the
  1057. line with.
  1058. */
  1059. /*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0
  1060. \internal
  1061. This function draws the layerable with the specified \a painter. It is only called by
  1062. QCustomPlot, if the layerable is visible (\ref setVisible).
  1063. Before this function is called, the painter's antialiasing state is set via \ref
  1064. applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was
  1065. set to \ref clipRect.
  1066. */
  1067. /* end documentation of pure virtual functions */
  1068. /* start documentation of signals */
  1069. /*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer);
  1070. This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to
  1071. a different layer.
  1072. \see setLayer
  1073. */
  1074. /* end documentation of signals */
  1075. /*!
  1076. Creates a new QCPLayerable instance.
  1077. Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the
  1078. derived classes.
  1079. If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a
  1080. targetLayer is an empty string, it places itself on the current layer of the plot (see \ref
  1081. QCustomPlot::setCurrentLayer).
  1082. It is possible to provide 0 as \a plot. In that case, you should assign a parent plot at a later
  1083. time with \ref initializeParentPlot.
  1084. The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable
  1085. parents are mainly used to control visibility in a hierarchy of layerables. This means a
  1086. layerable is only drawn, if all its ancestor layerables are also visible. Note that \a
  1087. parentLayerable does not become the QObject-parent (for memory management) of this layerable, \a
  1088. plot does. It is not uncommon to set the QObject-parent to something else in the constructors of
  1089. QCPLayerable subclasses, to guarantee a working destruction hierarchy.
  1090. */
  1091. QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) :
  1092. QObject(plot),
  1093. mVisible(true),
  1094. mParentPlot(plot),
  1095. mParentLayerable(parentLayerable),
  1096. mLayer(0),
  1097. mAntialiased(true)
  1098. {
  1099. if (mParentPlot)
  1100. {
  1101. if (targetLayer.isEmpty())
  1102. setLayer(mParentPlot->currentLayer());
  1103. else if (!setLayer(targetLayer))
  1104. qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed.";
  1105. }
  1106. }
  1107. QCPLayerable::~QCPLayerable()
  1108. {
  1109. if (mLayer)
  1110. {
  1111. mLayer->removeChild(this);
  1112. mLayer = 0;
  1113. }
  1114. }
  1115. /*!
  1116. Sets the visibility of this layerable object. If an object is not visible, it will not be drawn
  1117. on the QCustomPlot surface, and user interaction with it (e.g. click and selection) is not
  1118. possible.
  1119. */
  1120. void QCPLayerable::setVisible(bool on)
  1121. {
  1122. mVisible = on;
  1123. }
  1124. /*!
  1125. Sets the \a layer of this layerable object. The object will be placed on top of the other objects
  1126. already on \a layer.
  1127. If \a layer is 0, this layerable will not be on any layer and thus not appear in the plot (or
  1128. interact/receive events).
  1129. Returns true if the layer of this layerable was successfully changed to \a layer.
  1130. */
  1131. bool QCPLayerable::setLayer(QCPLayer *layer)
  1132. {
  1133. return moveToLayer(layer, false);
  1134. }
  1135. /*! \overload
  1136. Sets the layer of this layerable object by name
  1137. Returns true on success, i.e. if \a layerName is a valid layer name.
  1138. */
  1139. bool QCPLayerable::setLayer(const QString &layerName)
  1140. {
  1141. if (!mParentPlot)
  1142. {
  1143. qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
  1144. return false;
  1145. }
  1146. if (QCPLayer *layer = mParentPlot->layer(layerName))
  1147. {
  1148. return setLayer(layer);
  1149. } else
  1150. {
  1151. qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName;
  1152. return false;
  1153. }
  1154. }
  1155. /*!
  1156. Sets whether this object will be drawn antialiased or not.
  1157. Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and
  1158. QCustomPlot::setNotAntialiasedElements.
  1159. */
  1160. void QCPLayerable::setAntialiased(bool enabled)
  1161. {
  1162. mAntialiased = enabled;
  1163. }
  1164. /*!
  1165. Returns whether this layerable is visible, taking the visibility of the layerable parent and the
  1166. visibility of this layerable's layer into account. This is the method that is consulted to decide
  1167. whether a layerable shall be drawn or not.
  1168. If this layerable has a direct layerable parent (usually set via hierarchies implemented in
  1169. subclasses, like in the case of \ref QCPLayoutElement), this function returns true only if this
  1170. layerable has its visibility set to true and the parent layerable's \ref realVisibility returns
  1171. true.
  1172. */
  1173. bool QCPLayerable::realVisibility() const
  1174. {
  1175. return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility());
  1176. }
  1177. /*!
  1178. This function is used to decide whether a click hits a layerable object or not.
  1179. \a pos is a point in pixel coordinates on the QCustomPlot surface. This function returns the
  1180. shortest pixel distance of this point to the object. If the object is either invisible or the
  1181. distance couldn't be determined, -1.0 is returned. Further, if \a onlySelectable is true and the
  1182. object is not selectable, -1.0 is returned, too.
  1183. If the object is represented not by single lines but by an area like a \ref QCPItemText or the
  1184. bars of a \ref QCPBars plottable, a click inside the area should also be considered a hit. In
  1185. these cases this function thus returns a constant value greater zero but still below the parent
  1186. plot's selection tolerance. (typically the selectionTolerance multiplied by 0.99).
  1187. Providing a constant value for area objects allows selecting line objects even when they are
  1188. obscured by such area objects, by clicking close to the lines (i.e. closer than
  1189. 0.99*selectionTolerance).
  1190. The actual setting of the selection state is not done by this function. This is handled by the
  1191. parent QCustomPlot when the mouseReleaseEvent occurs, and the finally selected object is notified
  1192. via the \ref selectEvent/\ref deselectEvent methods.
  1193. \a details is an optional output parameter. Every layerable subclass may place any information
  1194. in \a details. This information will be passed to \ref selectEvent when the parent QCustomPlot
  1195. decides on the basis of this selectTest call, that the object was successfully selected. The
  1196. subsequent call to \ref selectEvent will carry the \a details. This is useful for multi-part
  1197. objects (like QCPAxis). This way, a possibly complex calculation to decide which part was clicked
  1198. is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be
  1199. placed in \a details. So in the subsequent \ref selectEvent, the decition which part was
  1200. selected doesn't have to be done a second time for a single selection operation.
  1201. You may pass 0 as \a details to indicate that you are not interested in those selection details.
  1202. \see selectEvent, deselectEvent, mousePressEvent, wheelEvent, QCustomPlot::setInteractions
  1203. */
  1204. double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  1205. {
  1206. Q_UNUSED(pos)
  1207. Q_UNUSED(onlySelectable)
  1208. Q_UNUSED(details)
  1209. return -1.0;
  1210. }
  1211. /*! \internal
  1212. Sets the parent plot of this layerable. Use this function once to set the parent plot if you have
  1213. passed 0 in the constructor. It can not be used to move a layerable from one QCustomPlot to
  1214. another one.
  1215. Note that, unlike when passing a non-null parent plot in the constructor, this function does not
  1216. make \a parentPlot the QObject-parent of this layerable. If you want this, call
  1217. QObject::setParent(\a parentPlot) in addition to this function.
  1218. Further, you will probably want to set a layer (\ref setLayer) after calling this function, to
  1219. make the layerable appear on the QCustomPlot.
  1220. The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized
  1221. so they can react accordingly (e.g. also initialize the parent plot of child layerables, like
  1222. QCPLayout does).
  1223. */
  1224. void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot)
  1225. {
  1226. if (mParentPlot)
  1227. {
  1228. qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized";
  1229. return;
  1230. }
  1231. if (!parentPlot)
  1232. qDebug() << Q_FUNC_INFO << "called with parentPlot zero";
  1233. mParentPlot = parentPlot;
  1234. parentPlotInitialized(mParentPlot);
  1235. }
  1236. /*! \internal
  1237. Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not
  1238. become the QObject-parent (for memory management) of this layerable.
  1239. The parent layerable has influence on the return value of the \ref realVisibility method. Only
  1240. layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be
  1241. drawn.
  1242. \see realVisibility
  1243. */
  1244. void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable)
  1245. {
  1246. mParentLayerable = parentLayerable;
  1247. }
  1248. /*! \internal
  1249. Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to
  1250. the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is
  1251. false, the object will be appended.
  1252. Returns true on success, i.e. if \a layer is a valid layer.
  1253. */
  1254. bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend)
  1255. {
  1256. if (layer && !mParentPlot)
  1257. {
  1258. qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
  1259. return false;
  1260. }
  1261. if (layer && layer->parentPlot() != mParentPlot)
  1262. {
  1263. qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable";
  1264. return false;
  1265. }
  1266. QCPLayer *oldLayer = mLayer;
  1267. if (mLayer)
  1268. mLayer->removeChild(this);
  1269. mLayer = layer;
  1270. if (mLayer)
  1271. mLayer->addChild(this, prepend);
  1272. if (mLayer != oldLayer)
  1273. emit layerChanged(mLayer);
  1274. return true;
  1275. }
  1276. /*! \internal
  1277. Sets the QCPainter::setAntialiasing state on the provided \a painter, depending on the \a
  1278. localAntialiased value as well as the overrides \ref QCustomPlot::setAntialiasedElements and \ref
  1279. QCustomPlot::setNotAntialiasedElements. Which override enum this function takes into account is
  1280. controlled via \a overrideElement.
  1281. */
  1282. void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const
  1283. {
  1284. if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement))
  1285. painter->setAntialiasing(false);
  1286. else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement))
  1287. painter->setAntialiasing(true);
  1288. else
  1289. painter->setAntialiasing(localAntialiased);
  1290. }
  1291. /*! \internal
  1292. This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting
  1293. of a parent plot. This is the case when 0 was passed as parent plot in the constructor, and the
  1294. parent plot is set at a later time.
  1295. For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any
  1296. QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level
  1297. element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To
  1298. propagate the parent plot to all the children of the hierarchy, the top level element then uses
  1299. this function to pass the parent plot on to its child elements.
  1300. The default implementation does nothing.
  1301. \see initializeParentPlot
  1302. */
  1303. void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot)
  1304. {
  1305. Q_UNUSED(parentPlot)
  1306. }
  1307. /*! \internal
  1308. Returns the selection category this layerable shall belong to. The selection category is used in
  1309. conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and
  1310. which aren't.
  1311. Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref
  1312. QCP::iSelectOther. This is what the default implementation returns.
  1313. \see QCustomPlot::setInteractions
  1314. */
  1315. QCP::Interaction QCPLayerable::selectionCategory() const
  1316. {
  1317. return QCP::iSelectOther;
  1318. }
  1319. /*! \internal
  1320. Returns the clipping rectangle of this layerable object. By default, this is the viewport of the
  1321. parent QCustomPlot. Specific subclasses may reimplement this function to provide different
  1322. clipping rects.
  1323. The returned clipping rect is set on the painter before the draw function of the respective
  1324. object is called.
  1325. */
  1326. QRect QCPLayerable::clipRect() const
  1327. {
  1328. if (mParentPlot)
  1329. return mParentPlot->viewport();
  1330. else
  1331. return QRect();
  1332. }
  1333. /*! \internal
  1334. This event is called when the layerable shall be selected, as a consequence of a click by the
  1335. user. Subclasses should react to it by setting their selection state appropriately. The default
  1336. implementation does nothing.
  1337. \a event is the mouse event that caused the selection. \a additive indicates, whether the user
  1338. was holding the multi-select-modifier while performing the selection (see \ref
  1339. QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled
  1340. (i.e. become selected when unselected and unselected when selected).
  1341. Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e.
  1342. returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot).
  1343. The \a details data you output from \ref selectTest is fed back via \a details here. You may
  1344. use it to transport any kind of information from the selectTest to the possibly subsequent
  1345. selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable
  1346. that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need
  1347. to do the calculation again to find out which part was actually clicked.
  1348. \a selectionStateChanged is an output parameter. If the pointer is non-null, this function must
  1349. set the value either to true or false, depending on whether the selection state of this layerable
  1350. was actually changed. For layerables that only are selectable as a whole and not in parts, this
  1351. is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the
  1352. selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the
  1353. layerable was previously unselected and now is switched to the selected state.
  1354. \see selectTest, deselectEvent
  1355. */
  1356. void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  1357. {
  1358. Q_UNUSED(event)
  1359. Q_UNUSED(additive)
  1360. Q_UNUSED(details)
  1361. Q_UNUSED(selectionStateChanged)
  1362. }
  1363. /*! \internal
  1364. This event is called when the layerable shall be deselected, either as consequence of a user
  1365. interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by
  1366. unsetting their selection appropriately.
  1367. just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must
  1368. return true or false when the selection state of this layerable has changed or not changed,
  1369. respectively.
  1370. \see selectTest, selectEvent
  1371. */
  1372. void QCPLayerable::deselectEvent(bool *selectionStateChanged)
  1373. {
  1374. Q_UNUSED(selectionStateChanged)
  1375. }
  1376. /*!
  1377. This event gets called when the user presses a mouse button while the cursor is over the
  1378. layerable. Whether a cursor is over the layerable is decided by a preceding call to \ref
  1379. selectTest.
  1380. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
  1381. event->pos(). The parameter \a details contains layerable-specific details about the hit, which
  1382. were generated in the previous call to \ref selectTest. For example, One-dimensional plottables
  1383. like \ref QCPGraph or \ref QCPBars convey the clicked data point in the \a details parameter, as
  1384. \ref QCPDataSelection packed as QVariant. Multi-part objects convey the specific \c
  1385. SelectablePart that was hit (e.g. \ref QCPAxis::SelectablePart in the case of axes).
  1386. QCustomPlot uses an event propagation system that works the same as Qt's system. If your
  1387. layerable doesn't reimplement the \ref mousePressEvent or explicitly calls \c event->ignore() in
  1388. its reimplementation, the event will be propagated to the next layerable in the stacking order.
  1389. Once a layerable has accepted the \ref mousePressEvent, it is considered the mouse grabber and
  1390. will receive all following calls to \ref mouseMoveEvent or \ref mouseReleaseEvent for this mouse
  1391. interaction (a "mouse interaction" in this context ends with the release).
  1392. The default implementation does nothing except explicitly ignoring the event with \c
  1393. event->ignore().
  1394. \see mouseMoveEvent, mouseReleaseEvent, mouseDoubleClickEvent, wheelEvent
  1395. */
  1396. void QCPLayerable::mousePressEvent(QMouseEvent *event, const QVariant &details)
  1397. {
  1398. Q_UNUSED(details)
  1399. event->ignore();
  1400. }
  1401. /*!
  1402. This event gets called when the user moves the mouse while holding a mouse button, after this
  1403. layerable has become the mouse grabber by accepting the preceding \ref mousePressEvent.
  1404. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
  1405. event->pos(). The parameter \a startPos indicates the position where the initial \ref
  1406. mousePressEvent occured, that started the mouse interaction.
  1407. The default implementation does nothing.
  1408. \see mousePressEvent, mouseReleaseEvent, mouseDoubleClickEvent, wheelEvent
  1409. */
  1410. void QCPLayerable::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  1411. {
  1412. Q_UNUSED(startPos)
  1413. event->ignore();
  1414. }
  1415. /*!
  1416. This event gets called when the user releases the mouse button, after this layerable has become
  1417. the mouse grabber by accepting the preceding \ref mousePressEvent.
  1418. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
  1419. event->pos(). The parameter \a startPos indicates the position where the initial \ref
  1420. mousePressEvent occured, that started the mouse interaction.
  1421. The default implementation does nothing.
  1422. \see mousePressEvent, mouseMoveEvent, mouseDoubleClickEvent, wheelEvent
  1423. */
  1424. void QCPLayerable::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  1425. {
  1426. Q_UNUSED(startPos)
  1427. event->ignore();
  1428. }
  1429. /*!
  1430. This event gets called when the user presses the mouse button a second time in a double-click,
  1431. while the cursor is over the layerable. Whether a cursor is over the layerable is decided by a
  1432. preceding call to \ref selectTest.
  1433. The \ref mouseDoubleClickEvent is called instead of the second \ref mousePressEvent. So in the
  1434. case of a double-click, the event succession is
  1435. <i>pressEvent &ndash; releaseEvent &ndash; doubleClickEvent &ndash; releaseEvent</i>.
  1436. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
  1437. event->pos(). The parameter \a details contains layerable-specific details about the hit, which
  1438. were generated in the previous call to \ref selectTest. For example, One-dimensional plottables
  1439. like \ref QCPGraph or \ref QCPBars convey the clicked data point in the \a details parameter, as
  1440. \ref QCPDataSelection packed as QVariant. Multi-part objects convey the specific \c
  1441. SelectablePart that was hit (e.g. \ref QCPAxis::SelectablePart in the case of axes).
  1442. Similarly to \ref mousePressEvent, once a layerable has accepted the \ref mouseDoubleClickEvent,
  1443. it is considered the mouse grabber and will receive all following calls to \ref mouseMoveEvent
  1444. and \ref mouseReleaseEvent for this mouse interaction (a "mouse interaction" in this context ends
  1445. with the release).
  1446. The default implementation does nothing except explicitly ignoring the event with \c
  1447. event->ignore().
  1448. \see mousePressEvent, mouseMoveEvent, mouseReleaseEvent, wheelEvent
  1449. */
  1450. void QCPLayerable::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details)
  1451. {
  1452. Q_UNUSED(details)
  1453. event->ignore();
  1454. }
  1455. /*!
  1456. This event gets called when the user turns the mouse scroll wheel while the cursor is over the
  1457. layerable. Whether a cursor is over the layerable is decided by a preceding call to \ref
  1458. selectTest.
  1459. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
  1460. event->pos().
  1461. The \c event->delta() indicates how far the mouse wheel was turned, which is usually +/- 120 for
  1462. single rotation steps. However, if the mouse wheel is turned rapidly, multiple steps may
  1463. accumulate to one event, making \c event->delta() larger. On the other hand, if the wheel has
  1464. very smooth steps or none at all, the delta may be smaller.
  1465. The default implementation does nothing.
  1466. \see mousePressEvent, mouseMoveEvent, mouseReleaseEvent, mouseDoubleClickEvent
  1467. */
  1468. void QCPLayerable::wheelEvent(QWheelEvent *event)
  1469. {
  1470. event->ignore();
  1471. }
  1472. /* end of 'src/layer.cpp' */
  1473. /* including file 'src/axis/range.cpp', size 12221 */
  1474. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  1475. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1476. //////////////////// QCPRange
  1477. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1478. /*! \class QCPRange
  1479. \brief Represents the range an axis is encompassing.
  1480. contains a \a lower and \a upper double value and provides convenience input, output and
  1481. modification functions.
  1482. \see QCPAxis::setRange
  1483. */
  1484. /* start of documentation of inline functions */
  1485. /*! \fn double QCPRange::size() const
  1486. Returns the size of the range, i.e. \a upper-\a lower
  1487. */
  1488. /*! \fn double QCPRange::center() const
  1489. Returns the center of the range, i.e. (\a upper+\a lower)*0.5
  1490. */
  1491. /*! \fn void QCPRange::normalize()
  1492. Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values are
  1493. swapped.
  1494. */
  1495. /*! \fn bool QCPRange::contains(double value) const
  1496. Returns true when \a value lies within or exactly on the borders of the range.
  1497. */
  1498. /*! \fn QCPRange &QCPRange::operator+=(const double& value)
  1499. Adds \a value to both boundaries of the range.
  1500. */
  1501. /*! \fn QCPRange &QCPRange::operator-=(const double& value)
  1502. Subtracts \a value from both boundaries of the range.
  1503. */
  1504. /*! \fn QCPRange &QCPRange::operator*=(const double& value)
  1505. Multiplies both boundaries of the range by \a value.
  1506. */
  1507. /*! \fn QCPRange &QCPRange::operator/=(const double& value)
  1508. Divides both boundaries of the range by \a value.
  1509. */
  1510. /* end of documentation of inline functions */
  1511. /*!
  1512. Minimum range size (\a upper - \a lower) the range changing functions will accept. Smaller
  1513. intervals would cause errors due to the 11-bit exponent of double precision numbers,
  1514. corresponding to a minimum magnitude of roughly 1e-308.
  1515. \warning Do not use this constant to indicate "arbitrarily small" values in plotting logic (as
  1516. values that will appear in the plot)! It is intended only as a bound to compare against, e.g. to
  1517. prevent axis ranges from obtaining underflowing ranges.
  1518. \see validRange, maxRange
  1519. */
  1520. const double QCPRange::minRange = 1e-280;
  1521. /*!
  1522. Maximum values (negative and positive) the range will accept in range-changing functions.
  1523. Larger absolute values would cause errors due to the 11-bit exponent of double precision numbers,
  1524. corresponding to a maximum magnitude of roughly 1e308.
  1525. \warning Do not use this constant to indicate "arbitrarily large" values in plotting logic (as
  1526. values that will appear in the plot)! It is intended only as a bound to compare against, e.g. to
  1527. prevent axis ranges from obtaining overflowing ranges.
  1528. \see validRange, minRange
  1529. */
  1530. const double QCPRange::maxRange = 1e250;
  1531. /*!
  1532. Constructs a range with \a lower and \a upper set to zero.
  1533. */
  1534. QCPRange::QCPRange() :
  1535. lower(0),
  1536. upper(0)
  1537. {
  1538. }
  1539. /*! \overload
  1540. Constructs a range with the specified \a lower and \a upper values.
  1541. The resulting range will be normalized (see \ref normalize), so if \a lower is not numerically
  1542. smaller than \a upper, they will be swapped.
  1543. */
  1544. QCPRange::QCPRange(double lower, double upper) :
  1545. lower(lower),
  1546. upper(upper)
  1547. {
  1548. normalize();
  1549. }
  1550. /*! \overload
  1551. Expands this range such that \a otherRange is contained in the new range. It is assumed that both
  1552. this range and \a otherRange are normalized (see \ref normalize).
  1553. If this range contains NaN as lower or upper bound, it will be replaced by the respective bound
  1554. of \a otherRange.
  1555. If \a otherRange is already inside the current range, this function does nothing.
  1556. \see expanded
  1557. */
  1558. void QCPRange::expand(const QCPRange &otherRange)
  1559. {
  1560. if (lower > otherRange.lower || qIsNaN(lower))
  1561. lower = otherRange.lower;
  1562. if (upper < otherRange.upper || qIsNaN(upper))
  1563. upper = otherRange.upper;
  1564. }
  1565. /*! \overload
  1566. Expands this range such that \a includeCoord is contained in the new range. It is assumed that
  1567. this range is normalized (see \ref normalize).
  1568. If this range contains NaN as lower or upper bound, the respective bound will be set to \a
  1569. includeCoord.
  1570. If \a includeCoord is already inside the current range, this function does nothing.
  1571. \see expand
  1572. */
  1573. void QCPRange::expand(double includeCoord)
  1574. {
  1575. if (lower > includeCoord || qIsNaN(lower))
  1576. lower = includeCoord;
  1577. if (upper < includeCoord || qIsNaN(upper))
  1578. upper = includeCoord;
  1579. }
  1580. /*! \overload
  1581. Returns an expanded range that contains this and \a otherRange. It is assumed that both this
  1582. range and \a otherRange are normalized (see \ref normalize).
  1583. If this range contains NaN as lower or upper bound, the returned range's bound will be taken from
  1584. \a otherRange.
  1585. \see expand
  1586. */
  1587. QCPRange QCPRange::expanded(const QCPRange &otherRange) const
  1588. {
  1589. QCPRange result = *this;
  1590. result.expand(otherRange);
  1591. return result;
  1592. }
  1593. /*! \overload
  1594. Returns an expanded range that includes the specified \a includeCoord. It is assumed that this
  1595. range is normalized (see \ref normalize).
  1596. If this range contains NaN as lower or upper bound, the returned range's bound will be set to \a
  1597. includeCoord.
  1598. \see expand
  1599. */
  1600. QCPRange QCPRange::expanded(double includeCoord) const
  1601. {
  1602. QCPRange result = *this;
  1603. result.expand(includeCoord);
  1604. return result;
  1605. }
  1606. /*!
  1607. Returns this range, possibly modified to not exceed the bounds provided as \a lowerBound and \a
  1608. upperBound. If possible, the size of the current range is preserved in the process.
  1609. If the range shall only be bounded at the lower side, you can set \a upperBound to \ref
  1610. QCPRange::maxRange. If it shall only be bounded at the upper side, set \a lowerBound to -\ref
  1611. QCPRange::maxRange.
  1612. */
  1613. QCPRange QCPRange::bounded(double lowerBound, double upperBound) const
  1614. {
  1615. if (lowerBound > upperBound)
  1616. qSwap(lowerBound, upperBound);
  1617. QCPRange result(lower, upper);
  1618. if (result.lower < lowerBound)
  1619. {
  1620. result.lower = lowerBound;
  1621. result.upper = lowerBound + size();
  1622. if (result.upper > upperBound || qFuzzyCompare(size(), upperBound-lowerBound))
  1623. result.upper = upperBound;
  1624. } else if (result.upper > upperBound)
  1625. {
  1626. result.upper = upperBound;
  1627. result.lower = upperBound - size();
  1628. if (result.lower < lowerBound || qFuzzyCompare(size(), upperBound-lowerBound))
  1629. result.lower = lowerBound;
  1630. }
  1631. return result;
  1632. }
  1633. /*!
  1634. Returns a sanitized version of the range. Sanitized means for logarithmic scales, that
  1635. the range won't span the positive and negative sign domain, i.e. contain zero. Further
  1636. \a lower will always be numerically smaller (or equal) to \a upper.
  1637. If the original range does span positive and negative sign domains or contains zero,
  1638. the returned range will try to approximate the original range as good as possible.
  1639. If the positive interval of the original range is wider than the negative interval, the
  1640. returned range will only contain the positive interval, with lower bound set to \a rangeFac or
  1641. \a rangeFac *\a upper, whichever is closer to zero. Same procedure is used if the negative interval
  1642. is wider than the positive interval, this time by changing the \a upper bound.
  1643. */
  1644. QCPRange QCPRange::sanitizedForLogScale() const
  1645. {
  1646. double rangeFac = 1e-3;
  1647. QCPRange sanitizedRange(lower, upper);
  1648. sanitizedRange.normalize();
  1649. // can't have range spanning negative and positive values in log plot, so change range to fix it
  1650. //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1))
  1651. if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0)
  1652. {
  1653. // case lower is 0
  1654. if (rangeFac < sanitizedRange.upper*rangeFac)
  1655. sanitizedRange.lower = rangeFac;
  1656. else
  1657. sanitizedRange.lower = sanitizedRange.upper*rangeFac;
  1658. } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1))
  1659. else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0)
  1660. {
  1661. // case upper is 0
  1662. if (-rangeFac > sanitizedRange.lower*rangeFac)
  1663. sanitizedRange.upper = -rangeFac;
  1664. else
  1665. sanitizedRange.upper = sanitizedRange.lower*rangeFac;
  1666. } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0)
  1667. {
  1668. // find out whether negative or positive interval is wider to decide which sign domain will be chosen
  1669. if (-sanitizedRange.lower > sanitizedRange.upper)
  1670. {
  1671. // negative is wider, do same as in case upper is 0
  1672. if (-rangeFac > sanitizedRange.lower*rangeFac)
  1673. sanitizedRange.upper = -rangeFac;
  1674. else
  1675. sanitizedRange.upper = sanitizedRange.lower*rangeFac;
  1676. } else
  1677. {
  1678. // positive is wider, do same as in case lower is 0
  1679. if (rangeFac < sanitizedRange.upper*rangeFac)
  1680. sanitizedRange.lower = rangeFac;
  1681. else
  1682. sanitizedRange.lower = sanitizedRange.upper*rangeFac;
  1683. }
  1684. }
  1685. // due to normalization, case lower>0 && upper<0 should never occur, because that implies upper<lower
  1686. return sanitizedRange;
  1687. }
  1688. /*!
  1689. Returns a sanitized version of the range. Sanitized means for linear scales, that
  1690. \a lower will always be numerically smaller (or equal) to \a upper.
  1691. */
  1692. QCPRange QCPRange::sanitizedForLinScale() const
  1693. {
  1694. QCPRange sanitizedRange(lower, upper);
  1695. sanitizedRange.normalize();
  1696. return sanitizedRange;
  1697. }
  1698. /*!
  1699. Checks, whether the specified range is within valid bounds, which are defined
  1700. as QCPRange::maxRange and QCPRange::minRange.
  1701. A valid range means:
  1702. \li range bounds within -maxRange and maxRange
  1703. \li range size above minRange
  1704. \li range size below maxRange
  1705. */
  1706. bool QCPRange::validRange(double lower, double upper)
  1707. {
  1708. return (lower > -maxRange &&
  1709. upper < maxRange &&
  1710. qAbs(lower-upper) > minRange &&
  1711. qAbs(lower-upper) < maxRange &&
  1712. !(lower > 0 && qIsInf(upper/lower)) &&
  1713. !(upper < 0 && qIsInf(lower/upper)));
  1714. }
  1715. /*!
  1716. \overload
  1717. Checks, whether the specified range is within valid bounds, which are defined
  1718. as QCPRange::maxRange and QCPRange::minRange.
  1719. A valid range means:
  1720. \li range bounds within -maxRange and maxRange
  1721. \li range size above minRange
  1722. \li range size below maxRange
  1723. */
  1724. bool QCPRange::validRange(const QCPRange &range)
  1725. {
  1726. return (range.lower > -maxRange &&
  1727. range.upper < maxRange &&
  1728. qAbs(range.lower-range.upper) > minRange &&
  1729. qAbs(range.lower-range.upper) < maxRange &&
  1730. !(range.lower > 0 && qIsInf(range.upper/range.lower)) &&
  1731. !(range.upper < 0 && qIsInf(range.lower/range.upper)));
  1732. }
  1733. /* end of 'src/axis/range.cpp' */
  1734. /* including file 'src/selection.cpp', size 21906 */
  1735. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  1736. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1737. //////////////////// QCPDataRange
  1738. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1739. /*! \class QCPDataRange
  1740. \brief Describes a data range given by begin and end index
  1741. QCPDataRange holds two integers describing the begin (\ref setBegin) and end (\ref setEnd) index
  1742. of a contiguous set of data points. The end index points to the data point above the last data point that's part of
  1743. the data range, similarly to the nomenclature used in standard iterators.
  1744. Data Ranges are not bound to a certain plottable, thus they can be freely exchanged, created and
  1745. modified. If a non-contiguous data set shall be described, the class \ref QCPDataSelection is
  1746. used, which holds and manages multiple instances of \ref QCPDataRange. In most situations, \ref
  1747. QCPDataSelection is thus used.
  1748. Both \ref QCPDataRange and \ref QCPDataSelection offer convenience methods to work with them,
  1749. e.g. \ref bounded, \ref expanded, \ref intersects, \ref intersection, \ref adjusted, \ref
  1750. contains. Further, addition and subtraction operators (defined in \ref QCPDataSelection) can be
  1751. used to join/subtract data ranges and data selections (or mixtures), to retrieve a corresponding
  1752. \ref QCPDataSelection.
  1753. %QCustomPlot's \ref dataselection "data selection mechanism" is based on \ref QCPDataSelection and
  1754. QCPDataRange.
  1755. \note Do not confuse \ref QCPDataRange with \ref QCPRange. A \ref QCPRange describes an interval
  1756. in floating point plot coordinates, e.g. the current axis range.
  1757. */
  1758. /* start documentation of inline functions */
  1759. /*! \fn int QCPDataRange::size() const
  1760. Returns the number of data points described by this data range. This is equal to the end index
  1761. minus the begin index.
  1762. \see length
  1763. */
  1764. /*! \fn int QCPDataRange::length() const
  1765. Returns the number of data points described by this data range. Equivalent to \ref size.
  1766. */
  1767. /*! \fn void QCPDataRange::setBegin(int begin)
  1768. Sets the begin of this data range. The \a begin index points to the first data point that is part
  1769. of the data range.
  1770. No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
  1771. \see setEnd
  1772. */
  1773. /*! \fn void QCPDataRange::setEnd(int end)
  1774. Sets the end of this data range. The \a end index points to the data point just above the last
  1775. data point that is part of the data range.
  1776. No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
  1777. \see setBegin
  1778. */
  1779. /*! \fn bool QCPDataRange::isValid() const
  1780. Returns whether this range is valid. A valid range has a begin index greater or equal to 0, and
  1781. an end index greater or equal to the begin index.
  1782. \note Invalid ranges should be avoided and are never the result of any of QCustomPlot's methods
  1783. (unless they are themselves fed with invalid ranges). Do not pass invalid ranges to QCustomPlot's
  1784. methods. The invalid range is not inherently prevented in QCPDataRange, to allow temporary
  1785. invalid begin/end values while manipulating the range. An invalid range is not necessarily empty
  1786. (\ref isEmpty), since its \ref length can be negative and thus non-zero.
  1787. */
  1788. /*! \fn bool QCPDataRange::isEmpty() const
  1789. Returns whether this range is empty, i.e. whether its begin index equals its end index.
  1790. \see size, length
  1791. */
  1792. /*! \fn QCPDataRange QCPDataRange::adjusted(int changeBegin, int changeEnd) const
  1793. Returns a data range where \a changeBegin and \a changeEnd were added to the begin and end
  1794. indices, respectively.
  1795. */
  1796. /* end documentation of inline functions */
  1797. /*!
  1798. Creates an empty QCPDataRange, with begin and end set to 0.
  1799. */
  1800. QCPDataRange::QCPDataRange() :
  1801. mBegin(0),
  1802. mEnd(0)
  1803. {
  1804. }
  1805. /*!
  1806. Creates a QCPDataRange, initialized with the specified \a begin and \a end.
  1807. No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
  1808. */
  1809. QCPDataRange::QCPDataRange(int begin, int end) :
  1810. mBegin(begin),
  1811. mEnd(end)
  1812. {
  1813. }
  1814. /*!
  1815. Returns a data range that matches this data range, except that parts exceeding \a other are
  1816. excluded.
  1817. This method is very similar to \ref intersection, with one distinction: If this range and the \a
  1818. other range share no intersection, the returned data range will be empty with begin and end set
  1819. to the respective boundary side of \a other, at which this range is residing. (\ref intersection
  1820. would just return a range with begin and end set to 0.)
  1821. */
  1822. QCPDataRange QCPDataRange::bounded(const QCPDataRange &other) const
  1823. {
  1824. QCPDataRange result(intersection(other));
  1825. if (result.isEmpty()) // no intersection, preserve respective bounding side of otherRange as both begin and end of return value
  1826. {
  1827. if (mEnd <= other.mBegin)
  1828. result = QCPDataRange(other.mBegin, other.mBegin);
  1829. else
  1830. result = QCPDataRange(other.mEnd, other.mEnd);
  1831. }
  1832. return result;
  1833. }
  1834. /*!
  1835. Returns a data range that contains both this data range as well as \a other.
  1836. */
  1837. QCPDataRange QCPDataRange::expanded(const QCPDataRange &other) const
  1838. {
  1839. return QCPDataRange(qMin(mBegin, other.mBegin), qMax(mEnd, other.mEnd));
  1840. }
  1841. /*!
  1842. Returns the data range which is contained in both this data range and \a other.
  1843. This method is very similar to \ref bounded, with one distinction: If this range and the \a other
  1844. range share no intersection, the returned data range will be empty with begin and end set to 0.
  1845. (\ref bounded would return a range with begin and end set to one of the boundaries of \a other,
  1846. depending on which side this range is on.)
  1847. \see QCPDataSelection::intersection
  1848. */
  1849. QCPDataRange QCPDataRange::intersection(const QCPDataRange &other) const
  1850. {
  1851. QCPDataRange result(qMax(mBegin, other.mBegin), qMin(mEnd, other.mEnd));
  1852. if (result.isValid())
  1853. return result;
  1854. else
  1855. return QCPDataRange();
  1856. }
  1857. /*!
  1858. Returns whether this data range and \a other share common data points.
  1859. \see intersection, contains
  1860. */
  1861. bool QCPDataRange::intersects(const QCPDataRange &other) const
  1862. {
  1863. return !( (mBegin > other.mBegin && mBegin >= other.mEnd) ||
  1864. (mEnd <= other.mBegin && mEnd < other.mEnd) );
  1865. }
  1866. /*!
  1867. Returns whether all data points described by this data range are also in \a other.
  1868. \see intersects
  1869. */
  1870. bool QCPDataRange::contains(const QCPDataRange &other) const
  1871. {
  1872. return mBegin <= other.mBegin && mEnd >= other.mEnd;
  1873. }
  1874. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1875. //////////////////// QCPDataSelection
  1876. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1877. /*! \class QCPDataSelection
  1878. \brief Describes a data set by holding multiple QCPDataRange instances
  1879. QCPDataSelection manages multiple instances of QCPDataRange in order to represent any (possibly
  1880. disjoint) set of data selection.
  1881. The data selection can be modified with addition and subtraction operators which take
  1882. QCPDataSelection and QCPDataRange instances, as well as methods such as \ref addDataRange and
  1883. \ref clear. Read access is provided by \ref dataRange, \ref dataRanges, \ref dataRangeCount, etc.
  1884. The method \ref simplify is used to join directly adjacent or even overlapping QCPDataRange
  1885. instances. QCPDataSelection automatically simplifies when using the addition/subtraction
  1886. operators. The only case when \ref simplify is left to the user, is when calling \ref
  1887. addDataRange, with the parameter \a simplify explicitly set to false. This is useful if many data
  1888. ranges will be added to the selection successively and the overhead for simplifying after each
  1889. iteration shall be avoided. In this case, you should make sure to call \ref simplify after
  1890. completing the operation.
  1891. Use \ref enforceType to bring the data selection into a state complying with the constraints for
  1892. selections defined in \ref QCP::SelectionType.
  1893. %QCustomPlot's \ref dataselection "data selection mechanism" is based on QCPDataSelection and
  1894. QCPDataRange.
  1895. \section qcpdataselection-iterating Iterating over a data selection
  1896. As an example, the following code snippet calculates the average value of a graph's data
  1897. \ref QCPAbstractPlottable::selection "selection":
  1898. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpdataselection-iterating-1
  1899. */
  1900. /* start documentation of inline functions */
  1901. /*! \fn int QCPDataSelection::dataRangeCount() const
  1902. Returns the number of ranges that make up the data selection. The ranges can be accessed by \ref
  1903. dataRange via their index.
  1904. \see dataRange, dataPointCount
  1905. */
  1906. /*! \fn QList<QCPDataRange> QCPDataSelection::dataRanges() const
  1907. Returns all data ranges that make up the data selection. If the data selection is simplified (the
  1908. usual state of the selection, see \ref simplify), the ranges are sorted by ascending data point
  1909. index.
  1910. \see dataRange
  1911. */
  1912. /*! \fn bool QCPDataSelection::isEmpty() const
  1913. Returns true if there are no data ranges, and thus no data points, in this QCPDataSelection
  1914. instance.
  1915. \see dataRangeCount
  1916. */
  1917. /* end documentation of inline functions */
  1918. /*!
  1919. Creates an empty QCPDataSelection.
  1920. */
  1921. QCPDataSelection::QCPDataSelection()
  1922. {
  1923. }
  1924. /*!
  1925. Creates a QCPDataSelection containing the provided \a range.
  1926. */
  1927. QCPDataSelection::QCPDataSelection(const QCPDataRange &range)
  1928. {
  1929. mDataRanges.append(range);
  1930. }
  1931. /*!
  1932. Returns true if this selection is identical (contains the same data ranges with the same begin
  1933. and end indices) to \a other.
  1934. Note that both data selections must be in simplified state (the usual state of the selection, see
  1935. \ref simplify) for this operator to return correct results.
  1936. */
  1937. bool QCPDataSelection::operator==(const QCPDataSelection &other) const
  1938. {
  1939. if (mDataRanges.size() != other.mDataRanges.size())
  1940. return false;
  1941. for (int i=0; i<mDataRanges.size(); ++i)
  1942. {
  1943. if (mDataRanges.at(i) != other.mDataRanges.at(i))
  1944. return false;
  1945. }
  1946. return true;
  1947. }
  1948. /*!
  1949. Adds the data selection of \a other to this data selection, and then simplifies this data
  1950. selection (see \ref simplify).
  1951. */
  1952. QCPDataSelection &QCPDataSelection::operator+=(const QCPDataSelection &other)
  1953. {
  1954. mDataRanges << other.mDataRanges;
  1955. simplify();
  1956. return *this;
  1957. }
  1958. /*!
  1959. Adds the data range \a other to this data selection, and then simplifies this data selection (see
  1960. \ref simplify).
  1961. */
  1962. QCPDataSelection &QCPDataSelection::operator+=(const QCPDataRange &other)
  1963. {
  1964. addDataRange(other);
  1965. return *this;
  1966. }
  1967. /*!
  1968. Removes all data point indices that are described by \a other from this data selection.
  1969. */
  1970. QCPDataSelection &QCPDataSelection::operator-=(const QCPDataSelection &other)
  1971. {
  1972. for (int i=0; i<other.dataRangeCount(); ++i)
  1973. *this -= other.dataRange(i);
  1974. return *this;
  1975. }
  1976. /*!
  1977. Removes all data point indices that are described by \a other from this data selection.
  1978. */
  1979. QCPDataSelection &QCPDataSelection::operator-=(const QCPDataRange &other)
  1980. {
  1981. if (other.isEmpty() || isEmpty())
  1982. return *this;
  1983. simplify();
  1984. int i=0;
  1985. while (i < mDataRanges.size())
  1986. {
  1987. const int thisBegin = mDataRanges.at(i).begin();
  1988. const int thisEnd = mDataRanges.at(i).end();
  1989. if (thisBegin >= other.end())
  1990. break; // since data ranges are sorted after the simplify() call, no ranges which contain other will come after this
  1991. if (thisEnd > other.begin()) // ranges which don't fulfill this are entirely before other and can be ignored
  1992. {
  1993. if (thisBegin >= other.begin()) // range leading segment is encompassed
  1994. {
  1995. if (thisEnd <= other.end()) // range fully encompassed, remove completely
  1996. {
  1997. mDataRanges.removeAt(i);
  1998. continue;
  1999. } else // only leading segment is encompassed, trim accordingly
  2000. mDataRanges[i].setBegin(other.end());
  2001. } else // leading segment is not encompassed
  2002. {
  2003. if (thisEnd <= other.end()) // only trailing segment is encompassed, trim accordingly
  2004. {
  2005. mDataRanges[i].setEnd(other.begin());
  2006. } else // other lies inside this range, so split range
  2007. {
  2008. mDataRanges[i].setEnd(other.begin());
  2009. mDataRanges.insert(i+1, QCPDataRange(other.end(), thisEnd));
  2010. break; // since data ranges are sorted (and don't overlap) after simplify() call, we're done here
  2011. }
  2012. }
  2013. }
  2014. ++i;
  2015. }
  2016. return *this;
  2017. }
  2018. /*!
  2019. Returns the total number of data points contained in all data ranges that make up this data
  2020. selection.
  2021. */
  2022. int QCPDataSelection::dataPointCount() const
  2023. {
  2024. int result = 0;
  2025. for (int i=0; i<mDataRanges.size(); ++i)
  2026. result += mDataRanges.at(i).length();
  2027. return result;
  2028. }
  2029. /*!
  2030. Returns the data range with the specified \a index.
  2031. If the data selection is simplified (the usual state of the selection, see \ref simplify), the
  2032. ranges are sorted by ascending data point index.
  2033. \see dataRangeCount
  2034. */
  2035. QCPDataRange QCPDataSelection::dataRange(int index) const
  2036. {
  2037. if (index >= 0 && index < mDataRanges.size())
  2038. {
  2039. return mDataRanges.at(index);
  2040. } else
  2041. {
  2042. qDebug() << Q_FUNC_INFO << "index out of range:" << index;
  2043. return QCPDataRange();
  2044. }
  2045. }
  2046. /*!
  2047. Returns a \ref QCPDataRange which spans the entire data selection, including possible
  2048. intermediate segments which are not part of the original data selection.
  2049. */
  2050. QCPDataRange QCPDataSelection::span() const
  2051. {
  2052. if (isEmpty())
  2053. return QCPDataRange();
  2054. else
  2055. return QCPDataRange(mDataRanges.first().begin(), mDataRanges.last().end());
  2056. }
  2057. /*!
  2058. Adds the given \a dataRange to this data selection. This is equivalent to the += operator but
  2059. allows disabling immediate simplification by setting \a simplify to false. This can improve
  2060. performance if adding a very large amount of data ranges successively. In this case, make sure to
  2061. call \ref simplify manually, after the operation.
  2062. */
  2063. void QCPDataSelection::addDataRange(const QCPDataRange &dataRange, bool simplify)
  2064. {
  2065. mDataRanges.append(dataRange);
  2066. if (simplify)
  2067. this->simplify();
  2068. }
  2069. /*!
  2070. Removes all data ranges. The data selection then contains no data points.
  2071. \ref isEmpty
  2072. */
  2073. void QCPDataSelection::clear()
  2074. {
  2075. mDataRanges.clear();
  2076. }
  2077. /*!
  2078. Sorts all data ranges by range begin index in ascending order, and then joins directly adjacent
  2079. or overlapping ranges. This can reduce the number of individual data ranges in the selection, and
  2080. prevents possible double-counting when iterating over the data points held by the data ranges.
  2081. This method is automatically called when using the addition/subtraction operators. The only case
  2082. when \ref simplify is left to the user, is when calling \ref addDataRange, with the parameter \a
  2083. simplify explicitly set to false.
  2084. */
  2085. void QCPDataSelection::simplify()
  2086. {
  2087. // remove any empty ranges:
  2088. for (int i=mDataRanges.size()-1; i>=0; --i)
  2089. {
  2090. if (mDataRanges.at(i).isEmpty())
  2091. mDataRanges.removeAt(i);
  2092. }
  2093. if (mDataRanges.isEmpty())
  2094. return;
  2095. // sort ranges by starting value, ascending:
  2096. std::sort(mDataRanges.begin(), mDataRanges.end(), lessThanDataRangeBegin);
  2097. // join overlapping/contiguous ranges:
  2098. int i = 1;
  2099. while (i < mDataRanges.size())
  2100. {
  2101. 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
  2102. {
  2103. mDataRanges[i-1].setEnd(qMax(mDataRanges.at(i-1).end(), mDataRanges.at(i).end()));
  2104. mDataRanges.removeAt(i);
  2105. } else
  2106. ++i;
  2107. }
  2108. }
  2109. /*!
  2110. Makes sure this data selection conforms to the specified \a type selection type. Before the type
  2111. is enforced, \ref simplify is called.
  2112. Depending on \a type, enforcing means adding new data points that were previously not part of the
  2113. selection, or removing data points from the selection. If the current selection already conforms
  2114. to \a type, the data selection is not changed.
  2115. \see QCP::SelectionType
  2116. */
  2117. void QCPDataSelection::enforceType(QCP::SelectionType type)
  2118. {
  2119. simplify();
  2120. switch (type)
  2121. {
  2122. case QCP::stNone:
  2123. {
  2124. mDataRanges.clear();
  2125. break;
  2126. }
  2127. case QCP::stWhole:
  2128. {
  2129. // whole selection isn't defined by data range, so don't change anything (is handled in plottable methods)
  2130. break;
  2131. }
  2132. case QCP::stSingleData:
  2133. {
  2134. // reduce all data ranges to the single first data point:
  2135. if (!mDataRanges.isEmpty())
  2136. {
  2137. if (mDataRanges.size() > 1)
  2138. mDataRanges = QList<QCPDataRange>() << mDataRanges.first();
  2139. if (mDataRanges.first().length() > 1)
  2140. mDataRanges.first().setEnd(mDataRanges.first().begin()+1);
  2141. }
  2142. break;
  2143. }
  2144. case QCP::stDataRange:
  2145. {
  2146. mDataRanges = QList<QCPDataRange>() << span();
  2147. break;
  2148. }
  2149. case QCP::stMultipleDataRanges:
  2150. {
  2151. // this is the selection type that allows all concievable combinations of ranges, so do nothing
  2152. break;
  2153. }
  2154. }
  2155. }
  2156. /*!
  2157. Returns true if the data selection \a other is contained entirely in this data selection, i.e.
  2158. all data point indices that are in \a other are also in this data selection.
  2159. \see QCPDataRange::contains
  2160. */
  2161. bool QCPDataSelection::contains(const QCPDataSelection &other) const
  2162. {
  2163. if (other.isEmpty()) return false;
  2164. int otherIndex = 0;
  2165. int thisIndex = 0;
  2166. while (thisIndex < mDataRanges.size() && otherIndex < other.mDataRanges.size())
  2167. {
  2168. if (mDataRanges.at(thisIndex).contains(other.mDataRanges.at(otherIndex)))
  2169. ++otherIndex;
  2170. else
  2171. ++thisIndex;
  2172. }
  2173. 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
  2174. }
  2175. /*!
  2176. Returns a data selection containing the points which are both in this data selection and in the
  2177. data range \a other.
  2178. A common use case is to limit an unknown data selection to the valid range of a data container,
  2179. using \ref QCPDataContainer::dataRange as \a other. One can then safely iterate over the returned
  2180. data selection without exceeding the data container's bounds.
  2181. */
  2182. QCPDataSelection QCPDataSelection::intersection(const QCPDataRange &other) const
  2183. {
  2184. QCPDataSelection result;
  2185. for (int i=0; i<mDataRanges.size(); ++i)
  2186. result.addDataRange(mDataRanges.at(i).intersection(other), false);
  2187. result.simplify();
  2188. return result;
  2189. }
  2190. /*!
  2191. Returns a data selection containing the points which are both in this data selection and in the
  2192. data selection \a other.
  2193. */
  2194. QCPDataSelection QCPDataSelection::intersection(const QCPDataSelection &other) const
  2195. {
  2196. QCPDataSelection result;
  2197. for (int i=0; i<other.dataRangeCount(); ++i)
  2198. result += intersection(other.dataRange(i));
  2199. result.simplify();
  2200. return result;
  2201. }
  2202. /*!
  2203. Returns a data selection which is the exact inverse of this data selection, with \a outerRange
  2204. defining the base range on which to invert. If \a outerRange is smaller than the \ref span of
  2205. this data selection, it is expanded accordingly.
  2206. For example, this method can be used to retrieve all unselected segments by setting \a outerRange
  2207. to the full data range of the plottable, and calling this method on a data selection holding the
  2208. selected segments.
  2209. */
  2210. QCPDataSelection QCPDataSelection::inverse(const QCPDataRange &outerRange) const
  2211. {
  2212. if (isEmpty())
  2213. return QCPDataSelection(outerRange);
  2214. QCPDataRange fullRange = outerRange.expanded(span());
  2215. QCPDataSelection result;
  2216. // first unselected segment:
  2217. if (mDataRanges.first().begin() != fullRange.begin())
  2218. result.addDataRange(QCPDataRange(fullRange.begin(), mDataRanges.first().begin()), false);
  2219. // intermediate unselected segments:
  2220. for (int i=1; i<mDataRanges.size(); ++i)
  2221. result.addDataRange(QCPDataRange(mDataRanges.at(i-1).end(), mDataRanges.at(i).begin()), false);
  2222. // last unselected segment:
  2223. if (mDataRanges.last().end() != fullRange.end())
  2224. result.addDataRange(QCPDataRange(mDataRanges.last().end(), fullRange.end()), false);
  2225. result.simplify();
  2226. return result;
  2227. }
  2228. /* end of 'src/selection.cpp' */
  2229. /* including file 'src/selectionrect.cpp', size 9224 */
  2230. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  2231. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2232. //////////////////// QCPSelectionRect
  2233. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2234. /*! \class QCPSelectionRect
  2235. \brief Provides rect/rubber-band data selection and range zoom interaction
  2236. QCPSelectionRect is used by QCustomPlot when the \ref QCustomPlot::setSelectionRectMode is not
  2237. \ref QCP::srmNone. When the user drags the mouse across the plot, the current selection rect
  2238. instance (\ref QCustomPlot::setSelectionRect) is forwarded these events and makes sure an
  2239. according rect shape is drawn. At the begin, during, and after completion of the interaction, it
  2240. emits the corresponding signals \ref started, \ref changed, \ref canceled, and \ref accepted.
  2241. The QCustomPlot instance connects own slots to the current selection rect instance, in order to
  2242. react to an accepted selection rect interaction accordingly.
  2243. \ref isActive can be used to check whether the selection rect is currently active. An ongoing
  2244. selection interaction can be cancelled programmatically via calling \ref cancel at any time.
  2245. The appearance of the selection rect can be controlled via \ref setPen and \ref setBrush.
  2246. If you wish to provide custom behaviour, e.g. a different visual representation of the selection
  2247. rect (\ref QCPSelectionRect::draw), you can subclass QCPSelectionRect and pass an instance of
  2248. your subclass to \ref QCustomPlot::setSelectionRect.
  2249. */
  2250. /* start of documentation of inline functions */
  2251. /*! \fn bool QCPSelectionRect::isActive() const
  2252. Returns true if there is currently a selection going on, i.e. the user has started dragging a
  2253. selection rect, but hasn't released the mouse button yet.
  2254. \see cancel
  2255. */
  2256. /* end of documentation of inline functions */
  2257. /* start documentation of signals */
  2258. /*! \fn void QCPSelectionRect::started(QMouseEvent *event);
  2259. This signal is emitted when a selection rect interaction was initiated, i.e. the user just
  2260. started dragging the selection rect with the mouse.
  2261. */
  2262. /*! \fn void QCPSelectionRect::changed(const QRect &rect, QMouseEvent *event);
  2263. This signal is emitted while the selection rect interaction is ongoing and the \a rect has
  2264. changed its size due to the user moving the mouse.
  2265. Note that \a rect may have a negative width or height, if the selection is being dragged to the
  2266. upper or left side of the selection rect origin.
  2267. */
  2268. /*! \fn void QCPSelectionRect::canceled(const QRect &rect, QInputEvent *event);
  2269. This signal is emitted when the selection interaction was cancelled. Note that \a event is 0 if
  2270. the selection interaction was cancelled programmatically, by a call to \ref cancel.
  2271. The user may cancel the selection interaction by pressing the escape key. In this case, \a event
  2272. holds the respective input event.
  2273. Note that \a rect may have a negative width or height, if the selection is being dragged to the
  2274. upper or left side of the selection rect origin.
  2275. */
  2276. /*! \fn void QCPSelectionRect::accepted(const QRect &rect, QMouseEvent *event);
  2277. This signal is emitted when the selection interaction was completed by the user releasing the
  2278. mouse button.
  2279. Note that \a rect may have a negative width or height, if the selection is being dragged to the
  2280. upper or left side of the selection rect origin.
  2281. */
  2282. /* end documentation of signals */
  2283. /*!
  2284. Creates a new QCPSelectionRect instance. To make QCustomPlot use the selection rect instance,
  2285. pass it to \ref QCustomPlot::setSelectionRect. \a parentPlot should be set to the same
  2286. QCustomPlot widget.
  2287. */
  2288. QCPSelectionRect::QCPSelectionRect(QCustomPlot *parentPlot) :
  2289. QCPLayerable(parentPlot),
  2290. mPen(QBrush(Qt::gray), 0, Qt::DashLine),
  2291. mBrush(Qt::NoBrush),
  2292. mActive(false)
  2293. {
  2294. }
  2295. QCPSelectionRect::~QCPSelectionRect()
  2296. {
  2297. cancel();
  2298. }
  2299. /*!
  2300. A convenience function which returns the coordinate range of the provided \a axis, that this
  2301. selection rect currently encompasses.
  2302. */
  2303. QCPRange QCPSelectionRect::range(const QCPAxis *axis) const
  2304. {
  2305. if (axis)
  2306. {
  2307. if (axis->orientation() == Qt::Horizontal)
  2308. return QCPRange(axis->pixelToCoord(mRect.left()), axis->pixelToCoord(mRect.left()+mRect.width()));
  2309. else
  2310. return QCPRange(axis->pixelToCoord(mRect.top()+mRect.height()), axis->pixelToCoord(mRect.top()));
  2311. } else
  2312. {
  2313. qDebug() << Q_FUNC_INFO << "called with axis zero";
  2314. return QCPRange();
  2315. }
  2316. }
  2317. /*!
  2318. Sets the pen that will be used to draw the selection rect outline.
  2319. \see setBrush
  2320. */
  2321. void QCPSelectionRect::setPen(const QPen &pen)
  2322. {
  2323. mPen = pen;
  2324. }
  2325. /*!
  2326. Sets the brush that will be used to fill the selection rect. By default the selection rect is not
  2327. filled, i.e. \a brush is <tt>Qt::NoBrush</tt>.
  2328. \see setPen
  2329. */
  2330. void QCPSelectionRect::setBrush(const QBrush &brush)
  2331. {
  2332. mBrush = brush;
  2333. }
  2334. /*!
  2335. If there is currently a selection interaction going on (\ref isActive), the interaction is
  2336. canceled. The selection rect will emit the \ref canceled signal.
  2337. */
  2338. void QCPSelectionRect::cancel()
  2339. {
  2340. if (mActive)
  2341. {
  2342. mActive = false;
  2343. emit canceled(mRect, 0);
  2344. }
  2345. }
  2346. /*! \internal
  2347. This method is called by QCustomPlot to indicate that a selection rect interaction was initiated.
  2348. The default implementation sets the selection rect to active, initializes the selection rect
  2349. geometry and emits the \ref started signal.
  2350. */
  2351. void QCPSelectionRect::startSelection(QMouseEvent *event)
  2352. {
  2353. mActive = true;
  2354. mRect = QRect(event->pos(), event->pos());
  2355. emit started(event);
  2356. }
  2357. /*! \internal
  2358. This method is called by QCustomPlot to indicate that an ongoing selection rect interaction needs
  2359. to update its geometry. The default implementation updates the rect and emits the \ref changed
  2360. signal.
  2361. */
  2362. void QCPSelectionRect::moveSelection(QMouseEvent *event)
  2363. {
  2364. mRect.setBottomRight(event->pos());
  2365. emit changed(mRect, event);
  2366. layer()->replot();
  2367. }
  2368. /*! \internal
  2369. This method is called by QCustomPlot to indicate that an ongoing selection rect interaction has
  2370. finished by the user releasing the mouse button. The default implementation deactivates the
  2371. selection rect and emits the \ref accepted signal.
  2372. */
  2373. void QCPSelectionRect::endSelection(QMouseEvent *event)
  2374. {
  2375. mRect.setBottomRight(event->pos());
  2376. mActive = false;
  2377. emit accepted(mRect, event);
  2378. }
  2379. /*! \internal
  2380. This method is called by QCustomPlot when a key has been pressed by the user while the selection
  2381. rect interaction is active. The default implementation allows to \ref cancel the interaction by
  2382. hitting the escape key.
  2383. */
  2384. void QCPSelectionRect::keyPressEvent(QKeyEvent *event)
  2385. {
  2386. if (event->key() == Qt::Key_Escape && mActive)
  2387. {
  2388. mActive = false;
  2389. emit canceled(mRect, event);
  2390. }
  2391. }
  2392. /* inherits documentation from base class */
  2393. void QCPSelectionRect::applyDefaultAntialiasingHint(QCPPainter *painter) const
  2394. {
  2395. applyAntialiasingHint(painter, mAntialiased, QCP::aeOther);
  2396. }
  2397. /*! \internal
  2398. If the selection rect is active (\ref isActive), draws the selection rect defined by \a mRect.
  2399. \seebaseclassmethod
  2400. */
  2401. void QCPSelectionRect::draw(QCPPainter *painter)
  2402. {
  2403. if (mActive)
  2404. {
  2405. painter->setPen(mPen);
  2406. painter->setBrush(mBrush);
  2407. painter->drawRect(mRect);
  2408. }
  2409. }
  2410. /* end of 'src/selectionrect.cpp' */
  2411. /* including file 'src/layout.cpp', size 79064 */
  2412. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  2413. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2414. //////////////////// QCPMarginGroup
  2415. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2416. /*! \class QCPMarginGroup
  2417. \brief A margin group allows synchronization of margin sides if working with multiple layout elements.
  2418. QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that
  2419. they will all have the same size, based on the largest required margin in the group.
  2420. \n
  2421. \image html QCPMarginGroup.png "Demonstration of QCPMarginGroup"
  2422. \n
  2423. In certain situations it is desirable that margins at specific sides are synchronized across
  2424. layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will
  2425. provide a cleaner look to the user if the left and right margins of the two axis rects are of the
  2426. same size. The left axis of the top axis rect will then be at the same horizontal position as the
  2427. left axis of the lower axis rect, making them appear aligned. The same applies for the right
  2428. axes. This is what QCPMarginGroup makes possible.
  2429. To add/remove a specific side of a layout element to/from a margin group, use the \ref
  2430. QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call
  2431. \ref clear, or just delete the margin group.
  2432. \section QCPMarginGroup-example Example
  2433. First create a margin group:
  2434. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-1
  2435. Then set this group on the layout element sides:
  2436. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-2
  2437. Here, we've used the first two axis rects of the plot and synchronized their left margins with
  2438. each other and their right margins with each other.
  2439. */
  2440. /* start documentation of inline functions */
  2441. /*! \fn QList<QCPLayoutElement*> QCPMarginGroup::elements(QCP::MarginSide side) const
  2442. Returns a list of all layout elements that have their margin \a side associated with this margin
  2443. group.
  2444. */
  2445. /* end documentation of inline functions */
  2446. /*!
  2447. Creates a new QCPMarginGroup instance in \a parentPlot.
  2448. */
  2449. QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) :
  2450. QObject(parentPlot),
  2451. mParentPlot(parentPlot)
  2452. {
  2453. mChildren.insert(QCP::msLeft, QList<QCPLayoutElement*>());
  2454. mChildren.insert(QCP::msRight, QList<QCPLayoutElement*>());
  2455. mChildren.insert(QCP::msTop, QList<QCPLayoutElement*>());
  2456. mChildren.insert(QCP::msBottom, QList<QCPLayoutElement*>());
  2457. }
  2458. QCPMarginGroup::~QCPMarginGroup()
  2459. {
  2460. clear();
  2461. }
  2462. /*!
  2463. Returns whether this margin group is empty. If this function returns true, no layout elements use
  2464. this margin group to synchronize margin sides.
  2465. */
  2466. bool QCPMarginGroup::isEmpty() const
  2467. {
  2468. QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
  2469. while (it.hasNext())
  2470. {
  2471. it.next();
  2472. if (!it.value().isEmpty())
  2473. return false;
  2474. }
  2475. return true;
  2476. }
  2477. /*!
  2478. Clears this margin group. The synchronization of the margin sides that use this margin group is
  2479. lifted and they will use their individual margin sizes again.
  2480. */
  2481. void QCPMarginGroup::clear()
  2482. {
  2483. // make all children remove themselves from this margin group:
  2484. QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
  2485. while (it.hasNext())
  2486. {
  2487. it.next();
  2488. const QList<QCPLayoutElement*> elements = it.value();
  2489. for (int i=elements.size()-1; i>=0; --i)
  2490. elements.at(i)->setMarginGroup(it.key(), 0); // removes itself from mChildren via removeChild
  2491. }
  2492. }
  2493. /*! \internal
  2494. Returns the synchronized common margin for \a side. This is the margin value that will be used by
  2495. the layout element on the respective side, if it is part of this margin group.
  2496. The common margin is calculated by requesting the automatic margin (\ref
  2497. QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin
  2498. group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into
  2499. account, too.)
  2500. */
  2501. int QCPMarginGroup::commonMargin(QCP::MarginSide side) const
  2502. {
  2503. // query all automatic margins of the layout elements in this margin group side and find maximum:
  2504. int result = 0;
  2505. const QList<QCPLayoutElement*> elements = mChildren.value(side);
  2506. for (int i=0; i<elements.size(); ++i)
  2507. {
  2508. if (!elements.at(i)->autoMargins().testFlag(side))
  2509. continue;
  2510. int m = qMax(elements.at(i)->calculateAutoMargin(side), QCP::getMarginValue(elements.at(i)->minimumMargins(), side));
  2511. if (m > result)
  2512. result = m;
  2513. }
  2514. return result;
  2515. }
  2516. /*! \internal
  2517. Adds \a element to the internal list of child elements, for the margin \a side.
  2518. This function does not modify the margin group property of \a element.
  2519. */
  2520. void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element)
  2521. {
  2522. if (!mChildren[side].contains(element))
  2523. mChildren[side].append(element);
  2524. else
  2525. qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast<quintptr>(element);
  2526. }
  2527. /*! \internal
  2528. Removes \a element from the internal list of child elements, for the margin \a side.
  2529. This function does not modify the margin group property of \a element.
  2530. */
  2531. void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element)
  2532. {
  2533. if (!mChildren[side].removeOne(element))
  2534. qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast<quintptr>(element);
  2535. }
  2536. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2537. //////////////////// QCPLayoutElement
  2538. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2539. /*! \class QCPLayoutElement
  2540. \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system".
  2541. This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses.
  2542. A Layout element is a rectangular object which can be placed in layouts. It has an outer rect
  2543. (QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference
  2544. between outer and inner rect is called its margin. The margin can either be set to automatic or
  2545. manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be
  2546. set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic,
  2547. the layout element subclass will control the value itself (via \ref calculateAutoMargin).
  2548. Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level
  2549. layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref
  2550. QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested.
  2551. Thus in QCustomPlot one can divide layout elements into two categories: The ones that are
  2552. invisible by themselves, because they don't draw anything. Their only purpose is to manage the
  2553. position and size of other layout elements. This category of layout elements usually use
  2554. QCPLayout as base class. Then there is the category of layout elements which actually draw
  2555. something. For example, QCPAxisRect, QCPLegend and QCPTextElement are of this category. This does
  2556. not necessarily mean that the latter category can't have child layout elements. QCPLegend for
  2557. instance, actually derives from QCPLayoutGrid and the individual legend items are child layout
  2558. elements in the grid layout.
  2559. */
  2560. /* start documentation of inline functions */
  2561. /*! \fn QCPLayout *QCPLayoutElement::layout() const
  2562. Returns the parent layout of this layout element.
  2563. */
  2564. /*! \fn QRect QCPLayoutElement::rect() const
  2565. Returns the inner rect of this layout element. The inner rect is the outer rect (\ref outerRect, \ref
  2566. setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins).
  2567. In some cases, the area between outer and inner rect is left blank. In other cases the margin
  2568. area is used to display peripheral graphics while the main content is in the inner rect. This is
  2569. where automatic margin calculation becomes interesting because it allows the layout element to
  2570. adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect
  2571. draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if
  2572. \ref setAutoMargins is enabled) according to the space required by the labels of the axes.
  2573. \see outerRect
  2574. */
  2575. /*! \fn QRect QCPLayoutElement::outerRect() const
  2576. Returns the outer rect of this layout element. The outer rect is the inner rect expanded by the
  2577. margins (\ref setMargins, \ref setAutoMargins). The outer rect is used (and set via \ref
  2578. setOuterRect) by the parent \ref QCPLayout to control the size of this layout element.
  2579. \see rect
  2580. */
  2581. /* end documentation of inline functions */
  2582. /*!
  2583. Creates an instance of QCPLayoutElement and sets default values.
  2584. */
  2585. QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) :
  2586. QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout)
  2587. mParentLayout(0),
  2588. mMinimumSize(),
  2589. mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX),
  2590. mSizeConstraintRect(scrInnerRect),
  2591. mRect(0, 0, 0, 0),
  2592. mOuterRect(0, 0, 0, 0),
  2593. mMargins(0, 0, 0, 0),
  2594. mMinimumMargins(0, 0, 0, 0),
  2595. mAutoMargins(QCP::msAll)
  2596. {
  2597. }
  2598. QCPLayoutElement::~QCPLayoutElement()
  2599. {
  2600. setMarginGroup(QCP::msAll, 0); // unregister at margin groups, if there are any
  2601. // unregister at layout:
  2602. 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
  2603. mParentLayout->take(this);
  2604. }
  2605. /*!
  2606. Sets the outer rect of this layout element. If the layout element is inside a layout, the layout
  2607. sets the position and size of this layout element using this function.
  2608. Calling this function externally has no effect, since the layout will overwrite any changes to
  2609. the outer rect upon the next replot.
  2610. The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect.
  2611. \see rect
  2612. */
  2613. void QCPLayoutElement::setOuterRect(const QRect &rect)
  2614. {
  2615. if (mOuterRect != rect)
  2616. {
  2617. mOuterRect = rect;
  2618. mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
  2619. }
  2620. }
  2621. /*!
  2622. Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all
  2623. sides, this function is used to manually set the margin on those sides. Sides that are still set
  2624. to be handled automatically are ignored and may have any value in \a margins.
  2625. The margin is the distance between the outer rect (controlled by the parent layout via \ref
  2626. setOuterRect) and the inner \ref rect (which usually contains the main content of this layout
  2627. element).
  2628. \see setAutoMargins
  2629. */
  2630. void QCPLayoutElement::setMargins(const QMargins &margins)
  2631. {
  2632. if (mMargins != margins)
  2633. {
  2634. mMargins = margins;
  2635. mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
  2636. }
  2637. }
  2638. /*!
  2639. If \ref setAutoMargins is enabled on some or all margins, this function is used to provide
  2640. minimum values for those margins.
  2641. The minimum values are not enforced on margin sides that were set to be under manual control via
  2642. \ref setAutoMargins.
  2643. \see setAutoMargins
  2644. */
  2645. void QCPLayoutElement::setMinimumMargins(const QMargins &margins)
  2646. {
  2647. if (mMinimumMargins != margins)
  2648. {
  2649. mMinimumMargins = margins;
  2650. }
  2651. }
  2652. /*!
  2653. Sets on which sides the margin shall be calculated automatically. If a side is calculated
  2654. automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is
  2655. set to be controlled manually, the value may be specified with \ref setMargins.
  2656. Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref
  2657. setMarginGroup), to synchronize (align) it with other layout elements in the plot.
  2658. \see setMinimumMargins, setMargins, QCP::MarginSide
  2659. */
  2660. void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides)
  2661. {
  2662. mAutoMargins = sides;
  2663. }
  2664. /*!
  2665. Sets the minimum size of this layout element. A parent layout tries to respect the \a size here
  2666. by changing row/column sizes in the layout accordingly.
  2667. If the parent layout size is not sufficient to satisfy all minimum size constraints of its child
  2668. layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot
  2669. propagates the layout's size constraints to the outside by setting its own minimum QWidget size
  2670. accordingly, so violations of \a size should be exceptions.
  2671. Whether this constraint applies to the inner or the outer rect can be specified with \ref
  2672. setSizeConstraintRect (see \ref rect and \ref outerRect).
  2673. */
  2674. void QCPLayoutElement::setMinimumSize(const QSize &size)
  2675. {
  2676. if (mMinimumSize != size)
  2677. {
  2678. mMinimumSize = size;
  2679. if (mParentLayout)
  2680. mParentLayout->sizeConstraintsChanged();
  2681. }
  2682. }
  2683. /*! \overload
  2684. Sets the minimum size of this layout element.
  2685. Whether this constraint applies to the inner or the outer rect can be specified with \ref
  2686. setSizeConstraintRect (see \ref rect and \ref outerRect).
  2687. */
  2688. void QCPLayoutElement::setMinimumSize(int width, int height)
  2689. {
  2690. setMinimumSize(QSize(width, height));
  2691. }
  2692. /*!
  2693. Sets the maximum size of this layout element. A parent layout tries to respect the \a size here
  2694. by changing row/column sizes in the layout accordingly.
  2695. Whether this constraint applies to the inner or the outer rect can be specified with \ref
  2696. setSizeConstraintRect (see \ref rect and \ref outerRect).
  2697. */
  2698. void QCPLayoutElement::setMaximumSize(const QSize &size)
  2699. {
  2700. if (mMaximumSize != size)
  2701. {
  2702. mMaximumSize = size;
  2703. if (mParentLayout)
  2704. mParentLayout->sizeConstraintsChanged();
  2705. }
  2706. }
  2707. /*! \overload
  2708. Sets the maximum size of this layout element.
  2709. Whether this constraint applies to the inner or the outer rect can be specified with \ref
  2710. setSizeConstraintRect (see \ref rect and \ref outerRect).
  2711. */
  2712. void QCPLayoutElement::setMaximumSize(int width, int height)
  2713. {
  2714. setMaximumSize(QSize(width, height));
  2715. }
  2716. /*!
  2717. Sets to which rect of a layout element the size constraints apply. Size constraints can be set
  2718. via \ref setMinimumSize and \ref setMaximumSize.
  2719. The outer rect (\ref outerRect) includes the margins (e.g. in the case of a QCPAxisRect the axis
  2720. labels), whereas the inner rect (\ref rect) does not.
  2721. \see setMinimumSize, setMaximumSize
  2722. */
  2723. void QCPLayoutElement::setSizeConstraintRect(SizeConstraintRect constraintRect)
  2724. {
  2725. if (mSizeConstraintRect != constraintRect)
  2726. {
  2727. mSizeConstraintRect = constraintRect;
  2728. if (mParentLayout)
  2729. mParentLayout->sizeConstraintsChanged();
  2730. }
  2731. }
  2732. /*!
  2733. Sets the margin \a group of the specified margin \a sides.
  2734. Margin groups allow synchronizing specified margins across layout elements, see the documentation
  2735. of \ref QCPMarginGroup.
  2736. To unset the margin group of \a sides, set \a group to 0.
  2737. Note that margin groups only work for margin sides that are set to automatic (\ref
  2738. setAutoMargins).
  2739. \see QCP::MarginSide
  2740. */
  2741. void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group)
  2742. {
  2743. QVector<QCP::MarginSide> sideVector;
  2744. if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft);
  2745. if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight);
  2746. if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop);
  2747. if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom);
  2748. for (int i=0; i<sideVector.size(); ++i)
  2749. {
  2750. QCP::MarginSide side = sideVector.at(i);
  2751. if (marginGroup(side) != group)
  2752. {
  2753. QCPMarginGroup *oldGroup = marginGroup(side);
  2754. if (oldGroup) // unregister at old group
  2755. oldGroup->removeChild(side, this);
  2756. if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there
  2757. {
  2758. mMarginGroups.remove(side);
  2759. } else // setting to a new group
  2760. {
  2761. mMarginGroups[side] = group;
  2762. group->addChild(side, this);
  2763. }
  2764. }
  2765. }
  2766. }
  2767. /*!
  2768. Updates the layout element and sub-elements. This function is automatically called before every
  2769. replot by the parent layout element. It is called multiple times, once for every \ref
  2770. UpdatePhase. The phases are run through in the order of the enum values. For details about what
  2771. happens at the different phases, see the documentation of \ref UpdatePhase.
  2772. Layout elements that have child elements should call the \ref update method of their child
  2773. elements, and pass the current \a phase unchanged.
  2774. The default implementation executes the automatic margin mechanism in the \ref upMargins phase.
  2775. Subclasses should make sure to call the base class implementation.
  2776. */
  2777. void QCPLayoutElement::update(UpdatePhase phase)
  2778. {
  2779. if (phase == upMargins)
  2780. {
  2781. if (mAutoMargins != QCP::msNone)
  2782. {
  2783. // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group:
  2784. QMargins newMargins = mMargins;
  2785. QList<QCP::MarginSide> allMarginSides = QList<QCP::MarginSide>() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom;
  2786. foreach (QCP::MarginSide side, allMarginSides)
  2787. {
  2788. if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically
  2789. {
  2790. if (mMarginGroups.contains(side))
  2791. QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group
  2792. else
  2793. QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly
  2794. // apply minimum margin restrictions:
  2795. if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side))
  2796. QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side));
  2797. }
  2798. }
  2799. setMargins(newMargins);
  2800. }
  2801. }
  2802. }
  2803. /*!
  2804. Returns the suggested minimum size this layout element (the \ref outerRect) may be compressed to,
  2805. if no manual minimum size is set.
  2806. if a minimum size (\ref setMinimumSize) was not set manually, parent layouts use the returned size
  2807. (usually indirectly through \ref QCPLayout::getFinalMinimumOuterSize) to determine the minimum
  2808. allowed size of this layout element.
  2809. A manual minimum size is considered set if it is non-zero.
  2810. The default implementation simply returns the sum of the horizontal margins for the width and the
  2811. sum of the vertical margins for the height. Reimplementations may use their detailed knowledge
  2812. about the layout element's content to provide size hints.
  2813. */
  2814. QSize QCPLayoutElement::minimumOuterSizeHint() const
  2815. {
  2816. return QSize(mMargins.left()+mMargins.right(), mMargins.top()+mMargins.bottom());
  2817. }
  2818. /*!
  2819. Returns the suggested maximum size this layout element (the \ref outerRect) may be expanded to,
  2820. if no manual maximum size is set.
  2821. if a maximum size (\ref setMaximumSize) was not set manually, parent layouts use the returned
  2822. size (usually indirectly through \ref QCPLayout::getFinalMaximumOuterSize) to determine the
  2823. maximum allowed size of this layout element.
  2824. A manual maximum size is considered set if it is smaller than Qt's \c QWIDGETSIZE_MAX.
  2825. The default implementation simply returns \c QWIDGETSIZE_MAX for both width and height, implying
  2826. no suggested maximum size. Reimplementations may use their detailed knowledge about the layout
  2827. element's content to provide size hints.
  2828. */
  2829. QSize QCPLayoutElement::maximumOuterSizeHint() const
  2830. {
  2831. return QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
  2832. }
  2833. /*!
  2834. Returns a list of all child elements in this layout element. If \a recursive is true, all
  2835. sub-child elements are included in the list, too.
  2836. \warning There may be entries with value 0 in the returned list. (For example, QCPLayoutGrid may have
  2837. empty cells which yield 0 at the respective index.)
  2838. */
  2839. QList<QCPLayoutElement*> QCPLayoutElement::elements(bool recursive) const
  2840. {
  2841. Q_UNUSED(recursive)
  2842. return QList<QCPLayoutElement*>();
  2843. }
  2844. /*!
  2845. Layout elements are sensitive to events inside their outer rect. If \a pos is within the outer
  2846. rect, this method returns a value corresponding to 0.99 times the parent plot's selection
  2847. tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is
  2848. true, -1.0 is returned.
  2849. See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
  2850. QCPLayoutElement subclasses may reimplement this method to provide more specific selection test
  2851. behaviour.
  2852. */
  2853. double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  2854. {
  2855. Q_UNUSED(details)
  2856. if (onlySelectable)
  2857. return -1;
  2858. if (QRectF(mOuterRect).contains(pos))
  2859. {
  2860. if (mParentPlot)
  2861. return mParentPlot->selectionTolerance()*0.99;
  2862. else
  2863. {
  2864. qDebug() << Q_FUNC_INFO << "parent plot not defined";
  2865. return -1;
  2866. }
  2867. } else
  2868. return -1;
  2869. }
  2870. /*! \internal
  2871. propagates the parent plot initialization to all child elements, by calling \ref
  2872. QCPLayerable::initializeParentPlot on them.
  2873. */
  2874. void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot)
  2875. {
  2876. foreach (QCPLayoutElement* el, elements(false))
  2877. {
  2878. if (!el->parentPlot())
  2879. el->initializeParentPlot(parentPlot);
  2880. }
  2881. }
  2882. /*! \internal
  2883. Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a
  2884. side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the
  2885. returned value will not be smaller than the specified minimum margin.
  2886. The default implementation just returns the respective manual margin (\ref setMargins) or the
  2887. minimum margin, whichever is larger.
  2888. */
  2889. int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side)
  2890. {
  2891. return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side));
  2892. }
  2893. /*! \internal
  2894. This virtual method is called when this layout element was moved to a different QCPLayout, or
  2895. when this layout element has changed its logical position (e.g. row and/or column) within the
  2896. same QCPLayout. Subclasses may use this to react accordingly.
  2897. Since this method is called after the completion of the move, you can access the new parent
  2898. layout via \ref layout().
  2899. The default implementation does nothing.
  2900. */
  2901. void QCPLayoutElement::layoutChanged()
  2902. {
  2903. }
  2904. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2905. //////////////////// QCPLayout
  2906. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2907. /*! \class QCPLayout
  2908. \brief The abstract base class for layouts
  2909. This is an abstract base class for layout elements whose main purpose is to define the position
  2910. and size of other child layout elements. In most cases, layouts don't draw anything themselves
  2911. (but there are exceptions to this, e.g. QCPLegend).
  2912. QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts.
  2913. QCPLayout introduces a common interface for accessing and manipulating the child elements. Those
  2914. functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref
  2915. simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions
  2916. to this interface which are more specialized to the form of the layout. For example, \ref
  2917. QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid
  2918. more conveniently.
  2919. Since this is an abstract base class, you can't instantiate it directly. Rather use one of its
  2920. subclasses like QCPLayoutGrid or QCPLayoutInset.
  2921. For a general introduction to the layout system, see the dedicated documentation page \ref
  2922. thelayoutsystem "The Layout System".
  2923. */
  2924. /* start documentation of pure virtual functions */
  2925. /*! \fn virtual int QCPLayout::elementCount() const = 0
  2926. Returns the number of elements/cells in the layout.
  2927. \see elements, elementAt
  2928. */
  2929. /*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0
  2930. Returns the element in the cell with the given \a index. If \a index is invalid, returns 0.
  2931. Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g.
  2932. QCPLayoutGrid), so this function may return 0 in those cases. You may use this function to check
  2933. whether a cell is empty or not.
  2934. \see elements, elementCount, takeAt
  2935. */
  2936. /*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0
  2937. Removes the element with the given \a index from the layout and returns it.
  2938. If the \a index is invalid or the cell with that index is empty, returns 0.
  2939. Note that some layouts don't remove the respective cell right away but leave an empty cell after
  2940. successful removal of the layout element. To collapse empty cells, use \ref simplify.
  2941. \see elementAt, take
  2942. */
  2943. /*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0
  2944. Removes the specified \a element from the layout and returns true on success.
  2945. If the \a element isn't in this layout, returns false.
  2946. Note that some layouts don't remove the respective cell right away but leave an empty cell after
  2947. successful removal of the layout element. To collapse empty cells, use \ref simplify.
  2948. \see takeAt
  2949. */
  2950. /* end documentation of pure virtual functions */
  2951. /*!
  2952. Creates an instance of QCPLayout and sets default values. Note that since QCPLayout
  2953. is an abstract base class, it can't be instantiated directly.
  2954. */
  2955. QCPLayout::QCPLayout()
  2956. {
  2957. }
  2958. /*!
  2959. If \a phase is \ref upLayout, calls \ref updateLayout, which subclasses may reimplement to
  2960. reposition and resize their cells.
  2961. Finally, the call is propagated down to all child \ref QCPLayoutElement "QCPLayoutElements".
  2962. For details about this method and the update phases, see the documentation of \ref
  2963. QCPLayoutElement::update.
  2964. */
  2965. void QCPLayout::update(UpdatePhase phase)
  2966. {
  2967. QCPLayoutElement::update(phase);
  2968. // set child element rects according to layout:
  2969. if (phase == upLayout)
  2970. updateLayout();
  2971. // propagate update call to child elements:
  2972. const int elCount = elementCount();
  2973. for (int i=0; i<elCount; ++i)
  2974. {
  2975. if (QCPLayoutElement *el = elementAt(i))
  2976. el->update(phase);
  2977. }
  2978. }
  2979. /* inherits documentation from base class */
  2980. QList<QCPLayoutElement*> QCPLayout::elements(bool recursive) const
  2981. {
  2982. const int c = elementCount();
  2983. QList<QCPLayoutElement*> result;
  2984. #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
  2985. result.reserve(c);
  2986. #endif
  2987. for (int i=0; i<c; ++i)
  2988. result.append(elementAt(i));
  2989. if (recursive)
  2990. {
  2991. for (int i=0; i<c; ++i)
  2992. {
  2993. if (result.at(i))
  2994. result << result.at(i)->elements(recursive);
  2995. }
  2996. }
  2997. return result;
  2998. }
  2999. /*!
  3000. Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the
  3001. default implementation does nothing.
  3002. Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit
  3003. simplification while QCPLayoutGrid does.
  3004. */
  3005. void QCPLayout::simplify()
  3006. {
  3007. }
  3008. /*!
  3009. Removes and deletes the element at the provided \a index. Returns true on success. If \a index is
  3010. invalid or points to an empty cell, returns false.
  3011. This function internally uses \ref takeAt to remove the element from the layout and then deletes
  3012. the returned element. Note that some layouts don't remove the respective cell right away but leave an
  3013. empty cell after successful removal of the layout element. To collapse empty cells, use \ref
  3014. simplify.
  3015. \see remove, takeAt
  3016. */
  3017. bool QCPLayout::removeAt(int index)
  3018. {
  3019. if (QCPLayoutElement *el = takeAt(index))
  3020. {
  3021. delete el;
  3022. return true;
  3023. } else
  3024. return false;
  3025. }
  3026. /*!
  3027. Removes and deletes the provided \a element. Returns true on success. If \a element is not in the
  3028. layout, returns false.
  3029. This function internally uses \ref takeAt to remove the element from the layout and then deletes
  3030. the element. Note that some layouts don't remove the respective cell right away but leave an
  3031. empty cell after successful removal of the layout element. To collapse empty cells, use \ref
  3032. simplify.
  3033. \see removeAt, take
  3034. */
  3035. bool QCPLayout::remove(QCPLayoutElement *element)
  3036. {
  3037. if (take(element))
  3038. {
  3039. delete element;
  3040. return true;
  3041. } else
  3042. return false;
  3043. }
  3044. /*!
  3045. Removes and deletes all layout elements in this layout. Finally calls \ref simplify to make sure
  3046. all empty cells are collapsed.
  3047. \see remove, removeAt
  3048. */
  3049. void QCPLayout::clear()
  3050. {
  3051. for (int i=elementCount()-1; i>=0; --i)
  3052. {
  3053. if (elementAt(i))
  3054. removeAt(i);
  3055. }
  3056. simplify();
  3057. }
  3058. /*!
  3059. Subclasses call this method to report changed (minimum/maximum) size constraints.
  3060. If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref
  3061. sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of
  3062. QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout,
  3063. it may update itself and resize cells accordingly.
  3064. */
  3065. void QCPLayout::sizeConstraintsChanged() const
  3066. {
  3067. if (QWidget *w = qobject_cast<QWidget*>(parent()))
  3068. w->updateGeometry();
  3069. else if (QCPLayout *l = qobject_cast<QCPLayout*>(parent()))
  3070. l->sizeConstraintsChanged();
  3071. }
  3072. /*! \internal
  3073. Subclasses reimplement this method to update the position and sizes of the child elements/cells
  3074. via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing.
  3075. The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay
  3076. within that rect.
  3077. \ref getSectionSizes may help with the reimplementation of this function.
  3078. \see update
  3079. */
  3080. void QCPLayout::updateLayout()
  3081. {
  3082. }
  3083. /*! \internal
  3084. Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the
  3085. \ref QCPLayerable::parentLayerable and the QObject parent to this layout.
  3086. Further, if \a el didn't previously have a parent plot, calls \ref
  3087. QCPLayerable::initializeParentPlot on \a el to set the paret plot.
  3088. This method is used by subclass specific methods that add elements to the layout. Note that this
  3089. method only changes properties in \a el. The removal from the old layout and the insertion into
  3090. the new layout must be done additionally.
  3091. */
  3092. void QCPLayout::adoptElement(QCPLayoutElement *el)
  3093. {
  3094. if (el)
  3095. {
  3096. el->mParentLayout = this;
  3097. el->setParentLayerable(this);
  3098. el->setParent(this);
  3099. if (!el->parentPlot())
  3100. el->initializeParentPlot(mParentPlot);
  3101. el->layoutChanged();
  3102. } else
  3103. qDebug() << Q_FUNC_INFO << "Null element passed";
  3104. }
  3105. /*! \internal
  3106. Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout
  3107. and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent
  3108. QCustomPlot.
  3109. This method is used by subclass specific methods that remove elements from the layout (e.g. \ref
  3110. take or \ref takeAt). Note that this method only changes properties in \a el. The removal from
  3111. the old layout must be done additionally.
  3112. */
  3113. void QCPLayout::releaseElement(QCPLayoutElement *el)
  3114. {
  3115. if (el)
  3116. {
  3117. el->mParentLayout = 0;
  3118. el->setParentLayerable(0);
  3119. el->setParent(mParentPlot);
  3120. // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot
  3121. } else
  3122. qDebug() << Q_FUNC_INFO << "Null element passed";
  3123. }
  3124. /*! \internal
  3125. This is a helper function for the implementation of \ref updateLayout in subclasses.
  3126. It calculates the sizes of one-dimensional sections with provided constraints on maximum section
  3127. sizes, minimum section sizes, relative stretch factors and the final total size of all sections.
  3128. The QVector entries refer to the sections. Thus all QVectors must have the same size.
  3129. \a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size
  3130. imposed, set all vector values to Qt's QWIDGETSIZE_MAX.
  3131. \a minSizes gives the minimum allowed size of each section. If there shall be no minimum size
  3132. imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than
  3133. \a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words,
  3134. not exceeding the allowed total size is taken to be more important than not going below minimum
  3135. section sizes.)
  3136. \a stretchFactors give the relative proportions of the sections to each other. If all sections
  3137. shall be scaled equally, set all values equal. If the first section shall be double the size of
  3138. each individual other section, set the first number of \a stretchFactors to double the value of
  3139. the other individual values (e.g. {2, 1, 1, 1}).
  3140. \a totalSize is the value that the final section sizes will add up to. Due to rounding, the
  3141. actual sum may differ slightly. If you want the section sizes to sum up to exactly that value,
  3142. you could distribute the remaining difference on the sections.
  3143. The return value is a QVector containing the section sizes.
  3144. */
  3145. QVector<int> QCPLayout::getSectionSizes(QVector<int> maxSizes, QVector<int> minSizes, QVector<double> stretchFactors, int totalSize) const
  3146. {
  3147. if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size())
  3148. {
  3149. qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors;
  3150. return QVector<int>();
  3151. }
  3152. if (stretchFactors.isEmpty())
  3153. return QVector<int>();
  3154. int sectionCount = stretchFactors.size();
  3155. QVector<double> sectionSizes(sectionCount);
  3156. // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections):
  3157. int minSizeSum = 0;
  3158. for (int i=0; i<sectionCount; ++i)
  3159. minSizeSum += minSizes.at(i);
  3160. if (totalSize < minSizeSum)
  3161. {
  3162. // new stretch factors are minimum sizes and minimum sizes are set to zero:
  3163. for (int i=0; i<sectionCount; ++i)
  3164. {
  3165. stretchFactors[i] = minSizes.at(i);
  3166. minSizes[i] = 0;
  3167. }
  3168. }
  3169. QList<int> minimumLockedSections;
  3170. QList<int> unfinishedSections;
  3171. for (int i=0; i<sectionCount; ++i)
  3172. unfinishedSections.append(i);
  3173. double freeSize = totalSize;
  3174. int outerIterations = 0;
  3175. while (!unfinishedSections.isEmpty() && outerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
  3176. {
  3177. ++outerIterations;
  3178. int innerIterations = 0;
  3179. while (!unfinishedSections.isEmpty() && innerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
  3180. {
  3181. ++innerIterations;
  3182. // find section that hits its maximum next:
  3183. int nextId = -1;
  3184. double nextMax = 1e12;
  3185. for (int i=0; i<unfinishedSections.size(); ++i)
  3186. {
  3187. int secId = unfinishedSections.at(i);
  3188. double hitsMaxAt = (maxSizes.at(secId)-sectionSizes.at(secId))/stretchFactors.at(secId);
  3189. if (hitsMaxAt < nextMax)
  3190. {
  3191. nextMax = hitsMaxAt;
  3192. nextId = secId;
  3193. }
  3194. }
  3195. // 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
  3196. // actually hits its maximum, without exceeding the total size when we add up all sections)
  3197. double stretchFactorSum = 0;
  3198. for (int i=0; i<unfinishedSections.size(); ++i)
  3199. stretchFactorSum += stretchFactors.at(unfinishedSections.at(i));
  3200. double nextMaxLimit = freeSize/stretchFactorSum;
  3201. if (nextMax < nextMaxLimit) // next maximum is actually hit, move forward to that point and fix the size of that section
  3202. {
  3203. for (int i=0; i<unfinishedSections.size(); ++i)
  3204. {
  3205. sectionSizes[unfinishedSections.at(i)] += nextMax*stretchFactors.at(unfinishedSections.at(i)); // increment all sections
  3206. freeSize -= nextMax*stretchFactors.at(unfinishedSections.at(i));
  3207. }
  3208. unfinishedSections.removeOne(nextId); // exclude the section that is now at maximum from further changes
  3209. } else // next maximum isn't hit, just distribute rest of free space on remaining sections
  3210. {
  3211. for (int i=0; i<unfinishedSections.size(); ++i)
  3212. sectionSizes[unfinishedSections.at(i)] += nextMaxLimit*stretchFactors.at(unfinishedSections.at(i)); // increment all sections
  3213. unfinishedSections.clear();
  3214. }
  3215. }
  3216. if (innerIterations == sectionCount*2)
  3217. qDebug() << Q_FUNC_INFO << "Exceeded maximum expected inner iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
  3218. // now check whether the resulting section sizes violate minimum restrictions:
  3219. bool foundMinimumViolation = false;
  3220. for (int i=0; i<sectionSizes.size(); ++i)
  3221. {
  3222. if (minimumLockedSections.contains(i))
  3223. continue;
  3224. if (sectionSizes.at(i) < minSizes.at(i)) // section violates minimum
  3225. {
  3226. sectionSizes[i] = minSizes.at(i); // set it to minimum
  3227. foundMinimumViolation = true; // make sure we repeat the whole optimization process
  3228. minimumLockedSections.append(i);
  3229. }
  3230. }
  3231. if (foundMinimumViolation)
  3232. {
  3233. freeSize = totalSize;
  3234. for (int i=0; i<sectionCount; ++i)
  3235. {
  3236. if (!minimumLockedSections.contains(i)) // only put sections that haven't hit their minimum back into the pool
  3237. unfinishedSections.append(i);
  3238. else
  3239. freeSize -= sectionSizes.at(i); // remove size of minimum locked sections from available space in next round
  3240. }
  3241. // reset all section sizes to zero that are in unfinished sections (all others have been set to their minimum):
  3242. for (int i=0; i<unfinishedSections.size(); ++i)
  3243. sectionSizes[unfinishedSections.at(i)] = 0;
  3244. }
  3245. }
  3246. if (outerIterations == sectionCount*2)
  3247. qDebug() << Q_FUNC_INFO << "Exceeded maximum expected outer iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
  3248. QVector<int> result(sectionCount);
  3249. for (int i=0; i<sectionCount; ++i)
  3250. result[i] = qRound(sectionSizes.at(i));
  3251. return result;
  3252. }
  3253. /*! \internal
  3254. This is a helper function for the implementation of subclasses.
  3255. It returns the minimum size that should finally be used for the outer rect of the passed layout
  3256. element \a el.
  3257. It takes into account whether a manual minimum size is set (\ref
  3258. QCPLayoutElement::setMinimumSize), which size constraint is set (\ref
  3259. QCPLayoutElement::setSizeConstraintRect), as well as the minimum size hint, if no manual minimum
  3260. size was set (\ref QCPLayoutElement::minimumOuterSizeHint).
  3261. */
  3262. QSize QCPLayout::getFinalMinimumOuterSize(const QCPLayoutElement *el)
  3263. {
  3264. QSize minOuterHint = el->minimumOuterSizeHint();
  3265. QSize minOuter = el->minimumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset minimum of 0)
  3266. if (minOuter.width() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
  3267. minOuter.rwidth() += el->margins().left() + el->margins().right();
  3268. if (minOuter.height() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
  3269. minOuter.rheight() += el->margins().top() + el->margins().bottom();
  3270. return QSize(minOuter.width() > 0 ? minOuter.width() : minOuterHint.width(),
  3271. minOuter.height() > 0 ? minOuter.height() : minOuterHint.height());;
  3272. }
  3273. /*! \internal
  3274. This is a helper function for the implementation of subclasses.
  3275. It returns the maximum size that should finally be used for the outer rect of the passed layout
  3276. element \a el.
  3277. It takes into account whether a manual maximum size is set (\ref
  3278. QCPLayoutElement::setMaximumSize), which size constraint is set (\ref
  3279. QCPLayoutElement::setSizeConstraintRect), as well as the maximum size hint, if no manual maximum
  3280. size was set (\ref QCPLayoutElement::maximumOuterSizeHint).
  3281. */
  3282. QSize QCPLayout::getFinalMaximumOuterSize(const QCPLayoutElement *el)
  3283. {
  3284. QSize maxOuterHint = el->maximumOuterSizeHint();
  3285. QSize maxOuter = el->maximumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset maximum of QWIDGETSIZE_MAX)
  3286. if (maxOuter.width() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
  3287. maxOuter.rwidth() += el->margins().left() + el->margins().right();
  3288. if (maxOuter.height() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
  3289. maxOuter.rheight() += el->margins().top() + el->margins().bottom();
  3290. return QSize(maxOuter.width() < QWIDGETSIZE_MAX ? maxOuter.width() : maxOuterHint.width(),
  3291. maxOuter.height() < QWIDGETSIZE_MAX ? maxOuter.height() : maxOuterHint.height());
  3292. }
  3293. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3294. //////////////////// QCPLayoutGrid
  3295. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3296. /*! \class QCPLayoutGrid
  3297. \brief A layout that arranges child elements in a grid
  3298. Elements are laid out in a grid with configurable stretch factors (\ref setColumnStretchFactor,
  3299. \ref setRowStretchFactor) and spacing (\ref setColumnSpacing, \ref setRowSpacing).
  3300. Elements can be added to cells via \ref addElement. The grid is expanded if the specified row or
  3301. column doesn't exist yet. Whether a cell contains a valid layout element can be checked with \ref
  3302. hasElement, that element can be retrieved with \ref element. If rows and columns that only have
  3303. empty cells shall be removed, call \ref simplify. Removal of elements is either done by just
  3304. adding the element to a different layout or by using the QCPLayout interface \ref take or \ref
  3305. remove.
  3306. If you use \ref addElement(QCPLayoutElement*) without explicit parameters for \a row and \a
  3307. column, the grid layout will choose the position according to the current \ref setFillOrder and
  3308. the wrapping (\ref setWrap).
  3309. Row and column insertion can be performed with \ref insertRow and \ref insertColumn.
  3310. */
  3311. /* start documentation of inline functions */
  3312. /*! \fn int QCPLayoutGrid::rowCount() const
  3313. Returns the number of rows in the layout.
  3314. \see columnCount
  3315. */
  3316. /*! \fn int QCPLayoutGrid::columnCount() const
  3317. Returns the number of columns in the layout.
  3318. \see rowCount
  3319. */
  3320. /* end documentation of inline functions */
  3321. /*!
  3322. Creates an instance of QCPLayoutGrid and sets default values.
  3323. */
  3324. QCPLayoutGrid::QCPLayoutGrid() :
  3325. mColumnSpacing(5),
  3326. mRowSpacing(5),
  3327. mWrap(0),
  3328. mFillOrder(foRowsFirst)
  3329. {
  3330. }
  3331. QCPLayoutGrid::~QCPLayoutGrid()
  3332. {
  3333. // clear all child layout elements. This is important because only the specific layouts know how
  3334. // to handle removing elements (clear calls virtual removeAt method to do that).
  3335. clear();
  3336. }
  3337. /*!
  3338. Returns the element in the cell in \a row and \a column.
  3339. Returns 0 if either the row/column is invalid or if the cell is empty. In those cases, a qDebug
  3340. message is printed. To check whether a cell exists and isn't empty, use \ref hasElement.
  3341. \see addElement, hasElement
  3342. */
  3343. QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const
  3344. {
  3345. if (row >= 0 && row < mElements.size())
  3346. {
  3347. if (column >= 0 && column < mElements.first().size())
  3348. {
  3349. if (QCPLayoutElement *result = mElements.at(row).at(column))
  3350. return result;
  3351. else
  3352. qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column;
  3353. } else
  3354. qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column;
  3355. } else
  3356. qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column;
  3357. return 0;
  3358. }
  3359. /*! \overload
  3360. Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it
  3361. is first removed from there. If \a row or \a column don't exist yet, the layout is expanded
  3362. accordingly.
  3363. Returns true if the element was added successfully, i.e. if the cell at \a row and \a column
  3364. didn't already have an element.
  3365. Use the overload of this method without explicit row/column index to place the element according
  3366. to the configured fill order and wrapping settings.
  3367. \see element, hasElement, take, remove
  3368. */
  3369. bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element)
  3370. {
  3371. if (!hasElement(row, column))
  3372. {
  3373. if (element && element->layout()) // remove from old layout first
  3374. element->layout()->take(element);
  3375. expandTo(row+1, column+1);
  3376. mElements[row][column] = element;
  3377. if (element)
  3378. adoptElement(element);
  3379. return true;
  3380. } else
  3381. qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column;
  3382. return false;
  3383. }
  3384. /*! \overload
  3385. Adds the \a element to the next empty cell according to the current fill order (\ref
  3386. setFillOrder) and wrapping (\ref setWrap). If \a element is already in a layout, it is first
  3387. removed from there. If necessary, the layout is expanded to hold the new element.
  3388. Returns true if the element was added successfully.
  3389. \see setFillOrder, setWrap, element, hasElement, take, remove
  3390. */
  3391. bool QCPLayoutGrid::addElement(QCPLayoutElement *element)
  3392. {
  3393. int rowIndex = 0;
  3394. int colIndex = 0;
  3395. if (mFillOrder == foColumnsFirst)
  3396. {
  3397. while (hasElement(rowIndex, colIndex))
  3398. {
  3399. ++colIndex;
  3400. if (colIndex >= mWrap && mWrap > 0)
  3401. {
  3402. colIndex = 0;
  3403. ++rowIndex;
  3404. }
  3405. }
  3406. } else
  3407. {
  3408. while (hasElement(rowIndex, colIndex))
  3409. {
  3410. ++rowIndex;
  3411. if (rowIndex >= mWrap && mWrap > 0)
  3412. {
  3413. rowIndex = 0;
  3414. ++colIndex;
  3415. }
  3416. }
  3417. }
  3418. return addElement(rowIndex, colIndex, element);
  3419. }
  3420. /*!
  3421. Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't
  3422. empty.
  3423. \see element
  3424. */
  3425. bool QCPLayoutGrid::hasElement(int row, int column)
  3426. {
  3427. if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount())
  3428. return mElements.at(row).at(column);
  3429. else
  3430. return false;
  3431. }
  3432. /*!
  3433. Sets the stretch \a factor of \a column.
  3434. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  3435. their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
  3436. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
  3437. QCPLayoutElement::setSizeConstraintRect.)
  3438. The default stretch factor of newly created rows/columns is 1.
  3439. \see setColumnStretchFactors, setRowStretchFactor
  3440. */
  3441. void QCPLayoutGrid::setColumnStretchFactor(int column, double factor)
  3442. {
  3443. if (column >= 0 && column < columnCount())
  3444. {
  3445. if (factor > 0)
  3446. mColumnStretchFactors[column] = factor;
  3447. else
  3448. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
  3449. } else
  3450. qDebug() << Q_FUNC_INFO << "Invalid column:" << column;
  3451. }
  3452. /*!
  3453. Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount.
  3454. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  3455. their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
  3456. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
  3457. QCPLayoutElement::setSizeConstraintRect.)
  3458. The default stretch factor of newly created rows/columns is 1.
  3459. \see setColumnStretchFactor, setRowStretchFactors
  3460. */
  3461. void QCPLayoutGrid::setColumnStretchFactors(const QList<double> &factors)
  3462. {
  3463. if (factors.size() == mColumnStretchFactors.size())
  3464. {
  3465. mColumnStretchFactors = factors;
  3466. for (int i=0; i<mColumnStretchFactors.size(); ++i)
  3467. {
  3468. if (mColumnStretchFactors.at(i) <= 0)
  3469. {
  3470. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mColumnStretchFactors.at(i);
  3471. mColumnStretchFactors[i] = 1;
  3472. }
  3473. }
  3474. } else
  3475. qDebug() << Q_FUNC_INFO << "Column count not equal to passed stretch factor count:" << factors;
  3476. }
  3477. /*!
  3478. Sets the stretch \a factor of \a row.
  3479. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  3480. their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
  3481. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
  3482. QCPLayoutElement::setSizeConstraintRect.)
  3483. The default stretch factor of newly created rows/columns is 1.
  3484. \see setColumnStretchFactors, setRowStretchFactor
  3485. */
  3486. void QCPLayoutGrid::setRowStretchFactor(int row, double factor)
  3487. {
  3488. if (row >= 0 && row < rowCount())
  3489. {
  3490. if (factor > 0)
  3491. mRowStretchFactors[row] = factor;
  3492. else
  3493. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
  3494. } else
  3495. qDebug() << Q_FUNC_INFO << "Invalid row:" << row;
  3496. }
  3497. /*!
  3498. Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount.
  3499. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  3500. their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
  3501. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
  3502. QCPLayoutElement::setSizeConstraintRect.)
  3503. The default stretch factor of newly created rows/columns is 1.
  3504. \see setRowStretchFactor, setColumnStretchFactors
  3505. */
  3506. void QCPLayoutGrid::setRowStretchFactors(const QList<double> &factors)
  3507. {
  3508. if (factors.size() == mRowStretchFactors.size())
  3509. {
  3510. mRowStretchFactors = factors;
  3511. for (int i=0; i<mRowStretchFactors.size(); ++i)
  3512. {
  3513. if (mRowStretchFactors.at(i) <= 0)
  3514. {
  3515. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mRowStretchFactors.at(i);
  3516. mRowStretchFactors[i] = 1;
  3517. }
  3518. }
  3519. } else
  3520. qDebug() << Q_FUNC_INFO << "Row count not equal to passed stretch factor count:" << factors;
  3521. }
  3522. /*!
  3523. Sets the gap that is left blank between columns to \a pixels.
  3524. \see setRowSpacing
  3525. */
  3526. void QCPLayoutGrid::setColumnSpacing(int pixels)
  3527. {
  3528. mColumnSpacing = pixels;
  3529. }
  3530. /*!
  3531. Sets the gap that is left blank between rows to \a pixels.
  3532. \see setColumnSpacing
  3533. */
  3534. void QCPLayoutGrid::setRowSpacing(int pixels)
  3535. {
  3536. mRowSpacing = pixels;
  3537. }
  3538. /*!
  3539. Sets the maximum number of columns or rows that are used, before new elements added with \ref
  3540. addElement(QCPLayoutElement*) will start to fill the next row or column, respectively. It depends
  3541. on \ref setFillOrder, whether rows or columns are wrapped.
  3542. If \a count is set to zero, no wrapping will ever occur.
  3543. If you wish to re-wrap the elements currently in the layout, call \ref setFillOrder with \a
  3544. rearrange set to true (the actual fill order doesn't need to be changed for the rearranging to be
  3545. done).
  3546. Note that the method \ref addElement(int row, int column, QCPLayoutElement *element) with
  3547. explicitly stated row and column is not subject to wrapping and can place elements even beyond
  3548. the specified wrapping point.
  3549. \see setFillOrder
  3550. */
  3551. void QCPLayoutGrid::setWrap(int count)
  3552. {
  3553. mWrap = qMax(0, count);
  3554. }
  3555. /*!
  3556. Sets the filling order and wrapping behaviour that is used when adding new elements with the
  3557. method \ref addElement(QCPLayoutElement*).
  3558. The specified \a order defines whether rows or columns are filled first. Using \ref setWrap, you
  3559. can control at which row/column count wrapping into the next column/row will occur. If you set it
  3560. to zero, no wrapping will ever occur. Changing the fill order also changes the meaning of the
  3561. linear index used e.g. in \ref elementAt and \ref takeAt.
  3562. If you want to have all current elements arranged in the new order, set \a rearrange to true. The
  3563. elements will be rearranged in a way that tries to preserve their linear index. However, empty
  3564. cells are skipped during build-up of the new cell order, which shifts the succeeding element's
  3565. index. The rearranging is performed even if the specified \a order is already the current fill
  3566. order. Thus this method can be used to re-wrap the current elements.
  3567. If \a rearrange is false, the current element arrangement is not changed, which means the
  3568. linear indexes change (because the linear index is dependent on the fill order).
  3569. Note that the method \ref addElement(int row, int column, QCPLayoutElement *element) with
  3570. explicitly stated row and column is not subject to wrapping and can place elements even beyond
  3571. the specified wrapping point.
  3572. \see setWrap, addElement(QCPLayoutElement*)
  3573. */
  3574. void QCPLayoutGrid::setFillOrder(FillOrder order, bool rearrange)
  3575. {
  3576. // if rearranging, take all elements via linear index of old fill order:
  3577. const int elCount = elementCount();
  3578. QVector<QCPLayoutElement*> tempElements;
  3579. if (rearrange)
  3580. {
  3581. tempElements.reserve(elCount);
  3582. for (int i=0; i<elCount; ++i)
  3583. {
  3584. if (elementAt(i))
  3585. tempElements.append(takeAt(i));
  3586. }
  3587. simplify();
  3588. }
  3589. // change fill order as requested:
  3590. mFillOrder = order;
  3591. // if rearranging, re-insert via linear index according to new fill order:
  3592. if (rearrange)
  3593. {
  3594. for (int i=0; i<tempElements.size(); ++i)
  3595. addElement(tempElements.at(i));
  3596. }
  3597. }
  3598. /*!
  3599. Expands the layout to have \a newRowCount rows and \a newColumnCount columns. So the last valid
  3600. row index will be \a newRowCount-1, the last valid column index will be \a newColumnCount-1.
  3601. If the current column/row count is already larger or equal to \a newColumnCount/\a newRowCount,
  3602. this function does nothing in that dimension.
  3603. Newly created cells are empty, new rows and columns have the stretch factor 1.
  3604. Note that upon a call to \ref addElement, the layout is expanded automatically to contain the
  3605. specified row and column, using this function.
  3606. \see simplify
  3607. */
  3608. void QCPLayoutGrid::expandTo(int newRowCount, int newColumnCount)
  3609. {
  3610. // add rows as necessary:
  3611. while (rowCount() < newRowCount)
  3612. {
  3613. mElements.append(QList<QCPLayoutElement*>());
  3614. mRowStretchFactors.append(1);
  3615. }
  3616. // go through rows and expand columns as necessary:
  3617. int newColCount = qMax(columnCount(), newColumnCount);
  3618. for (int i=0; i<rowCount(); ++i)
  3619. {
  3620. while (mElements.at(i).size() < newColCount)
  3621. mElements[i].append(0);
  3622. }
  3623. while (mColumnStretchFactors.size() < newColCount)
  3624. mColumnStretchFactors.append(1);
  3625. }
  3626. /*!
  3627. Inserts a new row with empty cells at the row index \a newIndex. Valid values for \a newIndex
  3628. range from 0 (inserts a row at the top) to \a rowCount (appends a row at the bottom).
  3629. \see insertColumn
  3630. */
  3631. void QCPLayoutGrid::insertRow(int newIndex)
  3632. {
  3633. if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
  3634. {
  3635. expandTo(1, 1);
  3636. return;
  3637. }
  3638. if (newIndex < 0)
  3639. newIndex = 0;
  3640. if (newIndex > rowCount())
  3641. newIndex = rowCount();
  3642. mRowStretchFactors.insert(newIndex, 1);
  3643. QList<QCPLayoutElement*> newRow;
  3644. for (int col=0; col<columnCount(); ++col)
  3645. newRow.append((QCPLayoutElement*)0);
  3646. mElements.insert(newIndex, newRow);
  3647. }
  3648. /*!
  3649. Inserts a new column with empty cells at the column index \a newIndex. Valid values for \a
  3650. newIndex range from 0 (inserts a column at the left) to \a columnCount (appends a column at the
  3651. right).
  3652. \see insertRow
  3653. */
  3654. void QCPLayoutGrid::insertColumn(int newIndex)
  3655. {
  3656. if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
  3657. {
  3658. expandTo(1, 1);
  3659. return;
  3660. }
  3661. if (newIndex < 0)
  3662. newIndex = 0;
  3663. if (newIndex > columnCount())
  3664. newIndex = columnCount();
  3665. mColumnStretchFactors.insert(newIndex, 1);
  3666. for (int row=0; row<rowCount(); ++row)
  3667. mElements[row].insert(newIndex, (QCPLayoutElement*)0);
  3668. }
  3669. /*!
  3670. Converts the given \a row and \a column to the linear index used by some methods of \ref
  3671. QCPLayoutGrid and \ref QCPLayout.
  3672. The way the cells are indexed depends on \ref setFillOrder. If it is \ref foRowsFirst, the
  3673. indices increase left to right and then top to bottom. If it is \ref foColumnsFirst, the indices
  3674. increase top to bottom and then left to right.
  3675. For the returned index to be valid, \a row and \a column must be valid indices themselves, i.e.
  3676. greater or equal to zero and smaller than the current \ref rowCount/\ref columnCount.
  3677. \see indexToRowCol
  3678. */
  3679. int QCPLayoutGrid::rowColToIndex(int row, int column) const
  3680. {
  3681. if (row >= 0 && row < rowCount())
  3682. {
  3683. if (column >= 0 && column < columnCount())
  3684. {
  3685. switch (mFillOrder)
  3686. {
  3687. case foRowsFirst: return column*rowCount() + row;
  3688. case foColumnsFirst: return row*columnCount() + column;
  3689. }
  3690. } else
  3691. qDebug() << Q_FUNC_INFO << "row index out of bounds:" << row;
  3692. } else
  3693. qDebug() << Q_FUNC_INFO << "column index out of bounds:" << column;
  3694. return 0;
  3695. }
  3696. /*!
  3697. Converts the linear index to row and column indices and writes the result to \a row and \a
  3698. column.
  3699. The way the cells are indexed depends on \ref setFillOrder. If it is \ref foRowsFirst, the
  3700. indices increase left to right and then top to bottom. If it is \ref foColumnsFirst, the indices
  3701. increase top to bottom and then left to right.
  3702. If there are no cells (i.e. column or row count is zero), sets \a row and \a column to -1.
  3703. For the retrieved \a row and \a column to be valid, the passed \a index must be valid itself,
  3704. i.e. greater or equal to zero and smaller than the current \ref elementCount.
  3705. \see rowColToIndex
  3706. */
  3707. void QCPLayoutGrid::indexToRowCol(int index, int &row, int &column) const
  3708. {
  3709. row = -1;
  3710. column = -1;
  3711. const int nCols = columnCount();
  3712. const int nRows = rowCount();
  3713. if (nCols == 0 || nRows == 0)
  3714. return;
  3715. if (index < 0 || index >= elementCount())
  3716. {
  3717. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  3718. return;
  3719. }
  3720. switch (mFillOrder)
  3721. {
  3722. case foRowsFirst:
  3723. {
  3724. column = index / nRows;
  3725. row = index % nRows;
  3726. break;
  3727. }
  3728. case foColumnsFirst:
  3729. {
  3730. row = index / nCols;
  3731. column = index % nCols;
  3732. break;
  3733. }
  3734. }
  3735. }
  3736. /* inherits documentation from base class */
  3737. void QCPLayoutGrid::updateLayout()
  3738. {
  3739. QVector<int> minColWidths, minRowHeights, maxColWidths, maxRowHeights;
  3740. getMinimumRowColSizes(&minColWidths, &minRowHeights);
  3741. getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
  3742. int totalRowSpacing = (rowCount()-1) * mRowSpacing;
  3743. int totalColSpacing = (columnCount()-1) * mColumnSpacing;
  3744. QVector<int> colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing);
  3745. QVector<int> rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing);
  3746. // go through cells and set rects accordingly:
  3747. int yOffset = mRect.top();
  3748. for (int row=0; row<rowCount(); ++row)
  3749. {
  3750. if (row > 0)
  3751. yOffset += rowHeights.at(row-1)+mRowSpacing;
  3752. int xOffset = mRect.left();
  3753. for (int col=0; col<columnCount(); ++col)
  3754. {
  3755. if (col > 0)
  3756. xOffset += colWidths.at(col-1)+mColumnSpacing;
  3757. if (mElements.at(row).at(col))
  3758. mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row)));
  3759. }
  3760. }
  3761. }
  3762. /*!
  3763. \seebaseclassmethod
  3764. Note that the association of the linear \a index to the row/column based cells depends on the
  3765. current setting of \ref setFillOrder.
  3766. \see rowColToIndex
  3767. */
  3768. QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const
  3769. {
  3770. if (index >= 0 && index < elementCount())
  3771. {
  3772. int row, col;
  3773. indexToRowCol(index, row, col);
  3774. return mElements.at(row).at(col);
  3775. } else
  3776. return 0;
  3777. }
  3778. /*!
  3779. \seebaseclassmethod
  3780. Note that the association of the linear \a index to the row/column based cells depends on the
  3781. current setting of \ref setFillOrder.
  3782. \see rowColToIndex
  3783. */
  3784. QCPLayoutElement *QCPLayoutGrid::takeAt(int index)
  3785. {
  3786. if (QCPLayoutElement *el = elementAt(index))
  3787. {
  3788. releaseElement(el);
  3789. int row, col;
  3790. indexToRowCol(index, row, col);
  3791. mElements[row][col] = 0;
  3792. return el;
  3793. } else
  3794. {
  3795. qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
  3796. return 0;
  3797. }
  3798. }
  3799. /* inherits documentation from base class */
  3800. bool QCPLayoutGrid::take(QCPLayoutElement *element)
  3801. {
  3802. if (element)
  3803. {
  3804. for (int i=0; i<elementCount(); ++i)
  3805. {
  3806. if (elementAt(i) == element)
  3807. {
  3808. takeAt(i);
  3809. return true;
  3810. }
  3811. }
  3812. qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
  3813. } else
  3814. qDebug() << Q_FUNC_INFO << "Can't take null element";
  3815. return false;
  3816. }
  3817. /* inherits documentation from base class */
  3818. QList<QCPLayoutElement*> QCPLayoutGrid::elements(bool recursive) const
  3819. {
  3820. QList<QCPLayoutElement*> result;
  3821. const int elCount = elementCount();
  3822. #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
  3823. result.reserve(elCount);
  3824. #endif
  3825. for (int i=0; i<elCount; ++i)
  3826. result.append(elementAt(i));
  3827. if (recursive)
  3828. {
  3829. for (int i=0; i<elCount; ++i)
  3830. {
  3831. if (result.at(i))
  3832. result << result.at(i)->elements(recursive);
  3833. }
  3834. }
  3835. return result;
  3836. }
  3837. /*!
  3838. Simplifies the layout by collapsing rows and columns which only contain empty cells.
  3839. */
  3840. void QCPLayoutGrid::simplify()
  3841. {
  3842. // remove rows with only empty cells:
  3843. for (int row=rowCount()-1; row>=0; --row)
  3844. {
  3845. bool hasElements = false;
  3846. for (int col=0; col<columnCount(); ++col)
  3847. {
  3848. if (mElements.at(row).at(col))
  3849. {
  3850. hasElements = true;
  3851. break;
  3852. }
  3853. }
  3854. if (!hasElements)
  3855. {
  3856. mRowStretchFactors.removeAt(row);
  3857. mElements.removeAt(row);
  3858. if (mElements.isEmpty()) // removed last element, also remove stretch factor (wouldn't happen below because also columnCount changed to 0 now)
  3859. mColumnStretchFactors.clear();
  3860. }
  3861. }
  3862. // remove columns with only empty cells:
  3863. for (int col=columnCount()-1; col>=0; --col)
  3864. {
  3865. bool hasElements = false;
  3866. for (int row=0; row<rowCount(); ++row)
  3867. {
  3868. if (mElements.at(row).at(col))
  3869. {
  3870. hasElements = true;
  3871. break;
  3872. }
  3873. }
  3874. if (!hasElements)
  3875. {
  3876. mColumnStretchFactors.removeAt(col);
  3877. for (int row=0; row<rowCount(); ++row)
  3878. mElements[row].removeAt(col);
  3879. }
  3880. }
  3881. }
  3882. /* inherits documentation from base class */
  3883. QSize QCPLayoutGrid::minimumOuterSizeHint() const
  3884. {
  3885. QVector<int> minColWidths, minRowHeights;
  3886. getMinimumRowColSizes(&minColWidths, &minRowHeights);
  3887. QSize result(0, 0);
  3888. for (int i=0; i<minColWidths.size(); ++i)
  3889. result.rwidth() += minColWidths.at(i);
  3890. for (int i=0; i<minRowHeights.size(); ++i)
  3891. result.rheight() += minRowHeights.at(i);
  3892. result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing;
  3893. result.rheight() += qMax(0, rowCount()-1) * mRowSpacing;
  3894. result.rwidth() += mMargins.left()+mMargins.right();
  3895. result.rheight() += mMargins.top()+mMargins.bottom();
  3896. return result;
  3897. }
  3898. /* inherits documentation from base class */
  3899. QSize QCPLayoutGrid::maximumOuterSizeHint() const
  3900. {
  3901. QVector<int> maxColWidths, maxRowHeights;
  3902. getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
  3903. QSize result(0, 0);
  3904. for (int i=0; i<maxColWidths.size(); ++i)
  3905. result.setWidth(qMin(result.width()+maxColWidths.at(i), QWIDGETSIZE_MAX));
  3906. for (int i=0; i<maxRowHeights.size(); ++i)
  3907. result.setHeight(qMin(result.height()+maxRowHeights.at(i), QWIDGETSIZE_MAX));
  3908. result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing;
  3909. result.rheight() += qMax(0, rowCount()-1) * mRowSpacing;
  3910. result.rwidth() += mMargins.left()+mMargins.right();
  3911. result.rheight() += mMargins.top()+mMargins.bottom();
  3912. if (result.height() > QWIDGETSIZE_MAX)
  3913. result.setHeight(QWIDGETSIZE_MAX);
  3914. if (result.width() > QWIDGETSIZE_MAX)
  3915. result.setWidth(QWIDGETSIZE_MAX);
  3916. return result;
  3917. }
  3918. /*! \internal
  3919. Places the minimum column widths and row heights into \a minColWidths and \a minRowHeights
  3920. respectively.
  3921. The minimum height of a row is the largest minimum height of any element's outer rect in that
  3922. row. The minimum width of a column is the largest minimum width of any element's outer rect in
  3923. that column.
  3924. This is a helper function for \ref updateLayout.
  3925. \see getMaximumRowColSizes
  3926. */
  3927. void QCPLayoutGrid::getMinimumRowColSizes(QVector<int> *minColWidths, QVector<int> *minRowHeights) const
  3928. {
  3929. *minColWidths = QVector<int>(columnCount(), 0);
  3930. *minRowHeights = QVector<int>(rowCount(), 0);
  3931. for (int row=0; row<rowCount(); ++row)
  3932. {
  3933. for (int col=0; col<columnCount(); ++col)
  3934. {
  3935. if (QCPLayoutElement *el = mElements.at(row).at(col))
  3936. {
  3937. QSize minSize = getFinalMinimumOuterSize(el);
  3938. if (minColWidths->at(col) < minSize.width())
  3939. (*minColWidths)[col] = minSize.width();
  3940. if (minRowHeights->at(row) < minSize.height())
  3941. (*minRowHeights)[row] = minSize.height();
  3942. }
  3943. }
  3944. }
  3945. }
  3946. /*! \internal
  3947. Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights
  3948. respectively.
  3949. The maximum height of a row is the smallest maximum height of any element's outer rect in that
  3950. row. The maximum width of a column is the smallest maximum width of any element's outer rect in
  3951. that column.
  3952. This is a helper function for \ref updateLayout.
  3953. \see getMinimumRowColSizes
  3954. */
  3955. void QCPLayoutGrid::getMaximumRowColSizes(QVector<int> *maxColWidths, QVector<int> *maxRowHeights) const
  3956. {
  3957. *maxColWidths = QVector<int>(columnCount(), QWIDGETSIZE_MAX);
  3958. *maxRowHeights = QVector<int>(rowCount(), QWIDGETSIZE_MAX);
  3959. for (int row=0; row<rowCount(); ++row)
  3960. {
  3961. for (int col=0; col<columnCount(); ++col)
  3962. {
  3963. if (QCPLayoutElement *el = mElements.at(row).at(col))
  3964. {
  3965. QSize maxSize = getFinalMaximumOuterSize(el);
  3966. if (maxColWidths->at(col) > maxSize.width())
  3967. (*maxColWidths)[col] = maxSize.width();
  3968. if (maxRowHeights->at(row) > maxSize.height())
  3969. (*maxRowHeights)[row] = maxSize.height();
  3970. }
  3971. }
  3972. }
  3973. }
  3974. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3975. //////////////////// QCPLayoutInset
  3976. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3977. /*! \class QCPLayoutInset
  3978. \brief A layout that places child elements aligned to the border or arbitrarily positioned
  3979. Elements are placed either aligned to the border or at arbitrary position in the area of the
  3980. layout. Which placement applies is controlled with the \ref InsetPlacement (\ref
  3981. setInsetPlacement).
  3982. Elements are added via \ref addElement(QCPLayoutElement *element, Qt::Alignment alignment) or
  3983. addElement(QCPLayoutElement *element, const QRectF &rect). If the first method is used, the inset
  3984. placement will default to \ref ipBorderAligned and the element will be aligned according to the
  3985. \a alignment parameter. The second method defaults to \ref ipFree and allows placing elements at
  3986. arbitrary position and size, defined by \a rect.
  3987. The alignment or rect can be set via \ref setInsetAlignment or \ref setInsetRect, respectively.
  3988. This is the layout that every QCPAxisRect has as \ref QCPAxisRect::insetLayout.
  3989. */
  3990. /* start documentation of inline functions */
  3991. /*! \fn virtual void QCPLayoutInset::simplify()
  3992. The QCPInsetLayout does not need simplification since it can never have empty cells due to its
  3993. linear index structure. This method does nothing.
  3994. */
  3995. /* end documentation of inline functions */
  3996. /*!
  3997. Creates an instance of QCPLayoutInset and sets default values.
  3998. */
  3999. QCPLayoutInset::QCPLayoutInset()
  4000. {
  4001. }
  4002. QCPLayoutInset::~QCPLayoutInset()
  4003. {
  4004. // clear all child layout elements. This is important because only the specific layouts know how
  4005. // to handle removing elements (clear calls virtual removeAt method to do that).
  4006. clear();
  4007. }
  4008. /*!
  4009. Returns the placement type of the element with the specified \a index.
  4010. */
  4011. QCPLayoutInset::InsetPlacement QCPLayoutInset::insetPlacement(int index) const
  4012. {
  4013. if (elementAt(index))
  4014. return mInsetPlacement.at(index);
  4015. else
  4016. {
  4017. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4018. return ipFree;
  4019. }
  4020. }
  4021. /*!
  4022. Returns the alignment of the element with the specified \a index. The alignment only has a
  4023. meaning, if the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned.
  4024. */
  4025. Qt::Alignment QCPLayoutInset::insetAlignment(int index) const
  4026. {
  4027. if (elementAt(index))
  4028. return mInsetAlignment.at(index);
  4029. else
  4030. {
  4031. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4032. return 0;
  4033. }
  4034. }
  4035. /*!
  4036. Returns the rect of the element with the specified \a index. The rect only has a
  4037. meaning, if the inset placement (\ref setInsetPlacement) is \ref ipFree.
  4038. */
  4039. QRectF QCPLayoutInset::insetRect(int index) const
  4040. {
  4041. if (elementAt(index))
  4042. return mInsetRect.at(index);
  4043. else
  4044. {
  4045. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4046. return QRectF();
  4047. }
  4048. }
  4049. /*!
  4050. Sets the inset placement type of the element with the specified \a index to \a placement.
  4051. \see InsetPlacement
  4052. */
  4053. void QCPLayoutInset::setInsetPlacement(int index, QCPLayoutInset::InsetPlacement placement)
  4054. {
  4055. if (elementAt(index))
  4056. mInsetPlacement[index] = placement;
  4057. else
  4058. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4059. }
  4060. /*!
  4061. If the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned, this function
  4062. is used to set the alignment of the element with the specified \a index to \a alignment.
  4063. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
  4064. Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
  4065. alignment flags will be ignored.
  4066. */
  4067. void QCPLayoutInset::setInsetAlignment(int index, Qt::Alignment alignment)
  4068. {
  4069. if (elementAt(index))
  4070. mInsetAlignment[index] = alignment;
  4071. else
  4072. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4073. }
  4074. /*!
  4075. If the inset placement (\ref setInsetPlacement) is \ref ipFree, this function is used to set the
  4076. position and size of the element with the specified \a index to \a rect.
  4077. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
  4078. will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
  4079. corner of the layout, with 35% width and height of the parent layout.
  4080. Note that the minimum and maximum sizes of the embedded element (\ref
  4081. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize) are enforced.
  4082. */
  4083. void QCPLayoutInset::setInsetRect(int index, const QRectF &rect)
  4084. {
  4085. if (elementAt(index))
  4086. mInsetRect[index] = rect;
  4087. else
  4088. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4089. }
  4090. /* inherits documentation from base class */
  4091. void QCPLayoutInset::updateLayout()
  4092. {
  4093. for (int i=0; i<mElements.size(); ++i)
  4094. {
  4095. QCPLayoutElement *el = mElements.at(i);
  4096. QRect insetRect;
  4097. QSize finalMinSize = getFinalMinimumOuterSize(el);
  4098. QSize finalMaxSize = getFinalMaximumOuterSize(el);
  4099. if (mInsetPlacement.at(i) == ipFree)
  4100. {
  4101. insetRect = QRect(rect().x()+rect().width()*mInsetRect.at(i).x(),
  4102. rect().y()+rect().height()*mInsetRect.at(i).y(),
  4103. rect().width()*mInsetRect.at(i).width(),
  4104. rect().height()*mInsetRect.at(i).height());
  4105. if (insetRect.size().width() < finalMinSize.width())
  4106. insetRect.setWidth(finalMinSize.width());
  4107. if (insetRect.size().height() < finalMinSize.height())
  4108. insetRect.setHeight(finalMinSize.height());
  4109. if (insetRect.size().width() > finalMaxSize.width())
  4110. insetRect.setWidth(finalMaxSize.width());
  4111. if (insetRect.size().height() > finalMaxSize.height())
  4112. insetRect.setHeight(finalMaxSize.height());
  4113. } else if (mInsetPlacement.at(i) == ipBorderAligned)
  4114. {
  4115. insetRect.setSize(finalMinSize);
  4116. Qt::Alignment al = mInsetAlignment.at(i);
  4117. if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x());
  4118. else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width());
  4119. else insetRect.moveLeft(rect().x()+rect().width()*0.5-finalMinSize.width()*0.5); // default to Qt::AlignHCenter
  4120. if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y());
  4121. else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height());
  4122. else insetRect.moveTop(rect().y()+rect().height()*0.5-finalMinSize.height()*0.5); // default to Qt::AlignVCenter
  4123. }
  4124. mElements.at(i)->setOuterRect(insetRect);
  4125. }
  4126. }
  4127. /* inherits documentation from base class */
  4128. int QCPLayoutInset::elementCount() const
  4129. {
  4130. return mElements.size();
  4131. }
  4132. /* inherits documentation from base class */
  4133. QCPLayoutElement *QCPLayoutInset::elementAt(int index) const
  4134. {
  4135. if (index >= 0 && index < mElements.size())
  4136. return mElements.at(index);
  4137. else
  4138. return 0;
  4139. }
  4140. /* inherits documentation from base class */
  4141. QCPLayoutElement *QCPLayoutInset::takeAt(int index)
  4142. {
  4143. if (QCPLayoutElement *el = elementAt(index))
  4144. {
  4145. releaseElement(el);
  4146. mElements.removeAt(index);
  4147. mInsetPlacement.removeAt(index);
  4148. mInsetAlignment.removeAt(index);
  4149. mInsetRect.removeAt(index);
  4150. return el;
  4151. } else
  4152. {
  4153. qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
  4154. return 0;
  4155. }
  4156. }
  4157. /* inherits documentation from base class */
  4158. bool QCPLayoutInset::take(QCPLayoutElement *element)
  4159. {
  4160. if (element)
  4161. {
  4162. for (int i=0; i<elementCount(); ++i)
  4163. {
  4164. if (elementAt(i) == element)
  4165. {
  4166. takeAt(i);
  4167. return true;
  4168. }
  4169. }
  4170. qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
  4171. } else
  4172. qDebug() << Q_FUNC_INFO << "Can't take null element";
  4173. return false;
  4174. }
  4175. /*!
  4176. The inset layout is sensitive to events only at areas where its (visible) child elements are
  4177. sensitive. If the selectTest method of any of the child elements returns a positive number for \a
  4178. pos, this method returns a value corresponding to 0.99 times the parent plot's selection
  4179. tolerance. The inset layout is not selectable itself by default. So if \a onlySelectable is true,
  4180. -1.0 is returned.
  4181. See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
  4182. */
  4183. double QCPLayoutInset::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  4184. {
  4185. Q_UNUSED(details)
  4186. if (onlySelectable)
  4187. return -1;
  4188. for (int i=0; i<mElements.size(); ++i)
  4189. {
  4190. // inset layout shall only return positive selectTest, if actually an inset object is at pos
  4191. // else it would block the entire underlying QCPAxisRect with its surface.
  4192. if (mElements.at(i)->realVisibility() && mElements.at(i)->selectTest(pos, onlySelectable) >= 0)
  4193. return mParentPlot->selectionTolerance()*0.99;
  4194. }
  4195. return -1;
  4196. }
  4197. /*!
  4198. Adds the specified \a element to the layout as an inset aligned at the border (\ref
  4199. setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a
  4200. alignment.
  4201. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
  4202. Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
  4203. alignment flags will be ignored.
  4204. \see addElement(QCPLayoutElement *element, const QRectF &rect)
  4205. */
  4206. void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment)
  4207. {
  4208. if (element)
  4209. {
  4210. if (element->layout()) // remove from old layout first
  4211. element->layout()->take(element);
  4212. mElements.append(element);
  4213. mInsetPlacement.append(ipBorderAligned);
  4214. mInsetAlignment.append(alignment);
  4215. mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4));
  4216. adoptElement(element);
  4217. } else
  4218. qDebug() << Q_FUNC_INFO << "Can't add null element";
  4219. }
  4220. /*!
  4221. Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref
  4222. setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a
  4223. rect.
  4224. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
  4225. will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
  4226. corner of the layout, with 35% width and height of the parent layout.
  4227. \see addElement(QCPLayoutElement *element, Qt::Alignment alignment)
  4228. */
  4229. void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect)
  4230. {
  4231. if (element)
  4232. {
  4233. if (element->layout()) // remove from old layout first
  4234. element->layout()->take(element);
  4235. mElements.append(element);
  4236. mInsetPlacement.append(ipFree);
  4237. mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop);
  4238. mInsetRect.append(rect);
  4239. adoptElement(element);
  4240. } else
  4241. qDebug() << Q_FUNC_INFO << "Can't add null element";
  4242. }
  4243. /* end of 'src/layout.cpp' */
  4244. /* including file 'src/lineending.cpp', size 11536 */
  4245. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  4246. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4247. //////////////////// QCPLineEnding
  4248. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4249. /*! \class QCPLineEnding
  4250. \brief Handles the different ending decorations for line-like items
  4251. \image html QCPLineEnding.png "The various ending styles currently supported"
  4252. For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine
  4253. has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail.
  4254. The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can
  4255. be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of
  4256. the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item.
  4257. For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite
  4258. directions, e.g. "outward". This can be changed by \ref setInverted, which would make the
  4259. respective arrow point inward.
  4260. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a
  4261. QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g.
  4262. \snippet documentation/doc-code-snippets/mainwindow.cpp qcplineending-sethead
  4263. */
  4264. /*!
  4265. Creates a QCPLineEnding instance with default values (style \ref esNone).
  4266. */
  4267. QCPLineEnding::QCPLineEnding() :
  4268. mStyle(esNone),
  4269. mWidth(8),
  4270. mLength(10),
  4271. mInverted(false)
  4272. {
  4273. }
  4274. /*!
  4275. Creates a QCPLineEnding instance with the specified values.
  4276. */
  4277. QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) :
  4278. mStyle(style),
  4279. mWidth(width),
  4280. mLength(length),
  4281. mInverted(inverted)
  4282. {
  4283. }
  4284. /*!
  4285. Sets the style of the ending decoration.
  4286. */
  4287. void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style)
  4288. {
  4289. mStyle = style;
  4290. }
  4291. /*!
  4292. Sets the width of the ending decoration, if the style supports it. On arrows, for example, the
  4293. width defines the size perpendicular to the arrow's pointing direction.
  4294. \see setLength
  4295. */
  4296. void QCPLineEnding::setWidth(double width)
  4297. {
  4298. mWidth = width;
  4299. }
  4300. /*!
  4301. Sets the length of the ending decoration, if the style supports it. On arrows, for example, the
  4302. length defines the size in pointing direction.
  4303. \see setWidth
  4304. */
  4305. void QCPLineEnding::setLength(double length)
  4306. {
  4307. mLength = length;
  4308. }
  4309. /*!
  4310. Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point
  4311. inward when \a inverted is set to true.
  4312. Note that also the \a width direction is inverted. For symmetrical ending styles like arrows or
  4313. discs, this doesn't make a difference. However, asymmetric styles like \ref esHalfBar are
  4314. affected by it, which can be used to control to which side the half bar points to.
  4315. */
  4316. void QCPLineEnding::setInverted(bool inverted)
  4317. {
  4318. mInverted = inverted;
  4319. }
  4320. /*! \internal
  4321. Returns the maximum pixel radius the ending decoration might cover, starting from the position
  4322. the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item).
  4323. This is relevant for clipping. Only omit painting of the decoration when the position where the
  4324. decoration is supposed to be drawn is farther away from the clipping rect than the returned
  4325. distance.
  4326. */
  4327. double QCPLineEnding::boundingDistance() const
  4328. {
  4329. switch (mStyle)
  4330. {
  4331. case esNone:
  4332. return 0;
  4333. case esFlatArrow:
  4334. case esSpikeArrow:
  4335. case esLineArrow:
  4336. case esSkewedBar:
  4337. return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length
  4338. case esDisc:
  4339. case esSquare:
  4340. case esDiamond:
  4341. case esBar:
  4342. case esHalfBar:
  4343. return mWidth*1.42; // items that only have a width -> width*sqrt(2)
  4344. }
  4345. return 0;
  4346. }
  4347. /*!
  4348. Starting from the origin of this line ending (which is style specific), returns the length
  4349. covered by the line ending symbol, in backward direction.
  4350. For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if
  4351. both have the same \ref setLength value, because the spike arrow has an inward curved back, which
  4352. reduces the length along its center axis (the drawing origin for arrows is at the tip).
  4353. This function is used for precise, style specific placement of line endings, for example in
  4354. QCPAxes.
  4355. */
  4356. double QCPLineEnding::realLength() const
  4357. {
  4358. switch (mStyle)
  4359. {
  4360. case esNone:
  4361. case esLineArrow:
  4362. case esSkewedBar:
  4363. case esBar:
  4364. case esHalfBar:
  4365. return 0;
  4366. case esFlatArrow:
  4367. return mLength;
  4368. case esDisc:
  4369. case esSquare:
  4370. case esDiamond:
  4371. return mWidth*0.5;
  4372. case esSpikeArrow:
  4373. return mLength*0.8;
  4374. }
  4375. return 0;
  4376. }
  4377. /*! \internal
  4378. Draws the line ending with the specified \a painter at the position \a pos. The direction of the
  4379. line ending is controlled with \a dir.
  4380. */
  4381. void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, const QCPVector2D &dir) const
  4382. {
  4383. if (mStyle == esNone)
  4384. return;
  4385. QCPVector2D lengthVec = dir.normalized() * mLength*(mInverted ? -1 : 1);
  4386. if (lengthVec.isNull())
  4387. lengthVec = QCPVector2D(1, 0);
  4388. QCPVector2D widthVec = dir.normalized().perpendicular() * mWidth*0.5*(mInverted ? -1 : 1);
  4389. QPen penBackup = painter->pen();
  4390. QBrush brushBackup = painter->brush();
  4391. QPen miterPen = penBackup;
  4392. miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey
  4393. QBrush brush(painter->pen().color(), Qt::SolidPattern);
  4394. switch (mStyle)
  4395. {
  4396. case esNone: break;
  4397. case esFlatArrow:
  4398. {
  4399. QPointF points[3] = {pos.toPointF(),
  4400. (pos-lengthVec+widthVec).toPointF(),
  4401. (pos-lengthVec-widthVec).toPointF()
  4402. };
  4403. painter->setPen(miterPen);
  4404. painter->setBrush(brush);
  4405. painter->drawConvexPolygon(points, 3);
  4406. painter->setBrush(brushBackup);
  4407. painter->setPen(penBackup);
  4408. break;
  4409. }
  4410. case esSpikeArrow:
  4411. {
  4412. QPointF points[4] = {pos.toPointF(),
  4413. (pos-lengthVec+widthVec).toPointF(),
  4414. (pos-lengthVec*0.8).toPointF(),
  4415. (pos-lengthVec-widthVec).toPointF()
  4416. };
  4417. painter->setPen(miterPen);
  4418. painter->setBrush(brush);
  4419. painter->drawConvexPolygon(points, 4);
  4420. painter->setBrush(brushBackup);
  4421. painter->setPen(penBackup);
  4422. break;
  4423. }
  4424. case esLineArrow:
  4425. {
  4426. QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(),
  4427. pos.toPointF(),
  4428. (pos-lengthVec-widthVec).toPointF()
  4429. };
  4430. painter->setPen(miterPen);
  4431. painter->drawPolyline(points, 3);
  4432. painter->setPen(penBackup);
  4433. break;
  4434. }
  4435. case esDisc:
  4436. {
  4437. painter->setBrush(brush);
  4438. painter->drawEllipse(pos.toPointF(), mWidth*0.5, mWidth*0.5);
  4439. painter->setBrush(brushBackup);
  4440. break;
  4441. }
  4442. case esSquare:
  4443. {
  4444. QCPVector2D widthVecPerp = widthVec.perpendicular();
  4445. QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(),
  4446. (pos-widthVecPerp-widthVec).toPointF(),
  4447. (pos+widthVecPerp-widthVec).toPointF(),
  4448. (pos+widthVecPerp+widthVec).toPointF()
  4449. };
  4450. painter->setPen(miterPen);
  4451. painter->setBrush(brush);
  4452. painter->drawConvexPolygon(points, 4);
  4453. painter->setBrush(brushBackup);
  4454. painter->setPen(penBackup);
  4455. break;
  4456. }
  4457. case esDiamond:
  4458. {
  4459. QCPVector2D widthVecPerp = widthVec.perpendicular();
  4460. QPointF points[4] = {(pos-widthVecPerp).toPointF(),
  4461. (pos-widthVec).toPointF(),
  4462. (pos+widthVecPerp).toPointF(),
  4463. (pos+widthVec).toPointF()
  4464. };
  4465. painter->setPen(miterPen);
  4466. painter->setBrush(brush);
  4467. painter->drawConvexPolygon(points, 4);
  4468. painter->setBrush(brushBackup);
  4469. painter->setPen(penBackup);
  4470. break;
  4471. }
  4472. case esBar:
  4473. {
  4474. painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF());
  4475. break;
  4476. }
  4477. case esHalfBar:
  4478. {
  4479. painter->drawLine((pos+widthVec).toPointF(), pos.toPointF());
  4480. break;
  4481. }
  4482. case esSkewedBar:
  4483. {
  4484. if (qFuzzyIsNull(painter->pen().widthF()) && !painter->modes().testFlag(QCPPainter::pmNonCosmetic))
  4485. {
  4486. // if drawing with cosmetic pen (perfectly thin stroke, happens only in vector exports), draw bar exactly on tip of line
  4487. painter->drawLine((pos+widthVec+lengthVec*0.2*(mInverted?-1:1)).toPointF(),
  4488. (pos-widthVec-lengthVec*0.2*(mInverted?-1:1)).toPointF());
  4489. } else
  4490. {
  4491. // if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly
  4492. painter->drawLine((pos+widthVec+lengthVec*0.2*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF(),
  4493. (pos-widthVec-lengthVec*0.2*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF());
  4494. }
  4495. break;
  4496. }
  4497. }
  4498. }
  4499. /*! \internal
  4500. \overload
  4501. Draws the line ending. The direction is controlled with the \a angle parameter in radians.
  4502. */
  4503. void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, double angle) const
  4504. {
  4505. draw(painter, pos, QCPVector2D(qCos(angle), qSin(angle)));
  4506. }
  4507. /* end of 'src/lineending.cpp' */
  4508. /* including file 'src/axis/axisticker.cpp', size 18664 */
  4509. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  4510. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4511. //////////////////// QCPAxisTicker
  4512. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4513. /*! \class QCPAxisTicker
  4514. \brief The base class tick generator used by QCPAxis to create tick positions and tick labels
  4515. Each QCPAxis has an internal QCPAxisTicker (or a subclass) in order to generate tick positions
  4516. and tick labels for the current axis range. The ticker of an axis can be set via \ref
  4517. QCPAxis::setTicker. Since that method takes a <tt>QSharedPointer<QCPAxisTicker></tt>, multiple
  4518. axes can share the same ticker instance.
  4519. This base class generates normal tick coordinates and numeric labels for linear axes. It picks a
  4520. reasonable tick step (the separation between ticks) which results in readable tick labels. The
  4521. number of ticks that should be approximately generated can be set via \ref setTickCount.
  4522. Depending on the current tick step strategy (\ref setTickStepStrategy), the algorithm either
  4523. sacrifices readability to better match the specified tick count (\ref
  4524. QCPAxisTicker::tssMeetTickCount) or relaxes the tick count in favor of better tick steps (\ref
  4525. QCPAxisTicker::tssReadability), which is the default.
  4526. The following more specialized axis ticker subclasses are available, see details in the
  4527. respective class documentation:
  4528. <center>
  4529. <table>
  4530. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerFixed</td><td>\image html axisticker-fixed.png</td></tr>
  4531. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerLog</td><td>\image html axisticker-log.png</td></tr>
  4532. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerPi</td><td>\image html axisticker-pi.png</td></tr>
  4533. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerText</td><td>\image html axisticker-text.png</td></tr>
  4534. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerDateTime</td><td>\image html axisticker-datetime.png</td></tr>
  4535. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerTime</td><td>\image html axisticker-time.png
  4536. \image html axisticker-time2.png</td></tr>
  4537. </table>
  4538. </center>
  4539. \section axisticker-subclassing Creating own axis tickers
  4540. Creating own axis tickers can be achieved very easily by sublassing QCPAxisTicker and
  4541. reimplementing some or all of the available virtual methods.
  4542. In the simplest case you might wish to just generate different tick steps than the other tickers,
  4543. so you only reimplement the method \ref getTickStep. If you additionally want control over the
  4544. string that will be shown as tick label, reimplement \ref getTickLabel.
  4545. If you wish to have complete control, you can generate the tick vectors and tick label vectors
  4546. yourself by reimplementing \ref createTickVector and \ref createLabelVector. The default
  4547. implementations use the previously mentioned virtual methods \ref getTickStep and \ref
  4548. getTickLabel, but your reimplementations don't necessarily need to do so. For example in the case
  4549. of unequal tick steps, the method \ref getTickStep loses its usefulness and can be ignored.
  4550. The sub tick count between major ticks can be controlled with \ref getSubTickCount. Full sub tick
  4551. placement control is obtained by reimplementing \ref createSubTickVector.
  4552. See the documentation of all these virtual methods in QCPAxisTicker for detailed information
  4553. about the parameters and expected return values.
  4554. */
  4555. /*!
  4556. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  4557. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  4558. */
  4559. QCPAxisTicker::QCPAxisTicker() :
  4560. mTickStepStrategy(tssReadability),
  4561. mTickCount(5),
  4562. mTickOrigin(0)
  4563. {
  4564. }
  4565. QCPAxisTicker::~QCPAxisTicker()
  4566. {
  4567. }
  4568. /*!
  4569. Sets which strategy the axis ticker follows when choosing the size of the tick step. For the
  4570. available strategies, see \ref TickStepStrategy.
  4571. */
  4572. void QCPAxisTicker::setTickStepStrategy(QCPAxisTicker::TickStepStrategy strategy)
  4573. {
  4574. mTickStepStrategy = strategy;
  4575. }
  4576. /*!
  4577. Sets how many ticks this ticker shall aim to generate across the axis range. Note that \a count
  4578. is not guaranteed to be matched exactly, as generating readable tick intervals may conflict with
  4579. the requested number of ticks.
  4580. Whether the readability has priority over meeting the requested \a count can be specified with
  4581. \ref setTickStepStrategy.
  4582. */
  4583. void QCPAxisTicker::setTickCount(int count)
  4584. {
  4585. if (count > 0)
  4586. mTickCount = count;
  4587. else
  4588. qDebug() << Q_FUNC_INFO << "tick count must be greater than zero:" << count;
  4589. }
  4590. /*!
  4591. Sets the mathematical coordinate (or "offset") of the zeroth tick. This tick coordinate is just a
  4592. concept and doesn't need to be inside the currently visible axis range.
  4593. By default \a origin is zero, which for example yields ticks {-5, 0, 5, 10, 15,...} when the tick
  4594. step is five. If \a origin is now set to 1 instead, the correspondingly generated ticks would be
  4595. {-4, 1, 6, 11, 16,...}.
  4596. */
  4597. void QCPAxisTicker::setTickOrigin(double origin)
  4598. {
  4599. mTickOrigin = origin;
  4600. }
  4601. /*!
  4602. This is the method called by QCPAxis in order to actually generate tick coordinates (\a ticks),
  4603. tick label strings (\a tickLabels) and sub tick coordinates (\a subTicks).
  4604. The ticks are generated for the specified \a range. The generated labels typically follow the
  4605. specified \a locale, \a formatChar and number \a precision, however this might be different (or
  4606. even irrelevant) for certain QCPAxisTicker subclasses.
  4607. The output parameter \a ticks is filled with the generated tick positions in axis coordinates.
  4608. The output parameters \a subTicks and \a tickLabels are optional (set them to 0 if not needed)
  4609. and are respectively filled with sub tick coordinates, and tick label strings belonging to \a
  4610. ticks by index.
  4611. */
  4612. void QCPAxisTicker::generate(const QCPRange &range, const QLocale &locale, QChar formatChar, int precision, QVector<double> &ticks, QVector<double> *subTicks, QVector<QString> *tickLabels)
  4613. {
  4614. // generate (major) ticks:
  4615. double tickStep = getTickStep(range);
  4616. ticks = createTickVector(tickStep, range);
  4617. trimTicks(range, ticks, true); // trim ticks to visible range plus one outer tick on each side (incase a subclass createTickVector creates more)
  4618. // generate sub ticks between major ticks:
  4619. if (subTicks)
  4620. {
  4621. if (ticks.size() > 0)
  4622. {
  4623. *subTicks = createSubTickVector(getSubTickCount(tickStep), ticks);
  4624. trimTicks(range, *subTicks, false);
  4625. } else
  4626. *subTicks = QVector<double>();
  4627. }
  4628. // finally trim also outliers (no further clipping happens in axis drawing):
  4629. trimTicks(range, ticks, false);
  4630. // generate labels for visible ticks if requested:
  4631. if (tickLabels)
  4632. *tickLabels = createLabelVector(ticks, locale, formatChar, precision);
  4633. }
  4634. /*! \internal
  4635. Takes the entire currently visible axis range and returns a sensible tick step in
  4636. order to provide readable tick labels as well as a reasonable number of tick counts (see \ref
  4637. setTickCount, \ref setTickStepStrategy).
  4638. If a QCPAxisTicker subclass only wants a different tick step behaviour than the default
  4639. implementation, it should reimplement this method. See \ref cleanMantissa for a possible helper
  4640. function.
  4641. */
  4642. double QCPAxisTicker::getTickStep(const QCPRange &range)
  4643. {
  4644. double exactStep = range.size()/(double)(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  4645. return cleanMantissa(exactStep);
  4646. }
  4647. /*! \internal
  4648. Takes the \a tickStep, i.e. the distance between two consecutive ticks, and returns
  4649. an appropriate number of sub ticks for that specific tick step.
  4650. Note that a returned sub tick count of e.g. 4 will split each tick interval into 5 sections.
  4651. */
  4652. int QCPAxisTicker::getSubTickCount(double tickStep)
  4653. {
  4654. int result = 1; // default to 1, if no proper value can be found
  4655. // separate integer and fractional part of mantissa:
  4656. double epsilon = 0.01;
  4657. double intPartf;
  4658. int intPart;
  4659. double fracPart = modf(getMantissa(tickStep), &intPartf);
  4660. intPart = intPartf;
  4661. // handle cases with (almost) integer mantissa:
  4662. if (fracPart < epsilon || 1.0-fracPart < epsilon)
  4663. {
  4664. if (1.0-fracPart < epsilon)
  4665. ++intPart;
  4666. switch (intPart)
  4667. {
  4668. case 1: result = 4; break; // 1.0 -> 0.2 substep
  4669. case 2: result = 3; break; // 2.0 -> 0.5 substep
  4670. case 3: result = 2; break; // 3.0 -> 1.0 substep
  4671. case 4: result = 3; break; // 4.0 -> 1.0 substep
  4672. case 5: result = 4; break; // 5.0 -> 1.0 substep
  4673. case 6: result = 2; break; // 6.0 -> 2.0 substep
  4674. case 7: result = 6; break; // 7.0 -> 1.0 substep
  4675. case 8: result = 3; break; // 8.0 -> 2.0 substep
  4676. case 9: result = 2; break; // 9.0 -> 3.0 substep
  4677. }
  4678. } else
  4679. {
  4680. // handle cases with significantly fractional mantissa:
  4681. if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa
  4682. {
  4683. switch (intPart)
  4684. {
  4685. case 1: result = 2; break; // 1.5 -> 0.5 substep
  4686. case 2: result = 4; break; // 2.5 -> 0.5 substep
  4687. case 3: result = 4; break; // 3.5 -> 0.7 substep
  4688. case 4: result = 2; break; // 4.5 -> 1.5 substep
  4689. case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with default getTickStep from here on)
  4690. case 6: result = 4; break; // 6.5 -> 1.3 substep
  4691. case 7: result = 2; break; // 7.5 -> 2.5 substep
  4692. case 8: result = 4; break; // 8.5 -> 1.7 substep
  4693. case 9: result = 4; break; // 9.5 -> 1.9 substep
  4694. }
  4695. }
  4696. // if mantissa fraction isn't 0.0 or 0.5, don't bother finding good sub tick marks, leave default
  4697. }
  4698. return result;
  4699. }
  4700. /*! \internal
  4701. This method returns the tick label string as it should be printed under the \a tick coordinate.
  4702. If a textual number is returned, it should respect the provided \a locale, \a formatChar and \a
  4703. precision.
  4704. If the returned value contains exponentials of the form "2e5" and beautifully typeset powers is
  4705. enabled in the QCPAxis number format (\ref QCPAxis::setNumberFormat), the exponential part will
  4706. be formatted accordingly using multiplication symbol and superscript during rendering of the
  4707. label automatically.
  4708. */
  4709. QString QCPAxisTicker::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  4710. {
  4711. return locale.toString(tick, formatChar.toLatin1(), precision);
  4712. }
  4713. /*! \internal
  4714. Returns a vector containing all coordinates of sub ticks that should be drawn. It generates \a
  4715. subTickCount sub ticks between each tick pair given in \a ticks.
  4716. If a QCPAxisTicker subclass needs maximal control over the generated sub ticks, it should
  4717. reimplement this method. Depending on the purpose of the subclass it doesn't necessarily need to
  4718. base its result on \a subTickCount or \a ticks.
  4719. */
  4720. QVector<double> QCPAxisTicker::createSubTickVector(int subTickCount, const QVector<double> &ticks)
  4721. {
  4722. QVector<double> result;
  4723. if (subTickCount <= 0 || ticks.size() < 2)
  4724. return result;
  4725. result.reserve((ticks.size()-1)*subTickCount);
  4726. for (int i=1; i<ticks.size(); ++i)
  4727. {
  4728. double subTickStep = (ticks.at(i)-ticks.at(i-1))/(double)(subTickCount+1);
  4729. for (int k=1; k<=subTickCount; ++k)
  4730. result.append(ticks.at(i-1) + k*subTickStep);
  4731. }
  4732. return result;
  4733. }
  4734. /*! \internal
  4735. Returns a vector containing all coordinates of ticks that should be drawn. The default
  4736. implementation generates ticks with a spacing of \a tickStep (mathematically starting at the tick
  4737. step origin, see \ref setTickOrigin) distributed over the passed \a range.
  4738. In order for the axis ticker to generate proper sub ticks, it is necessary that the first and
  4739. last tick coordinates returned by this method are just below/above the provided \a range.
  4740. Otherwise the outer intervals won't contain any sub ticks.
  4741. If a QCPAxisTicker subclass needs maximal control over the generated ticks, it should reimplement
  4742. this method. Depending on the purpose of the subclass it doesn't necessarily need to base its
  4743. result on \a tickStep, e.g. when the ticks are spaced unequally like in the case of
  4744. QCPAxisTickerLog.
  4745. */
  4746. QVector<double> QCPAxisTicker::createTickVector(double tickStep, const QCPRange &range)
  4747. {
  4748. QVector<double> result;
  4749. // Generate tick positions according to tickStep:
  4750. qint64 firstStep = floor((range.lower-mTickOrigin)/tickStep); // do not use qFloor here, or we'll lose 64 bit precision
  4751. qint64 lastStep = ceil((range.upper-mTickOrigin)/tickStep); // do not use qCeil here, or we'll lose 64 bit precision
  4752. int tickcount = lastStep-firstStep+1;
  4753. if (tickcount < 0) tickcount = 0;
  4754. result.resize(tickcount);
  4755. for (int i=0; i<tickcount; ++i)
  4756. result[i] = mTickOrigin + (firstStep+i)*tickStep;
  4757. return result;
  4758. }
  4759. /*! \internal
  4760. Returns a vector containing all tick label strings corresponding to the tick coordinates provided
  4761. in \a ticks. The default implementation calls \ref getTickLabel to generate the respective
  4762. strings.
  4763. It is possible but uncommon for QCPAxisTicker subclasses to reimplement this method, as
  4764. reimplementing \ref getTickLabel often achieves the intended result easier.
  4765. */
  4766. QVector<QString> QCPAxisTicker::createLabelVector(const QVector<double> &ticks, const QLocale &locale, QChar formatChar, int precision)
  4767. {
  4768. QVector<QString> result;
  4769. result.reserve(ticks.size());
  4770. for (int i=0; i<ticks.size(); ++i)
  4771. result.append(getTickLabel(ticks.at(i), locale, formatChar, precision));
  4772. return result;
  4773. }
  4774. /*! \internal
  4775. Removes tick coordinates from \a ticks which lie outside the specified \a range. If \a
  4776. keepOneOutlier is true, it preserves one tick just outside the range on both sides, if present.
  4777. The passed \a ticks must be sorted in ascending order.
  4778. */
  4779. void QCPAxisTicker::trimTicks(const QCPRange &range, QVector<double> &ticks, bool keepOneOutlier) const
  4780. {
  4781. bool lowFound = false;
  4782. bool highFound = false;
  4783. int lowIndex = 0;
  4784. int highIndex = -1;
  4785. for (int i=0; i < ticks.size(); ++i)
  4786. {
  4787. if (ticks.at(i) >= range.lower)
  4788. {
  4789. lowFound = true;
  4790. lowIndex = i;
  4791. break;
  4792. }
  4793. }
  4794. for (int i=ticks.size()-1; i >= 0; --i)
  4795. {
  4796. if (ticks.at(i) <= range.upper)
  4797. {
  4798. highFound = true;
  4799. highIndex = i;
  4800. break;
  4801. }
  4802. }
  4803. if (highFound && lowFound)
  4804. {
  4805. int trimFront = qMax(0, lowIndex-(keepOneOutlier ? 1 : 0));
  4806. int trimBack = qMax(0, ticks.size()-(keepOneOutlier ? 2 : 1)-highIndex);
  4807. if (trimFront > 0 || trimBack > 0)
  4808. ticks = ticks.mid(trimFront, ticks.size()-trimFront-trimBack);
  4809. } else // all ticks are either all below or all above the range
  4810. ticks.clear();
  4811. }
  4812. /*! \internal
  4813. Returns the coordinate contained in \a candidates which is closest to the provided \a target.
  4814. This method assumes \a candidates is not empty and sorted in ascending order.
  4815. */
  4816. double QCPAxisTicker::pickClosest(double target, const QVector<double> &candidates) const
  4817. {
  4818. if (candidates.size() == 1)
  4819. return candidates.first();
  4820. QVector<double>::const_iterator it = std::lower_bound(candidates.constBegin(), candidates.constEnd(), target);
  4821. if (it == candidates.constEnd())
  4822. return *(it-1);
  4823. else if (it == candidates.constBegin())
  4824. return *it;
  4825. else
  4826. return target-*(it-1) < *it-target ? *(it-1) : *it;
  4827. }
  4828. /*! \internal
  4829. Returns the decimal mantissa of \a input. Optionally, if \a magnitude is not set to zero, it also
  4830. returns the magnitude of \a input as a power of 10.
  4831. For example, an input of 142.6 will return a mantissa of 1.426 and a magnitude of 100.
  4832. */
  4833. double QCPAxisTicker::getMantissa(double input, double *magnitude) const
  4834. {
  4835. const double mag = qPow(10.0, qFloor(qLn(input)/qLn(10.0)));
  4836. if (magnitude) *magnitude = mag;
  4837. return input/mag;
  4838. }
  4839. /*! \internal
  4840. Returns a number that is close to \a input but has a clean, easier human readable mantissa. How
  4841. strongly the mantissa is altered, and thus how strong the result deviates from the original \a
  4842. input, depends on the current tick step strategy (see \ref setTickStepStrategy).
  4843. */
  4844. double QCPAxisTicker::cleanMantissa(double input) const
  4845. {
  4846. double magnitude;
  4847. const double mantissa = getMantissa(input, &magnitude);
  4848. switch (mTickStepStrategy)
  4849. {
  4850. case tssReadability:
  4851. {
  4852. return pickClosest(mantissa, QVector<double>() << 1.0 << 2.0 << 2.5 << 5.0 << 10.0)*magnitude;
  4853. }
  4854. case tssMeetTickCount:
  4855. {
  4856. // 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
  4857. if (mantissa <= 5.0)
  4858. return (int)(mantissa*2)/2.0*magnitude; // round digit after decimal point to 0.5
  4859. else
  4860. return (int)(mantissa/2.0)*2.0*magnitude; // round to first digit in multiples of 2
  4861. }
  4862. }
  4863. return input;
  4864. }
  4865. /* end of 'src/axis/axisticker.cpp' */
  4866. /* including file 'src/axis/axistickerdatetime.cpp', size 14443 */
  4867. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  4868. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4869. //////////////////// QCPAxisTickerDateTime
  4870. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4871. /*! \class QCPAxisTickerDateTime
  4872. \brief Specialized axis ticker for calendar dates and times as axis ticks
  4873. \image html axisticker-datetime.png
  4874. This QCPAxisTicker subclass generates ticks that correspond to real calendar dates and times. The
  4875. plot axis coordinate is interpreted as Unix Time, so seconds since Epoch (January 1, 1970, 00:00
  4876. UTC). This is also used for example by QDateTime in the <tt>toTime_t()/setTime_t()</tt> methods
  4877. with a precision of one second. Since Qt 4.7, millisecond accuracy can be obtained from QDateTime
  4878. by using <tt>QDateTime::fromMSecsSinceEpoch()/1000.0</tt>. The static methods \ref dateTimeToKey
  4879. and \ref keyToDateTime conveniently perform this conversion achieving a precision of one
  4880. millisecond on all Qt versions.
  4881. The format of the date/time display in the tick labels is controlled with \ref setDateTimeFormat.
  4882. If a different time spec (time zone) shall be used, see \ref setDateTimeSpec.
  4883. This ticker produces unequal tick spacing in order to provide intuitive date and time-of-day
  4884. ticks. For example, if the axis range spans a few years such that there is one tick per year,
  4885. ticks will be positioned on 1. January of every year. This is intuitive but, due to leap years,
  4886. will result in slightly unequal tick intervals (visually unnoticeable). The same can be seen in
  4887. the image above: even though the number of days varies month by month, this ticker generates
  4888. ticks on the same day of each month.
  4889. If you would like to change the date/time that is used as a (mathematical) starting date for the
  4890. ticks, use the \ref setTickOrigin(const QDateTime &origin) method overload, which takes a
  4891. QDateTime. If you pass 15. July, 9:45 to this method, the yearly ticks will end up on 15. July at
  4892. 9:45 of every year.
  4893. The ticker can be created and assigned to an axis like this:
  4894. \snippet documentation/doc-image-generator/mainwindow.cpp axistickerdatetime-creation
  4895. \note If you rather wish to display relative times in terms of days, hours, minutes, seconds and
  4896. milliseconds, and are not interested in the intricacies of real calendar dates with months and
  4897. (leap) years, have a look at QCPAxisTickerTime instead.
  4898. */
  4899. /*!
  4900. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  4901. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  4902. */
  4903. QCPAxisTickerDateTime::QCPAxisTickerDateTime() :
  4904. mDateTimeFormat(QLatin1String("hh:mm:ss\ndd.MM.yy")),
  4905. mDateTimeSpec(Qt::LocalTime),
  4906. mDateStrategy(dsNone)
  4907. {
  4908. setTickCount(4);
  4909. }
  4910. /*!
  4911. Sets the format in which dates and times are displayed as tick labels. For details about the \a
  4912. format string, see the documentation of QDateTime::toString().
  4913. Newlines can be inserted with "\n".
  4914. \see setDateTimeSpec
  4915. */
  4916. void QCPAxisTickerDateTime::setDateTimeFormat(const QString &format)
  4917. {
  4918. mDateTimeFormat = format;
  4919. }
  4920. /*!
  4921. Sets the time spec that is used for creating the tick labels from corresponding dates/times.
  4922. The default value of QDateTime objects (and also QCPAxisTickerDateTime) is
  4923. <tt>Qt::LocalTime</tt>. However, if the date time values passed to QCustomPlot (e.g. in the form
  4924. of axis ranges or keys of a plottable) are given in the UTC spec, set \a spec to <tt>Qt::UTC</tt>
  4925. to get the correct axis labels.
  4926. \see setDateTimeFormat
  4927. */
  4928. void QCPAxisTickerDateTime::setDateTimeSpec(Qt::TimeSpec spec)
  4929. {
  4930. mDateTimeSpec = spec;
  4931. }
  4932. /*!
  4933. Sets the tick origin (see \ref QCPAxisTicker::setTickOrigin) in seconds since Epoch (1. Jan 1970,
  4934. 00:00 UTC). For the date time ticker it might be more intuitive to use the overload which
  4935. directly takes a QDateTime, see \ref setTickOrigin(const QDateTime &origin).
  4936. This is useful to define the month/day/time recurring at greater tick interval steps. For
  4937. example, If you pass 15. July, 9:45 to this method and the tick interval happens to be one tick
  4938. per year, the ticks will end up on 15. July at 9:45 of every year.
  4939. */
  4940. void QCPAxisTickerDateTime::setTickOrigin(double origin)
  4941. {
  4942. QCPAxisTicker::setTickOrigin(origin);
  4943. }
  4944. /*!
  4945. Sets the tick origin (see \ref QCPAxisTicker::setTickOrigin) as a QDateTime \a origin.
  4946. This is useful to define the month/day/time recurring at greater tick interval steps. For
  4947. example, If you pass 15. July, 9:45 to this method and the tick interval happens to be one tick
  4948. per year, the ticks will end up on 15. July at 9:45 of every year.
  4949. */
  4950. void QCPAxisTickerDateTime::setTickOrigin(const QDateTime &origin)
  4951. {
  4952. setTickOrigin(dateTimeToKey(origin));
  4953. }
  4954. /*! \internal
  4955. Returns a sensible tick step with intervals appropriate for a date-time-display, such as weekly,
  4956. monthly, bi-monthly, etc.
  4957. Note that this tick step isn't used exactly when generating the tick vector in \ref
  4958. createTickVector, but only as a guiding value requiring some correction for each individual tick
  4959. interval. Otherwise this would lead to unintuitive date displays, e.g. jumping between first day
  4960. in the month to the last day in the previous month from tick to tick, due to the non-uniform
  4961. length of months. The same problem arises with leap years.
  4962. \seebaseclassmethod
  4963. */
  4964. double QCPAxisTickerDateTime::getTickStep(const QCPRange &range)
  4965. {
  4966. double result = range.size()/(double)(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  4967. mDateStrategy = dsNone;
  4968. if (result < 1) // ideal tick step is below 1 second -> use normal clean mantissa algorithm in units of seconds
  4969. {
  4970. result = cleanMantissa(result);
  4971. } else if (result < 86400*30.4375*12) // below a year
  4972. {
  4973. result = pickClosest(result, QVector<double>()
  4974. << 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
  4975. << 3600*2 << 3600*3 << 3600*6 << 3600*12 << 3600*24 // hour to day range
  4976. << 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)
  4977. if (result > 86400*30.4375-1) // month tick intervals or larger
  4978. mDateStrategy = dsUniformDayInMonth;
  4979. else if (result > 3600*24-1) // day tick intervals or larger
  4980. mDateStrategy = dsUniformTimeInDay;
  4981. } else // more than a year, go back to normal clean mantissa algorithm but in units of years
  4982. {
  4983. const double secondsPerYear = 86400*30.4375*12; // average including leap years
  4984. result = cleanMantissa(result/secondsPerYear)*secondsPerYear;
  4985. mDateStrategy = dsUniformDayInMonth;
  4986. }
  4987. return result;
  4988. }
  4989. /*! \internal
  4990. Returns a sensible sub tick count with intervals appropriate for a date-time-display, such as weekly,
  4991. monthly, bi-monthly, etc.
  4992. \seebaseclassmethod
  4993. */
  4994. int QCPAxisTickerDateTime::getSubTickCount(double tickStep)
  4995. {
  4996. int result = QCPAxisTicker::getSubTickCount(tickStep);
  4997. switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day/week/month range (as specified in getTickStep)
  4998. {
  4999. case 5*60: result = 4; break;
  5000. case 10*60: result = 1; break;
  5001. case 15*60: result = 2; break;
  5002. case 30*60: result = 1; break;
  5003. case 60*60: result = 3; break;
  5004. case 3600*2: result = 3; break;
  5005. case 3600*3: result = 2; break;
  5006. case 3600*6: result = 1; break;
  5007. case 3600*12: result = 3; break;
  5008. case 3600*24: result = 3; break;
  5009. case 86400*2: result = 1; break;
  5010. case 86400*5: result = 4; break;
  5011. case 86400*7: result = 6; break;
  5012. case 86400*14: result = 1; break;
  5013. case (int)(86400*30.4375+0.5): result = 3; break;
  5014. case (int)(86400*30.4375*2+0.5): result = 1; break;
  5015. case (int)(86400*30.4375*3+0.5): result = 2; break;
  5016. case (int)(86400*30.4375*6+0.5): result = 5; break;
  5017. case (int)(86400*30.4375*12+0.5): result = 3; break;
  5018. }
  5019. return result;
  5020. }
  5021. /*! \internal
  5022. Generates a date/time tick label for tick coordinate \a tick, based on the currently set format
  5023. (\ref setDateTimeFormat) and time spec (\ref setDateTimeSpec).
  5024. \seebaseclassmethod
  5025. */
  5026. QString QCPAxisTickerDateTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  5027. {
  5028. Q_UNUSED(precision)
  5029. Q_UNUSED(formatChar)
  5030. return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
  5031. }
  5032. /*! \internal
  5033. Uses the passed \a tickStep as a guiding value and applies corrections in order to obtain
  5034. non-uniform tick intervals but intuitive tick labels, e.g. falling on the same day of each month.
  5035. \seebaseclassmethod
  5036. */
  5037. QVector<double> QCPAxisTickerDateTime::createTickVector(double tickStep, const QCPRange &range)
  5038. {
  5039. QVector<double> result = QCPAxisTicker::createTickVector(tickStep, range);
  5040. if (!result.isEmpty())
  5041. {
  5042. if (mDateStrategy == dsUniformTimeInDay)
  5043. {
  5044. QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // the time of this datetime will be set for all other ticks, if possible
  5045. QDateTime tickDateTime;
  5046. for (int i=0; i<result.size(); ++i)
  5047. {
  5048. tickDateTime = keyToDateTime(result.at(i));
  5049. tickDateTime.setTime(uniformDateTime.time());
  5050. result[i] = dateTimeToKey(tickDateTime);
  5051. }
  5052. } else if (mDateStrategy == dsUniformDayInMonth)
  5053. {
  5054. QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // this day (in month) and time will be set for all other ticks, if possible
  5055. QDateTime tickDateTime;
  5056. for (int i=0; i<result.size(); ++i)
  5057. {
  5058. tickDateTime = keyToDateTime(result.at(i));
  5059. tickDateTime.setTime(uniformDateTime.time());
  5060. 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)
  5061. 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
  5062. tickDateTime = tickDateTime.addMonths(1);
  5063. 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
  5064. tickDateTime = tickDateTime.addMonths(-1);
  5065. tickDateTime.setDate(QDate(tickDateTime.date().year(), tickDateTime.date().month(), thisUniformDay));
  5066. result[i] = dateTimeToKey(tickDateTime);
  5067. }
  5068. }
  5069. }
  5070. return result;
  5071. }
  5072. /*!
  5073. A convenience method which turns \a key (in seconds since Epoch 1. Jan 1970, 00:00 UTC) into a
  5074. QDateTime object. This can be used to turn axis coordinates to actual QDateTimes.
  5075. The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it
  5076. works around the lack of a QDateTime::fromMSecsSinceEpoch in Qt 4.6)
  5077. \see dateTimeToKey
  5078. */
  5079. QDateTime QCPAxisTickerDateTime::keyToDateTime(double key)
  5080. {
  5081. # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
  5082. return QDateTime::fromTime_t(key).addMSecs((key-(qint64)key)*1000);
  5083. # else
  5084. return QDateTime::fromMSecsSinceEpoch(key*1000.0);
  5085. # endif
  5086. }
  5087. /*! \overload
  5088. A convenience method which turns a QDateTime object into a double value that corresponds to
  5089. seconds since Epoch (1. Jan 1970, 00:00 UTC). This is the format used as axis coordinates by
  5090. QCPAxisTickerDateTime.
  5091. The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it
  5092. works around the lack of a QDateTime::toMSecsSinceEpoch in Qt 4.6)
  5093. \see keyToDateTime
  5094. */
  5095. double QCPAxisTickerDateTime::dateTimeToKey(const QDateTime dateTime)
  5096. {
  5097. # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
  5098. return dateTime.toTime_t()+dateTime.time().msec()/1000.0;
  5099. # else
  5100. return dateTime.toMSecsSinceEpoch()/1000.0;
  5101. # endif
  5102. }
  5103. /*! \overload
  5104. A convenience method which turns a QDate object into a double value that corresponds to
  5105. seconds since Epoch (1. Jan 1970, 00:00 UTC). This is the format used as axis coordinates by
  5106. QCPAxisTickerDateTime.
  5107. \see keyToDateTime
  5108. */
  5109. double QCPAxisTickerDateTime::dateTimeToKey(const QDate date)
  5110. {
  5111. # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
  5112. return QDateTime(date).toTime_t();
  5113. # else
  5114. return QDateTime(date).toMSecsSinceEpoch()/1000.0;
  5115. # endif
  5116. }
  5117. /* end of 'src/axis/axistickerdatetime.cpp' */
  5118. /* including file 'src/axis/axistickertime.cpp', size 11747 */
  5119. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  5120. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5121. //////////////////// QCPAxisTickerTime
  5122. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5123. /*! \class QCPAxisTickerTime
  5124. \brief Specialized axis ticker for time spans in units of milliseconds to days
  5125. \image html axisticker-time.png
  5126. This QCPAxisTicker subclass generates ticks that corresponds to time intervals.
  5127. The format of the time display in the tick labels is controlled with \ref setTimeFormat and \ref
  5128. setFieldWidth. The time coordinate is in the unit of seconds with respect to the time coordinate
  5129. zero. Unlike with QCPAxisTickerDateTime, the ticks don't correspond to a specific calendar date
  5130. and time.
  5131. The time can be displayed in milliseconds, seconds, minutes, hours and days. Depending on the
  5132. largest available unit in the format specified with \ref setTimeFormat, any time spans above will
  5133. be carried in that largest unit. So for example if the format string is "%m:%s" and a tick at
  5134. coordinate value 7815 (being 2 hours, 10 minutes and 15 seconds) is created, the resulting tick
  5135. label will show "130:15" (130 minutes, 15 seconds). If the format string is "%h:%m:%s", the hour
  5136. unit will be used and the label will thus be "02:10:15". Negative times with respect to the axis
  5137. zero will carry a leading minus sign.
  5138. The ticker can be created and assigned to an axis like this:
  5139. \snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation
  5140. Here is an example of a time axis providing time information in days, hours and minutes. Due to
  5141. the axis range spanning a few days and the wanted tick count (\ref setTickCount), the ticker
  5142. decided to use tick steps of 12 hours:
  5143. \image html axisticker-time2.png
  5144. The format string for this example is
  5145. \snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation-2
  5146. \note If you rather wish to display calendar dates and times, have a look at QCPAxisTickerDateTime
  5147. instead.
  5148. */
  5149. /*!
  5150. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  5151. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  5152. */
  5153. QCPAxisTickerTime::QCPAxisTickerTime() :
  5154. mTimeFormat(QLatin1String("%h:%m:%s")),
  5155. mSmallestUnit(tuSeconds),
  5156. mBiggestUnit(tuHours)
  5157. {
  5158. setTickCount(4);
  5159. mFieldWidth[tuMilliseconds] = 3;
  5160. mFieldWidth[tuSeconds] = 2;
  5161. mFieldWidth[tuMinutes] = 2;
  5162. mFieldWidth[tuHours] = 2;
  5163. mFieldWidth[tuDays] = 1;
  5164. mFormatPattern[tuMilliseconds] = QLatin1String("%z");
  5165. mFormatPattern[tuSeconds] = QLatin1String("%s");
  5166. mFormatPattern[tuMinutes] = QLatin1String("%m");
  5167. mFormatPattern[tuHours] = QLatin1String("%h");
  5168. mFormatPattern[tuDays] = QLatin1String("%d");
  5169. }
  5170. /*!
  5171. Sets the format that will be used to display time in the tick labels.
  5172. The available patterns are:
  5173. - %%z for milliseconds
  5174. - %%s for seconds
  5175. - %%m for minutes
  5176. - %%h for hours
  5177. - %%d for days
  5178. The field width (zero padding) can be controlled for each unit with \ref setFieldWidth.
  5179. The largest unit that appears in \a format will carry all the remaining time of a certain tick
  5180. coordinate, even if it overflows the natural limit of the unit. For example, if %%m is the
  5181. largest unit it might become larger than 59 in order to consume larger time values. If on the
  5182. other hand %%h is available, the minutes will wrap around to zero after 59 and the time will
  5183. carry to the hour digit.
  5184. */
  5185. void QCPAxisTickerTime::setTimeFormat(const QString &format)
  5186. {
  5187. mTimeFormat = format;
  5188. // determine smallest and biggest unit in format, to optimize unit replacement and allow biggest
  5189. // unit to consume remaining time of a tick value and grow beyond its modulo (e.g. min > 59)
  5190. mSmallestUnit = tuMilliseconds;
  5191. mBiggestUnit = tuMilliseconds;
  5192. bool hasSmallest = false;
  5193. for (int i = tuMilliseconds; i <= tuDays; ++i)
  5194. {
  5195. TimeUnit unit = static_cast<TimeUnit>(i);
  5196. if (mTimeFormat.contains(mFormatPattern.value(unit)))
  5197. {
  5198. if (!hasSmallest)
  5199. {
  5200. mSmallestUnit = unit;
  5201. hasSmallest = true;
  5202. }
  5203. mBiggestUnit = unit;
  5204. }
  5205. }
  5206. }
  5207. /*!
  5208. Sets the field widh of the specified \a unit to be \a width digits, when displayed in the tick
  5209. label. If the number for the specific unit is shorter than \a width, it will be padded with an
  5210. according number of zeros to the left in order to reach the field width.
  5211. \see setTimeFormat
  5212. */
  5213. void QCPAxisTickerTime::setFieldWidth(QCPAxisTickerTime::TimeUnit unit, int width)
  5214. {
  5215. mFieldWidth[unit] = qMax(width, 1);
  5216. }
  5217. /*! \internal
  5218. Returns the tick step appropriate for time displays, depending on the provided \a range and the
  5219. smallest available time unit in the current format (\ref setTimeFormat). For example if the unit
  5220. of seconds isn't available in the format, this method will not generate steps (like 2.5 minutes)
  5221. that require sub-minute precision to be displayed correctly.
  5222. \seebaseclassmethod
  5223. */
  5224. double QCPAxisTickerTime::getTickStep(const QCPRange &range)
  5225. {
  5226. double result = range.size()/(double)(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  5227. if (result < 1) // ideal tick step is below 1 second -> use normal clean mantissa algorithm in units of seconds
  5228. {
  5229. if (mSmallestUnit == tuMilliseconds)
  5230. result = qMax(cleanMantissa(result), 0.001); // smallest tick step is 1 millisecond
  5231. else // have no milliseconds available in format, so stick with 1 second tickstep
  5232. result = 1.0;
  5233. } else if (result < 3600*24) // below a day
  5234. {
  5235. // the filling of availableSteps seems a bit contorted but it fills in a sorted fashion and thus saves a post-fill sorting run
  5236. QVector<double> availableSteps;
  5237. // seconds range:
  5238. if (mSmallestUnit <= tuSeconds)
  5239. availableSteps << 1;
  5240. if (mSmallestUnit == tuMilliseconds)
  5241. availableSteps << 2.5; // only allow half second steps if milliseconds are there to display it
  5242. else if (mSmallestUnit == tuSeconds)
  5243. availableSteps << 2;
  5244. if (mSmallestUnit <= tuSeconds)
  5245. availableSteps << 5 << 10 << 15 << 30;
  5246. // minutes range:
  5247. if (mSmallestUnit <= tuMinutes)
  5248. availableSteps << 1*60;
  5249. if (mSmallestUnit <= tuSeconds)
  5250. availableSteps << 2.5*60; // only allow half minute steps if seconds are there to display it
  5251. else if (mSmallestUnit == tuMinutes)
  5252. availableSteps << 2*60;
  5253. if (mSmallestUnit <= tuMinutes)
  5254. availableSteps << 5*60 << 10*60 << 15*60 << 30*60;
  5255. // hours range:
  5256. if (mSmallestUnit <= tuHours)
  5257. availableSteps << 1*3600 << 2*3600 << 3*3600 << 6*3600 << 12*3600 << 24*3600;
  5258. // pick available step that is most appropriate to approximate ideal step:
  5259. result = pickClosest(result, availableSteps);
  5260. } else // more than a day, go back to normal clean mantissa algorithm but in units of days
  5261. {
  5262. const double secondsPerDay = 3600*24;
  5263. result = cleanMantissa(result/secondsPerDay)*secondsPerDay;
  5264. }
  5265. return result;
  5266. }
  5267. /*! \internal
  5268. Returns the sub tick count appropriate for the provided \a tickStep and time displays.
  5269. \seebaseclassmethod
  5270. */
  5271. int QCPAxisTickerTime::getSubTickCount(double tickStep)
  5272. {
  5273. int result = QCPAxisTicker::getSubTickCount(tickStep);
  5274. switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day range (as specified in getTickStep)
  5275. {
  5276. case 5*60: result = 4; break;
  5277. case 10*60: result = 1; break;
  5278. case 15*60: result = 2; break;
  5279. case 30*60: result = 1; break;
  5280. case 60*60: result = 3; break;
  5281. case 3600*2: result = 3; break;
  5282. case 3600*3: result = 2; break;
  5283. case 3600*6: result = 1; break;
  5284. case 3600*12: result = 3; break;
  5285. case 3600*24: result = 3; break;
  5286. }
  5287. return result;
  5288. }
  5289. /*! \internal
  5290. Returns the tick label corresponding to the provided \a tick and the configured format and field
  5291. widths (\ref setTimeFormat, \ref setFieldWidth).
  5292. \seebaseclassmethod
  5293. */
  5294. QString QCPAxisTickerTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  5295. {
  5296. Q_UNUSED(precision)
  5297. Q_UNUSED(formatChar)
  5298. Q_UNUSED(locale)
  5299. bool negative = tick < 0;
  5300. if (negative) tick *= -1;
  5301. double values[tuDays+1]; // contains the msec/sec/min/... value with its respective modulo (e.g. minute 0..59)
  5302. double restValues[tuDays+1]; // contains the msec/sec/min/... value as if it's the largest available unit and thus consumes the remaining time
  5303. restValues[tuMilliseconds] = tick*1000;
  5304. values[tuMilliseconds] = modf(restValues[tuMilliseconds]/1000, &restValues[tuSeconds])*1000;
  5305. values[tuSeconds] = modf(restValues[tuSeconds]/60, &restValues[tuMinutes])*60;
  5306. values[tuMinutes] = modf(restValues[tuMinutes]/60, &restValues[tuHours])*60;
  5307. values[tuHours] = modf(restValues[tuHours]/24, &restValues[tuDays])*24;
  5308. // no need to set values[tuDays] because days are always a rest value (there is no higher unit so it consumes all remaining time)
  5309. QString result = mTimeFormat;
  5310. for (int i = mSmallestUnit; i <= mBiggestUnit; ++i)
  5311. {
  5312. TimeUnit iUnit = static_cast<TimeUnit>(i);
  5313. replaceUnit(result, iUnit, qRound(iUnit == mBiggestUnit ? restValues[iUnit] : values[iUnit]));
  5314. }
  5315. if (negative)
  5316. result.prepend(QLatin1Char('-'));
  5317. return result;
  5318. }
  5319. /*! \internal
  5320. Replaces all occurrences of the format pattern belonging to \a unit in \a text with the specified
  5321. \a value, using the field width as specified with \ref setFieldWidth for the \a unit.
  5322. */
  5323. void QCPAxisTickerTime::replaceUnit(QString &text, QCPAxisTickerTime::TimeUnit unit, int value) const
  5324. {
  5325. QString valueStr = QString::number(value);
  5326. while (valueStr.size() < mFieldWidth.value(unit))
  5327. valueStr.prepend(QLatin1Char('0'));
  5328. text.replace(mFormatPattern.value(unit), valueStr);
  5329. }
  5330. /* end of 'src/axis/axistickertime.cpp' */
  5331. /* including file 'src/axis/axistickerfixed.cpp', size 5583 */
  5332. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  5333. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5334. //////////////////// QCPAxisTickerFixed
  5335. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5336. /*! \class QCPAxisTickerFixed
  5337. \brief Specialized axis ticker with a fixed tick step
  5338. \image html axisticker-fixed.png
  5339. This QCPAxisTicker subclass generates ticks with a fixed tick step set with \ref setTickStep. It
  5340. is also possible to allow integer multiples and integer powers of the specified tick step with
  5341. \ref setScaleStrategy.
  5342. A typical application of this ticker is to make an axis only display integers, by setting the
  5343. tick step of the ticker to 1.0 and the scale strategy to \ref ssMultiples.
  5344. Another case is when a certain number has a special meaning and axis ticks should only appear at
  5345. multiples of that value. In this case you might also want to consider \ref QCPAxisTickerPi
  5346. because despite the name it is not limited to only pi symbols/values.
  5347. The ticker can be created and assigned to an axis like this:
  5348. \snippet documentation/doc-image-generator/mainwindow.cpp axistickerfixed-creation
  5349. */
  5350. /*!
  5351. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  5352. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  5353. */
  5354. QCPAxisTickerFixed::QCPAxisTickerFixed() :
  5355. mTickStep(1.0),
  5356. mScaleStrategy(ssNone)
  5357. {
  5358. }
  5359. /*!
  5360. Sets the fixed tick interval to \a step.
  5361. The axis ticker will only use this tick step when generating axis ticks. This might cause a very
  5362. high tick density and overlapping labels if the axis range is zoomed out. Using \ref
  5363. setScaleStrategy it is possible to relax the fixed step and also allow multiples or powers of \a
  5364. step. This will enable the ticker to reduce the number of ticks to a reasonable amount (see \ref
  5365. setTickCount).
  5366. */
  5367. void QCPAxisTickerFixed::setTickStep(double step)
  5368. {
  5369. if (step > 0)
  5370. mTickStep = step;
  5371. else
  5372. qDebug() << Q_FUNC_INFO << "tick step must be greater than zero:" << step;
  5373. }
  5374. /*!
  5375. Sets whether the specified tick step (\ref setTickStep) is absolutely fixed or whether
  5376. modifications may be applied to it before calculating the finally used tick step, such as
  5377. permitting multiples or powers. See \ref ScaleStrategy for details.
  5378. The default strategy is \ref ssNone, which means the tick step is absolutely fixed.
  5379. */
  5380. void QCPAxisTickerFixed::setScaleStrategy(QCPAxisTickerFixed::ScaleStrategy strategy)
  5381. {
  5382. mScaleStrategy = strategy;
  5383. }
  5384. /*! \internal
  5385. Determines the actually used tick step from the specified tick step and scale strategy (\ref
  5386. setTickStep, \ref setScaleStrategy).
  5387. This method either returns the specified tick step exactly, or, if the scale strategy is not \ref
  5388. ssNone, a modification of it to allow varying the number of ticks in the current axis range.
  5389. \seebaseclassmethod
  5390. */
  5391. double QCPAxisTickerFixed::getTickStep(const QCPRange &range)
  5392. {
  5393. switch (mScaleStrategy)
  5394. {
  5395. case ssNone:
  5396. {
  5397. return mTickStep;
  5398. }
  5399. case ssMultiples:
  5400. {
  5401. double exactStep = range.size()/(double)(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  5402. if (exactStep < mTickStep)
  5403. return mTickStep;
  5404. else
  5405. return (qint64)(cleanMantissa(exactStep/mTickStep)+0.5)*mTickStep;
  5406. }
  5407. case ssPowers:
  5408. {
  5409. double exactStep = range.size()/(double)(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  5410. return qPow(mTickStep, (int)(qLn(exactStep)/qLn(mTickStep)+0.5));
  5411. }
  5412. }
  5413. return mTickStep;
  5414. }
  5415. /* end of 'src/axis/axistickerfixed.cpp' */
  5416. /* including file 'src/axis/axistickertext.cpp', size 8653 */
  5417. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  5418. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5419. //////////////////// QCPAxisTickerText
  5420. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5421. /*! \class QCPAxisTickerText
  5422. \brief Specialized axis ticker which allows arbitrary labels at specified coordinates
  5423. \image html axisticker-text.png
  5424. This QCPAxisTicker subclass generates ticks which can be directly specified by the user as
  5425. coordinates and associated strings. They can be passed as a whole with \ref setTicks or one at a
  5426. time with \ref addTick. Alternatively you can directly access the internal storage via \ref ticks
  5427. and modify the tick/label data there.
  5428. This is useful for cases where the axis represents categories rather than numerical values.
  5429. If you are updating the ticks of this ticker regularly and in a dynamic fasion (e.g. dependent on
  5430. the axis range), it is a sign that you should probably create an own ticker by subclassing
  5431. QCPAxisTicker, instead of using this one.
  5432. The ticker can be created and assigned to an axis like this:
  5433. \snippet documentation/doc-image-generator/mainwindow.cpp axistickertext-creation
  5434. */
  5435. /* start of documentation of inline functions */
  5436. /*! \fn QMap<double, QString> &QCPAxisTickerText::ticks()
  5437. Returns a non-const reference to the internal map which stores the tick coordinates and their
  5438. labels.
  5439. You can access the map directly in order to add, remove or manipulate ticks, as an alternative to
  5440. using the methods provided by QCPAxisTickerText, such as \ref setTicks and \ref addTick.
  5441. */
  5442. /* end of documentation of inline functions */
  5443. /*!
  5444. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  5445. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  5446. */
  5447. QCPAxisTickerText::QCPAxisTickerText() :
  5448. mSubTickCount(0)
  5449. {
  5450. }
  5451. /*! \overload
  5452. Sets the ticks that shall appear on the axis. The map key of \a ticks corresponds to the axis
  5453. coordinate, and the map value is the string that will appear as tick label.
  5454. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  5455. getter.
  5456. \see addTicks, addTick, clear
  5457. */
  5458. void QCPAxisTickerText::setTicks(const QMap<double, QString> &ticks)
  5459. {
  5460. mTicks = ticks;
  5461. }
  5462. /*! \overload
  5463. Sets the ticks that shall appear on the axis. The entries of \a positions correspond to the axis
  5464. coordinates, and the entries of \a labels are the respective strings that will appear as tick
  5465. labels.
  5466. \see addTicks, addTick, clear
  5467. */
  5468. void QCPAxisTickerText::setTicks(const QVector<double> &positions, const QVector<QString> labels)
  5469. {
  5470. clear();
  5471. addTicks(positions, labels);
  5472. }
  5473. /*!
  5474. Sets the number of sub ticks that shall appear between ticks. For QCPAxisTickerText, there is no
  5475. automatic sub tick count calculation. So if sub ticks are needed, they must be configured with this
  5476. method.
  5477. */
  5478. void QCPAxisTickerText::setSubTickCount(int subTicks)
  5479. {
  5480. if (subTicks >= 0)
  5481. mSubTickCount = subTicks;
  5482. else
  5483. qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks;
  5484. }
  5485. /*!
  5486. Clears all ticks.
  5487. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  5488. getter.
  5489. \see setTicks, addTicks, addTick
  5490. */
  5491. void QCPAxisTickerText::clear()
  5492. {
  5493. mTicks.clear();
  5494. }
  5495. /*!
  5496. Adds a single tick to the axis at the given axis coordinate \a position, with the provided tick \a
  5497. label.
  5498. \see addTicks, setTicks, clear
  5499. */
  5500. void QCPAxisTickerText::addTick(double position, QString label)
  5501. {
  5502. mTicks.insert(position, label);
  5503. }
  5504. /*! \overload
  5505. Adds the provided \a ticks to the ones already existing. The map key of \a ticks corresponds to
  5506. the axis coordinate, and the map value is the string that will appear as tick label.
  5507. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  5508. getter.
  5509. \see addTick, setTicks, clear
  5510. */
  5511. void QCPAxisTickerText::addTicks(const QMap<double, QString> &ticks)
  5512. {
  5513. mTicks.unite(ticks);
  5514. }
  5515. /*! \overload
  5516. Adds the provided ticks to the ones already existing. The entries of \a positions correspond to
  5517. the axis coordinates, and the entries of \a labels are the respective strings that will appear as
  5518. tick labels.
  5519. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  5520. getter.
  5521. \see addTick, setTicks, clear
  5522. */
  5523. void QCPAxisTickerText::addTicks(const QVector<double> &positions, const QVector<QString> &labels)
  5524. {
  5525. if (positions.size() != labels.size())
  5526. qDebug() << Q_FUNC_INFO << "passed unequal length vectors for positions and labels:" << positions.size() << labels.size();
  5527. int n = qMin(positions.size(), labels.size());
  5528. for (int i=0; i<n; ++i)
  5529. mTicks.insert(positions.at(i), labels.at(i));
  5530. }
  5531. /*!
  5532. Since the tick coordinates are provided externally, this method implementation does nothing.
  5533. \seebaseclassmethod
  5534. */
  5535. double QCPAxisTickerText::getTickStep(const QCPRange &range)
  5536. {
  5537. // text axis ticker has manual tick positions, so doesn't need this method
  5538. Q_UNUSED(range)
  5539. return 1.0;
  5540. }
  5541. /*!
  5542. Returns the sub tick count that was configured with \ref setSubTickCount.
  5543. \seebaseclassmethod
  5544. */
  5545. int QCPAxisTickerText::getSubTickCount(double tickStep)
  5546. {
  5547. Q_UNUSED(tickStep)
  5548. return mSubTickCount;
  5549. }
  5550. /*!
  5551. Returns the tick label which corresponds to the key \a tick in the internal tick storage. Since
  5552. the labels are provided externally, \a locale, \a formatChar, and \a precision are ignored.
  5553. \seebaseclassmethod
  5554. */
  5555. QString QCPAxisTickerText::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  5556. {
  5557. Q_UNUSED(locale)
  5558. Q_UNUSED(formatChar)
  5559. Q_UNUSED(precision)
  5560. return mTicks.value(tick);
  5561. }
  5562. /*!
  5563. Returns the externally provided tick coordinates which are in the specified \a range. If
  5564. available, one tick above and below the range is provided in addition, to allow possible sub tick
  5565. calculation. The parameter \a tickStep is ignored.
  5566. \seebaseclassmethod
  5567. */
  5568. QVector<double> QCPAxisTickerText::createTickVector(double tickStep, const QCPRange &range)
  5569. {
  5570. Q_UNUSED(tickStep)
  5571. QVector<double> result;
  5572. if (mTicks.isEmpty())
  5573. return result;
  5574. QMap<double, QString>::const_iterator start = mTicks.lowerBound(range.lower);
  5575. QMap<double, QString>::const_iterator end = mTicks.upperBound(range.upper);
  5576. // this method should try to give one tick outside of range so proper subticks can be generated:
  5577. if (start != mTicks.constBegin()) --start;
  5578. if (end != mTicks.constEnd()) ++end;
  5579. for (QMap<double, QString>::const_iterator it = start; it != end; ++it)
  5580. result.append(it.key());
  5581. return result;
  5582. }
  5583. /* end of 'src/axis/axistickertext.cpp' */
  5584. /* including file 'src/axis/axistickerpi.cpp', size 11170 */
  5585. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  5586. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5587. //////////////////// QCPAxisTickerPi
  5588. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5589. /*! \class QCPAxisTickerPi
  5590. \brief Specialized axis ticker to display ticks in units of an arbitrary constant, for example pi
  5591. \image html axisticker-pi.png
  5592. This QCPAxisTicker subclass generates ticks that are expressed with respect to a given symbolic
  5593. constant with a numerical value specified with \ref setPiValue and an appearance in the tick
  5594. labels specified with \ref setPiSymbol.
  5595. Ticks may be generated at fractions of the symbolic constant. How these fractions appear in the
  5596. tick label can be configured with \ref setFractionStyle.
  5597. The ticker can be created and assigned to an axis like this:
  5598. \snippet documentation/doc-image-generator/mainwindow.cpp axistickerpi-creation
  5599. */
  5600. /*!
  5601. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  5602. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  5603. */
  5604. QCPAxisTickerPi::QCPAxisTickerPi() :
  5605. mPiSymbol(QLatin1String(" ")+QChar(0x03C0)),
  5606. mPiValue(M_PI),
  5607. mPeriodicity(0),
  5608. mFractionStyle(fsUnicodeFractions),
  5609. mPiTickStep(0)
  5610. {
  5611. setTickCount(4);
  5612. }
  5613. /*!
  5614. Sets how the symbol part (which is always a suffix to the number) shall appear in the axis tick
  5615. label.
  5616. If a space shall appear between the number and the symbol, make sure the space is contained in \a
  5617. symbol.
  5618. */
  5619. void QCPAxisTickerPi::setPiSymbol(QString symbol)
  5620. {
  5621. mPiSymbol = symbol;
  5622. }
  5623. /*!
  5624. Sets the numerical value that the symbolic constant has.
  5625. This will be used to place the appropriate fractions of the symbol at the respective axis
  5626. coordinates.
  5627. */
  5628. void QCPAxisTickerPi::setPiValue(double pi)
  5629. {
  5630. mPiValue = pi;
  5631. }
  5632. /*!
  5633. Sets whether the axis labels shall appear periodicly and if so, at which multiplicity of the
  5634. symbolic constant.
  5635. To disable periodicity, set \a multiplesOfPi to zero.
  5636. For example, an axis that identifies 0 with 2pi would set \a multiplesOfPi to two.
  5637. */
  5638. void QCPAxisTickerPi::setPeriodicity(int multiplesOfPi)
  5639. {
  5640. mPeriodicity = qAbs(multiplesOfPi);
  5641. }
  5642. /*!
  5643. Sets how the numerical/fractional part preceding the symbolic constant is displayed in tick
  5644. labels. See \ref FractionStyle for the various options.
  5645. */
  5646. void QCPAxisTickerPi::setFractionStyle(QCPAxisTickerPi::FractionStyle style)
  5647. {
  5648. mFractionStyle = style;
  5649. }
  5650. /*! \internal
  5651. Returns the tick step, using the constant's value (\ref setPiValue) as base unit. In consequence
  5652. the numerical/fractional part preceding the symbolic constant is made to have a readable
  5653. mantissa.
  5654. \seebaseclassmethod
  5655. */
  5656. double QCPAxisTickerPi::getTickStep(const QCPRange &range)
  5657. {
  5658. mPiTickStep = range.size()/mPiValue/(double)(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  5659. mPiTickStep = cleanMantissa(mPiTickStep);
  5660. return mPiTickStep*mPiValue;
  5661. }
  5662. /*! \internal
  5663. Returns the sub tick count, using the constant's value (\ref setPiValue) as base unit. In
  5664. consequence the sub ticks divide the numerical/fractional part preceding the symbolic constant
  5665. reasonably, and not the total tick coordinate.
  5666. \seebaseclassmethod
  5667. */
  5668. int QCPAxisTickerPi::getSubTickCount(double tickStep)
  5669. {
  5670. return QCPAxisTicker::getSubTickCount(tickStep/mPiValue);
  5671. }
  5672. /*! \internal
  5673. Returns the tick label as a fractional/numerical part and a symbolic string as suffix. The
  5674. formatting of the fraction is done according to the specified \ref setFractionStyle. The appended
  5675. symbol is specified with \ref setPiSymbol.
  5676. \seebaseclassmethod
  5677. */
  5678. QString QCPAxisTickerPi::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  5679. {
  5680. double tickInPis = tick/mPiValue;
  5681. if (mPeriodicity > 0)
  5682. tickInPis = fmod(tickInPis, mPeriodicity);
  5683. if (mFractionStyle != fsFloatingPoint && mPiTickStep > 0.09 && mPiTickStep < 50)
  5684. {
  5685. // simply construct fraction from decimal like 1.234 -> 1234/1000 and then simplify fraction, smaller digits are irrelevant due to mPiTickStep conditional above
  5686. int denominator = 1000;
  5687. int numerator = qRound(tickInPis*denominator);
  5688. simplifyFraction(numerator, denominator);
  5689. if (qAbs(numerator) == 1 && denominator == 1)
  5690. return (numerator < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed();
  5691. else if (numerator == 0)
  5692. return QLatin1String("0");
  5693. else
  5694. return fractionToString(numerator, denominator) + mPiSymbol;
  5695. } else
  5696. {
  5697. if (qFuzzyIsNull(tickInPis))
  5698. return QLatin1String("0");
  5699. else if (qFuzzyCompare(qAbs(tickInPis), 1.0))
  5700. return (tickInPis < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed();
  5701. else
  5702. return QCPAxisTicker::getTickLabel(tickInPis, locale, formatChar, precision) + mPiSymbol;
  5703. }
  5704. }
  5705. /*! \internal
  5706. Takes the fraction given by \a numerator and \a denominator and modifies the values to make sure
  5707. the fraction is in irreducible form, i.e. numerator and denominator don't share any common
  5708. factors which could be cancelled.
  5709. */
  5710. void QCPAxisTickerPi::simplifyFraction(int &numerator, int &denominator) const
  5711. {
  5712. if (numerator == 0 || denominator == 0)
  5713. return;
  5714. int num = numerator;
  5715. int denom = denominator;
  5716. while (denom != 0) // euclidean gcd algorithm
  5717. {
  5718. int oldDenom = denom;
  5719. denom = num % denom;
  5720. num = oldDenom;
  5721. }
  5722. // num is now gcd of numerator and denominator
  5723. numerator /= num;
  5724. denominator /= num;
  5725. }
  5726. /*! \internal
  5727. Takes the fraction given by \a numerator and \a denominator and returns a string representation.
  5728. The result depends on the configured fraction style (\ref setFractionStyle).
  5729. This method is used to format the numerical/fractional part when generating tick labels. It
  5730. simplifies the passed fraction to an irreducible form using \ref simplifyFraction and factors out
  5731. any integer parts of the fraction (e.g. "10/4" becomes "2 1/2").
  5732. */
  5733. QString QCPAxisTickerPi::fractionToString(int numerator, int denominator) const
  5734. {
  5735. if (denominator == 0)
  5736. {
  5737. qDebug() << Q_FUNC_INFO << "called with zero denominator";
  5738. return QString();
  5739. }
  5740. if (mFractionStyle == fsFloatingPoint) // should never be the case when calling this function
  5741. {
  5742. qDebug() << Q_FUNC_INFO << "shouldn't be called with fraction style fsDecimal";
  5743. return QString::number(numerator/(double)denominator); // failsafe
  5744. }
  5745. int sign = numerator*denominator < 0 ? -1 : 1;
  5746. numerator = qAbs(numerator);
  5747. denominator = qAbs(denominator);
  5748. if (denominator == 1)
  5749. {
  5750. return QString::number(sign*numerator);
  5751. } else
  5752. {
  5753. int integerPart = numerator/denominator;
  5754. int remainder = numerator%denominator;
  5755. if (remainder == 0)
  5756. {
  5757. return QString::number(sign*integerPart);
  5758. } else
  5759. {
  5760. if (mFractionStyle == fsAsciiFractions)
  5761. {
  5762. return QString(QLatin1String("%1%2%3/%4"))
  5763. .arg(sign == -1 ? QLatin1String("-") : QLatin1String(""))
  5764. .arg(integerPart > 0 ? QString::number(integerPart)+QLatin1String(" ") : QLatin1String(""))
  5765. .arg(remainder)
  5766. .arg(denominator);
  5767. } else if (mFractionStyle == fsUnicodeFractions)
  5768. {
  5769. return QString(QLatin1String("%1%2%3"))
  5770. .arg(sign == -1 ? QLatin1String("-") : QLatin1String(""))
  5771. .arg(integerPart > 0 ? QString::number(integerPart) : QLatin1String(""))
  5772. .arg(unicodeFraction(remainder, denominator));
  5773. }
  5774. }
  5775. }
  5776. return QString();
  5777. }
  5778. /*! \internal
  5779. Returns the unicode string representation of the fraction given by \a numerator and \a
  5780. denominator. This is the representation used in \ref fractionToString when the fraction style
  5781. (\ref setFractionStyle) is \ref fsUnicodeFractions.
  5782. This method doesn't use the single-character common fractions but builds each fraction from a
  5783. superscript unicode number, the unicode fraction character, and a subscript unicode number.
  5784. */
  5785. QString QCPAxisTickerPi::unicodeFraction(int numerator, int denominator) const
  5786. {
  5787. return unicodeSuperscript(numerator)+QChar(0x2044)+unicodeSubscript(denominator);
  5788. }
  5789. /*! \internal
  5790. Returns the unicode string representing \a number as superscript. This is used to build
  5791. unicode fractions in \ref unicodeFraction.
  5792. */
  5793. QString QCPAxisTickerPi::unicodeSuperscript(int number) const
  5794. {
  5795. if (number == 0)
  5796. return QString(QChar(0x2070));
  5797. QString result;
  5798. while (number > 0)
  5799. {
  5800. const int digit = number%10;
  5801. switch (digit)
  5802. {
  5803. case 1: { result.prepend(QChar(0x00B9)); break; }
  5804. case 2: { result.prepend(QChar(0x00B2)); break; }
  5805. case 3: { result.prepend(QChar(0x00B3)); break; }
  5806. default: { result.prepend(QChar(0x2070+digit)); break; }
  5807. }
  5808. number /= 10;
  5809. }
  5810. return result;
  5811. }
  5812. /*! \internal
  5813. Returns the unicode string representing \a number as subscript. This is used to build unicode
  5814. fractions in \ref unicodeFraction.
  5815. */
  5816. QString QCPAxisTickerPi::unicodeSubscript(int number) const
  5817. {
  5818. if (number == 0)
  5819. return QString(QChar(0x2080));
  5820. QString result;
  5821. while (number > 0)
  5822. {
  5823. result.prepend(QChar(0x2080+number%10));
  5824. number /= 10;
  5825. }
  5826. return result;
  5827. }
  5828. /* end of 'src/axis/axistickerpi.cpp' */
  5829. /* including file 'src/axis/axistickerlog.cpp', size 7106 */
  5830. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  5831. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5832. //////////////////// QCPAxisTickerLog
  5833. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5834. /*! \class QCPAxisTickerLog
  5835. \brief Specialized axis ticker suited for logarithmic axes
  5836. \image html axisticker-log.png
  5837. This QCPAxisTicker subclass generates ticks with unequal tick intervals suited for logarithmic
  5838. axis scales. The ticks are placed at powers of the specified log base (\ref setLogBase).
  5839. Especially in the case of a log base equal to 10 (the default), it might be desirable to have
  5840. tick labels in the form of powers of ten without mantissa display. To achieve this, set the
  5841. number precision (\ref QCPAxis::setNumberPrecision) to zero and the number format (\ref
  5842. QCPAxis::setNumberFormat) to scientific (exponential) display with beautifully typeset decimal
  5843. powers, so a format string of <tt>"eb"</tt>. This will result in the following axis tick labels:
  5844. \image html axisticker-log-powers.png
  5845. The ticker can be created and assigned to an axis like this:
  5846. \snippet documentation/doc-image-generator/mainwindow.cpp axistickerlog-creation
  5847. */
  5848. /*!
  5849. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  5850. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  5851. */
  5852. QCPAxisTickerLog::QCPAxisTickerLog() :
  5853. mLogBase(10.0),
  5854. mSubTickCount(8), // generates 10 intervals
  5855. mLogBaseLnInv(1.0/qLn(mLogBase))
  5856. {
  5857. }
  5858. /*!
  5859. Sets the logarithm base used for tick coordinate generation. The ticks will be placed at integer
  5860. powers of \a base.
  5861. */
  5862. void QCPAxisTickerLog::setLogBase(double base)
  5863. {
  5864. if (base > 0)
  5865. {
  5866. mLogBase = base;
  5867. mLogBaseLnInv = 1.0/qLn(mLogBase);
  5868. } else
  5869. qDebug() << Q_FUNC_INFO << "log base has to be greater than zero:" << base;
  5870. }
  5871. /*!
  5872. Sets the number of sub ticks in a tick interval. Within each interval, the sub ticks are spaced
  5873. linearly to provide a better visual guide, so the sub tick density increases toward the higher
  5874. tick.
  5875. Note that \a subTicks is the number of sub ticks (not sub intervals) in one tick interval. So in
  5876. the case of logarithm base 10 an intuitive sub tick spacing would be achieved with eight sub
  5877. ticks (the default). This means e.g. between the ticks 10 and 100 there will be eight ticks,
  5878. namely at 20, 30, 40, 50, 60, 70, 80 and 90.
  5879. */
  5880. void QCPAxisTickerLog::setSubTickCount(int subTicks)
  5881. {
  5882. if (subTicks >= 0)
  5883. mSubTickCount = subTicks;
  5884. else
  5885. qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks;
  5886. }
  5887. /*! \internal
  5888. Since logarithmic tick steps are necessarily different for each tick interval, this method does
  5889. nothing in the case of QCPAxisTickerLog
  5890. \seebaseclassmethod
  5891. */
  5892. double QCPAxisTickerLog::getTickStep(const QCPRange &range)
  5893. {
  5894. // Logarithmic axis ticker has unequal tick spacing, so doesn't need this method
  5895. Q_UNUSED(range)
  5896. return 1.0;
  5897. }
  5898. /*! \internal
  5899. Returns the sub tick count specified in \ref setSubTickCount. For QCPAxisTickerLog, there is no
  5900. automatic sub tick count calculation necessary.
  5901. \seebaseclassmethod
  5902. */
  5903. int QCPAxisTickerLog::getSubTickCount(double tickStep)
  5904. {
  5905. Q_UNUSED(tickStep)
  5906. return mSubTickCount;
  5907. }
  5908. /*! \internal
  5909. Creates ticks with a spacing given by the logarithm base and an increasing integer power in the
  5910. provided \a range. The step in which the power increases tick by tick is chosen in order to keep
  5911. the total number of ticks as close as possible to the tick count (\ref setTickCount). The
  5912. parameter \a tickStep is ignored for QCPAxisTickerLog
  5913. \seebaseclassmethod
  5914. */
  5915. QVector<double> QCPAxisTickerLog::createTickVector(double tickStep, const QCPRange &range)
  5916. {
  5917. Q_UNUSED(tickStep)
  5918. QVector<double> result;
  5919. if (range.lower > 0 && range.upper > 0) // positive range
  5920. {
  5921. double exactPowerStep = qLn(range.upper/range.lower)*mLogBaseLnInv/(double)(mTickCount+1e-10);
  5922. double newLogBase = qPow(mLogBase, qMax((int)cleanMantissa(exactPowerStep), 1));
  5923. double currentTick = qPow(newLogBase, qFloor(qLn(range.lower)/qLn(newLogBase)));
  5924. result.append(currentTick);
  5925. while (currentTick < range.upper && currentTick > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
  5926. {
  5927. currentTick *= newLogBase;
  5928. result.append(currentTick);
  5929. }
  5930. } else if (range.lower < 0 && range.upper < 0) // negative range
  5931. {
  5932. double exactPowerStep = qLn(range.lower/range.upper)*mLogBaseLnInv/(double)(mTickCount+1e-10);
  5933. double newLogBase = qPow(mLogBase, qMax((int)cleanMantissa(exactPowerStep), 1));
  5934. double currentTick = -qPow(newLogBase, qCeil(qLn(-range.lower)/qLn(newLogBase)));
  5935. result.append(currentTick);
  5936. while (currentTick < range.upper && currentTick < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
  5937. {
  5938. currentTick /= newLogBase;
  5939. result.append(currentTick);
  5940. }
  5941. } else // invalid range for logarithmic scale, because lower and upper have different sign
  5942. {
  5943. qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << range.lower << ".." << range.upper;
  5944. }
  5945. return result;
  5946. }
  5947. /* end of 'src/axis/axistickerlog.cpp' */
  5948. /* including file 'src/axis/axis.cpp', size 99397 */
  5949. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  5950. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5951. //////////////////// QCPGrid
  5952. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5953. /*! \class QCPGrid
  5954. \brief Responsible for drawing the grid of a QCPAxis.
  5955. This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the
  5956. grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref
  5957. QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself.
  5958. The axis and grid drawing was split into two classes to allow them to be placed on different
  5959. layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid
  5960. in the background and the axes in the foreground, and any plottables/items in between. This
  5961. described situation is the default setup, see the QCPLayer documentation.
  5962. */
  5963. /*!
  5964. Creates a QCPGrid instance and sets default values.
  5965. You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid.
  5966. */
  5967. QCPGrid::QCPGrid(QCPAxis *parentAxis) :
  5968. QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis),
  5969. mParentAxis(parentAxis)
  5970. {
  5971. // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called
  5972. setParent(parentAxis);
  5973. setPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
  5974. setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
  5975. setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine));
  5976. setSubGridVisible(false);
  5977. setAntialiased(false);
  5978. setAntialiasedSubGrid(false);
  5979. setAntialiasedZeroLine(false);
  5980. }
  5981. /*!
  5982. Sets whether grid lines at sub tick marks are drawn.
  5983. \see setSubGridPen
  5984. */
  5985. void QCPGrid::setSubGridVisible(bool visible)
  5986. {
  5987. mSubGridVisible = visible;
  5988. }
  5989. /*!
  5990. Sets whether sub grid lines are drawn antialiased.
  5991. */
  5992. void QCPGrid::setAntialiasedSubGrid(bool enabled)
  5993. {
  5994. mAntialiasedSubGrid = enabled;
  5995. }
  5996. /*!
  5997. Sets whether zero lines are drawn antialiased.
  5998. */
  5999. void QCPGrid::setAntialiasedZeroLine(bool enabled)
  6000. {
  6001. mAntialiasedZeroLine = enabled;
  6002. }
  6003. /*!
  6004. Sets the pen with which (major) grid lines are drawn.
  6005. */
  6006. void QCPGrid::setPen(const QPen &pen)
  6007. {
  6008. mPen = pen;
  6009. }
  6010. /*!
  6011. Sets the pen with which sub grid lines are drawn.
  6012. */
  6013. void QCPGrid::setSubGridPen(const QPen &pen)
  6014. {
  6015. mSubGridPen = pen;
  6016. }
  6017. /*!
  6018. Sets the pen with which zero lines are drawn.
  6019. Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid
  6020. lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen.
  6021. */
  6022. void QCPGrid::setZeroLinePen(const QPen &pen)
  6023. {
  6024. mZeroLinePen = pen;
  6025. }
  6026. /*! \internal
  6027. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  6028. before drawing the major grid lines.
  6029. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  6030. This function takes into account the local setting of the antialiasing flag as well as the
  6031. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  6032. QCustomPlot::setNotAntialiasedElements.
  6033. \see setAntialiased
  6034. */
  6035. void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const
  6036. {
  6037. applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid);
  6038. }
  6039. /*! \internal
  6040. Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning
  6041. over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen).
  6042. */
  6043. void QCPGrid::draw(QCPPainter *painter)
  6044. {
  6045. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  6046. if (mParentAxis->subTicks() && mSubGridVisible)
  6047. drawSubGridLines(painter);
  6048. drawGridLines(painter);
  6049. }
  6050. /*! \internal
  6051. Draws the main grid lines and possibly a zero line with the specified painter.
  6052. This is a helper function called by \ref draw.
  6053. */
  6054. void QCPGrid::drawGridLines(QCPPainter *painter) const
  6055. {
  6056. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  6057. const int tickCount = mParentAxis->mTickVector.size();
  6058. double t; // helper variable, result of coordinate-to-pixel transforms
  6059. if (mParentAxis->orientation() == Qt::Horizontal)
  6060. {
  6061. // draw zeroline:
  6062. int zeroLineIndex = -1;
  6063. if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
  6064. {
  6065. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  6066. painter->setPen(mZeroLinePen);
  6067. double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero
  6068. for (int i=0; i<tickCount; ++i)
  6069. {
  6070. if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
  6071. {
  6072. zeroLineIndex = i;
  6073. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
  6074. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  6075. break;
  6076. }
  6077. }
  6078. }
  6079. // draw grid lines:
  6080. applyDefaultAntialiasingHint(painter);
  6081. painter->setPen(mPen);
  6082. for (int i=0; i<tickCount; ++i)
  6083. {
  6084. if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
  6085. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
  6086. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  6087. }
  6088. } else
  6089. {
  6090. // draw zeroline:
  6091. int zeroLineIndex = -1;
  6092. if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
  6093. {
  6094. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  6095. painter->setPen(mZeroLinePen);
  6096. double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero
  6097. for (int i=0; i<tickCount; ++i)
  6098. {
  6099. if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
  6100. {
  6101. zeroLineIndex = i;
  6102. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
  6103. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  6104. break;
  6105. }
  6106. }
  6107. }
  6108. // draw grid lines:
  6109. applyDefaultAntialiasingHint(painter);
  6110. painter->setPen(mPen);
  6111. for (int i=0; i<tickCount; ++i)
  6112. {
  6113. if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
  6114. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
  6115. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  6116. }
  6117. }
  6118. }
  6119. /*! \internal
  6120. Draws the sub grid lines with the specified painter.
  6121. This is a helper function called by \ref draw.
  6122. */
  6123. void QCPGrid::drawSubGridLines(QCPPainter *painter) const
  6124. {
  6125. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  6126. applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid);
  6127. double t; // helper variable, result of coordinate-to-pixel transforms
  6128. painter->setPen(mSubGridPen);
  6129. if (mParentAxis->orientation() == Qt::Horizontal)
  6130. {
  6131. for (int i=0; i<mParentAxis->mSubTickVector.size(); ++i)
  6132. {
  6133. t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // x
  6134. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  6135. }
  6136. } else
  6137. {
  6138. for (int i=0; i<mParentAxis->mSubTickVector.size(); ++i)
  6139. {
  6140. t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // y
  6141. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  6142. }
  6143. }
  6144. }
  6145. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6146. //////////////////// QCPAxis
  6147. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6148. /*! \class QCPAxis
  6149. \brief Manages a single axis inside a QCustomPlot.
  6150. Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via
  6151. QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and
  6152. QCustomPlot::yAxis2 (right).
  6153. Axes are always part of an axis rect, see QCPAxisRect.
  6154. \image html AxisNamesOverview.png
  6155. <center>Naming convention of axis parts</center>
  6156. \n
  6157. \image html AxisRectSpacingOverview.png
  6158. <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line
  6159. on the left represents the QCustomPlot widget border.</center>
  6160. Each axis holds an instance of QCPAxisTicker which is used to generate the tick coordinates and
  6161. tick labels. You can access the currently installed \ref ticker or set a new one (possibly one of
  6162. the specialized subclasses, or your own subclass) via \ref setTicker. For details, see the
  6163. documentation of QCPAxisTicker.
  6164. */
  6165. /* start of documentation of inline functions */
  6166. /*! \fn Qt::Orientation QCPAxis::orientation() const
  6167. Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced
  6168. from the axis type (left, top, right or bottom).
  6169. \see orientation(AxisType type), pixelOrientation
  6170. */
  6171. /*! \fn QCPGrid *QCPAxis::grid() const
  6172. Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the
  6173. grid is displayed.
  6174. */
  6175. /*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type)
  6176. Returns the orientation of the specified axis type
  6177. \see orientation(), pixelOrientation
  6178. */
  6179. /*! \fn int QCPAxis::pixelOrientation() const
  6180. Returns which direction points towards higher coordinate values/keys, in pixel space.
  6181. This method returns either 1 or -1. If it returns 1, then going in the positive direction along
  6182. the orientation of the axis in pixels corresponds to going from lower to higher axis coordinates.
  6183. On the other hand, if this method returns -1, going to smaller pixel values corresponds to going
  6184. from lower to higher axis coordinates.
  6185. For example, this is useful to easily shift axis coordinates by a certain amount given in pixels,
  6186. without having to care about reversed or vertically aligned axes:
  6187. \code
  6188. double newKey = keyAxis->pixelToCoord(keyAxis->coordToPixel(oldKey)+10*keyAxis->pixelOrientation());
  6189. \endcode
  6190. \a newKey will then contain a key that is ten pixels towards higher keys, starting from \a oldKey.
  6191. */
  6192. /*! \fn QSharedPointer<QCPAxisTicker> QCPAxis::ticker() const
  6193. Returns a modifiable shared pointer to the currently installed axis ticker. The axis ticker is
  6194. responsible for generating the tick positions and tick labels of this axis. You can access the
  6195. \ref QCPAxisTicker with this method and modify basic properties such as the approximate tick count
  6196. (\ref QCPAxisTicker::setTickCount).
  6197. You can gain more control over the axis ticks by setting a different \ref QCPAxisTicker subclass, see
  6198. the documentation there. A new axis ticker can be set with \ref setTicker.
  6199. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  6200. ticker simply by passing the same shared pointer to multiple axes.
  6201. \see setTicker
  6202. */
  6203. /* end of documentation of inline functions */
  6204. /* start of documentation of signals */
  6205. /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange)
  6206. This signal is emitted when the range of this axis has changed. You can connect it to the \ref
  6207. setRange slot of another axis to communicate the new range to the other axis, in order for it to
  6208. be synchronized.
  6209. You may also manipulate/correct the range with \ref setRange in a slot connected to this signal.
  6210. This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper
  6211. range shouldn't go beyond certain values (see \ref QCPRange::bounded). For example, the following
  6212. slot would limit the x axis to ranges between 0 and 10:
  6213. \code
  6214. customPlot->xAxis->setRange(newRange.bounded(0, 10))
  6215. \endcode
  6216. */
  6217. /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange)
  6218. \overload
  6219. Additionally to the new range, this signal also provides the previous range held by the axis as
  6220. \a oldRange.
  6221. */
  6222. /*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType);
  6223. This signal is emitted when the scale type changes, by calls to \ref setScaleType
  6224. */
  6225. /*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection)
  6226. This signal is emitted when the selection state of this axis has changed, either by user interaction
  6227. or by a direct call to \ref setSelectedParts.
  6228. */
  6229. /*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts);
  6230. This signal is emitted when the selectability changes, by calls to \ref setSelectableParts
  6231. */
  6232. /* end of documentation of signals */
  6233. /*!
  6234. Constructs an Axis instance of Type \a type for the axis rect \a parent.
  6235. Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create
  6236. them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however,
  6237. create them manually and then inject them also via \ref QCPAxisRect::addAxis.
  6238. */
  6239. QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) :
  6240. QCPLayerable(parent->parentPlot(), QString(), parent),
  6241. // axis base:
  6242. mAxisType(type),
  6243. mAxisRect(parent),
  6244. mPadding(5),
  6245. mOrientation(orientation(type)),
  6246. mSelectableParts(spAxis | spTickLabels | spAxisLabel),
  6247. mSelectedParts(spNone),
  6248. mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  6249. mSelectedBasePen(QPen(Qt::blue, 2)),
  6250. // axis label:
  6251. mLabel(),
  6252. mLabelFont(mParentPlot->font()),
  6253. mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
  6254. mLabelColor(Qt::black),
  6255. mSelectedLabelColor(Qt::blue),
  6256. // tick labels:
  6257. mTickLabels(true),
  6258. mTickLabelFont(mParentPlot->font()),
  6259. mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
  6260. mTickLabelColor(Qt::black),
  6261. mSelectedTickLabelColor(Qt::blue),
  6262. mNumberPrecision(6),
  6263. mNumberFormatChar('g'),
  6264. mNumberBeautifulPowers(true),
  6265. // ticks and subticks:
  6266. mTicks(true),
  6267. mSubTicks(true),
  6268. mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  6269. mSelectedTickPen(QPen(Qt::blue, 2)),
  6270. mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  6271. mSelectedSubTickPen(QPen(Qt::blue, 2)),
  6272. // scale and range:
  6273. mRange(0, 5),
  6274. mRangeReversed(false),
  6275. mScaleType(stLinear),
  6276. // internal members:
  6277. mGrid(new QCPGrid(this)),
  6278. mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())),
  6279. mTicker(new QCPAxisTicker),
  6280. mCachedMarginValid(false),
  6281. mCachedMargin(0)
  6282. {
  6283. setParent(parent);
  6284. mGrid->setVisible(false);
  6285. setAntialiased(false);
  6286. 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
  6287. if (type == atTop)
  6288. {
  6289. setTickLabelPadding(3);
  6290. setLabelPadding(6);
  6291. } else if (type == atRight)
  6292. {
  6293. setTickLabelPadding(7);
  6294. setLabelPadding(12);
  6295. } else if (type == atBottom)
  6296. {
  6297. setTickLabelPadding(3);
  6298. setLabelPadding(3);
  6299. } else if (type == atLeft)
  6300. {
  6301. setTickLabelPadding(5);
  6302. setLabelPadding(10);
  6303. }
  6304. }
  6305. QCPAxis::~QCPAxis()
  6306. {
  6307. delete mAxisPainter;
  6308. delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order
  6309. }
  6310. /* No documentation as it is a property getter */
  6311. int QCPAxis::tickLabelPadding() const
  6312. {
  6313. return mAxisPainter->tickLabelPadding;
  6314. }
  6315. /* No documentation as it is a property getter */
  6316. double QCPAxis::tickLabelRotation() const
  6317. {
  6318. return mAxisPainter->tickLabelRotation;
  6319. }
  6320. /* No documentation as it is a property getter */
  6321. QCPAxis::LabelSide QCPAxis::tickLabelSide() const
  6322. {
  6323. return mAxisPainter->tickLabelSide;
  6324. }
  6325. /* No documentation as it is a property getter */
  6326. QString QCPAxis::numberFormat() const
  6327. {
  6328. QString result;
  6329. result.append(mNumberFormatChar);
  6330. if (mNumberBeautifulPowers)
  6331. {
  6332. result.append(QLatin1Char('b'));
  6333. if (mAxisPainter->numberMultiplyCross)
  6334. result.append(QLatin1Char('c'));
  6335. }
  6336. return result;
  6337. }
  6338. /* No documentation as it is a property getter */
  6339. int QCPAxis::tickLengthIn() const
  6340. {
  6341. return mAxisPainter->tickLengthIn;
  6342. }
  6343. /* No documentation as it is a property getter */
  6344. int QCPAxis::tickLengthOut() const
  6345. {
  6346. return mAxisPainter->tickLengthOut;
  6347. }
  6348. /* No documentation as it is a property getter */
  6349. int QCPAxis::subTickLengthIn() const
  6350. {
  6351. return mAxisPainter->subTickLengthIn;
  6352. }
  6353. /* No documentation as it is a property getter */
  6354. int QCPAxis::subTickLengthOut() const
  6355. {
  6356. return mAxisPainter->subTickLengthOut;
  6357. }
  6358. /* No documentation as it is a property getter */
  6359. int QCPAxis::labelPadding() const
  6360. {
  6361. return mAxisPainter->labelPadding;
  6362. }
  6363. /* No documentation as it is a property getter */
  6364. int QCPAxis::offset() const
  6365. {
  6366. return mAxisPainter->offset;
  6367. }
  6368. /* No documentation as it is a property getter */
  6369. QCPLineEnding QCPAxis::lowerEnding() const
  6370. {
  6371. return mAxisPainter->lowerEnding;
  6372. }
  6373. /* No documentation as it is a property getter */
  6374. QCPLineEnding QCPAxis::upperEnding() const
  6375. {
  6376. return mAxisPainter->upperEnding;
  6377. }
  6378. /*!
  6379. Sets whether the axis uses a linear scale or a logarithmic scale.
  6380. Note that this method controls the coordinate transformation. You will likely also want to use a
  6381. logarithmic tick spacing and labeling, which can be achieved by setting an instance of \ref
  6382. QCPAxisTickerLog via \ref setTicker. See the documentation of \ref QCPAxisTickerLog about the
  6383. details of logarithmic axis tick creation.
  6384. \ref setNumberPrecision
  6385. */
  6386. void QCPAxis::setScaleType(QCPAxis::ScaleType type)
  6387. {
  6388. if (mScaleType != type)
  6389. {
  6390. mScaleType = type;
  6391. if (mScaleType == stLogarithmic)
  6392. setRange(mRange.sanitizedForLogScale());
  6393. mCachedMarginValid = false;
  6394. emit scaleTypeChanged(mScaleType);
  6395. }
  6396. }
  6397. /*!
  6398. Sets the range of the axis.
  6399. This slot may be connected with the \ref rangeChanged signal of another axis so this axis
  6400. is always synchronized with the other axis range, when it changes.
  6401. To invert the direction of an axis, use \ref setRangeReversed.
  6402. */
  6403. void QCPAxis::setRange(const QCPRange &range)
  6404. {
  6405. if (range.lower == mRange.lower && range.upper == mRange.upper)
  6406. return;
  6407. if (!QCPRange::validRange(range)) return;
  6408. QCPRange oldRange = mRange;
  6409. if (mScaleType == stLogarithmic)
  6410. {
  6411. mRange = range.sanitizedForLogScale();
  6412. } else
  6413. {
  6414. mRange = range.sanitizedForLinScale();
  6415. }
  6416. emit rangeChanged(mRange);
  6417. emit rangeChanged(mRange, oldRange);
  6418. }
  6419. /*!
  6420. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  6421. (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
  6422. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  6423. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  6424. directly.
  6425. \see SelectablePart, setSelectedParts
  6426. */
  6427. void QCPAxis::setSelectableParts(const SelectableParts &selectable)
  6428. {
  6429. if (mSelectableParts != selectable)
  6430. {
  6431. mSelectableParts = selectable;
  6432. emit selectableChanged(mSelectableParts);
  6433. }
  6434. }
  6435. /*!
  6436. Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
  6437. is selected, it uses a different pen/font.
  6438. The entire selection mechanism for axes is handled automatically when \ref
  6439. QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
  6440. wish to change the selection state manually.
  6441. This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
  6442. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  6443. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
  6444. setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
  6445. */
  6446. void QCPAxis::setSelectedParts(const SelectableParts &selected)
  6447. {
  6448. if (mSelectedParts != selected)
  6449. {
  6450. mSelectedParts = selected;
  6451. emit selectionChanged(mSelectedParts);
  6452. }
  6453. }
  6454. /*!
  6455. \overload
  6456. Sets the lower and upper bound of the axis range.
  6457. To invert the direction of an axis, use \ref setRangeReversed.
  6458. There is also a slot to set a range, see \ref setRange(const QCPRange &range).
  6459. */
  6460. void QCPAxis::setRange(double lower, double upper)
  6461. {
  6462. if (lower == mRange.lower && upper == mRange.upper)
  6463. return;
  6464. if (!QCPRange::validRange(lower, upper)) return;
  6465. QCPRange oldRange = mRange;
  6466. mRange.lower = lower;
  6467. mRange.upper = upper;
  6468. if (mScaleType == stLogarithmic)
  6469. {
  6470. mRange = mRange.sanitizedForLogScale();
  6471. } else
  6472. {
  6473. mRange = mRange.sanitizedForLinScale();
  6474. }
  6475. emit rangeChanged(mRange);
  6476. emit rangeChanged(mRange, oldRange);
  6477. }
  6478. /*!
  6479. \overload
  6480. Sets the range of the axis.
  6481. The \a position coordinate indicates together with the \a alignment parameter, where the new
  6482. range will be positioned. \a size defines the size of the new axis range. \a alignment may be
  6483. Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
  6484. or center of the range to be aligned with \a position. Any other values of \a alignment will
  6485. default to Qt::AlignCenter.
  6486. */
  6487. void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment)
  6488. {
  6489. if (alignment == Qt::AlignLeft)
  6490. setRange(position, position+size);
  6491. else if (alignment == Qt::AlignRight)
  6492. setRange(position-size, position);
  6493. else // alignment == Qt::AlignCenter
  6494. setRange(position-size/2.0, position+size/2.0);
  6495. }
  6496. /*!
  6497. Sets the lower bound of the axis range. The upper bound is not changed.
  6498. \see setRange
  6499. */
  6500. void QCPAxis::setRangeLower(double lower)
  6501. {
  6502. if (mRange.lower == lower)
  6503. return;
  6504. QCPRange oldRange = mRange;
  6505. mRange.lower = lower;
  6506. if (mScaleType == stLogarithmic)
  6507. {
  6508. mRange = mRange.sanitizedForLogScale();
  6509. } else
  6510. {
  6511. mRange = mRange.sanitizedForLinScale();
  6512. }
  6513. emit rangeChanged(mRange);
  6514. emit rangeChanged(mRange, oldRange);
  6515. }
  6516. /*!
  6517. Sets the upper bound of the axis range. The lower bound is not changed.
  6518. \see setRange
  6519. */
  6520. void QCPAxis::setRangeUpper(double upper)
  6521. {
  6522. if (mRange.upper == upper)
  6523. return;
  6524. QCPRange oldRange = mRange;
  6525. mRange.upper = upper;
  6526. if (mScaleType == stLogarithmic)
  6527. {
  6528. mRange = mRange.sanitizedForLogScale();
  6529. } else
  6530. {
  6531. mRange = mRange.sanitizedForLinScale();
  6532. }
  6533. emit rangeChanged(mRange);
  6534. emit rangeChanged(mRange, oldRange);
  6535. }
  6536. /*!
  6537. Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
  6538. axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
  6539. direction of increasing values is inverted.
  6540. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
  6541. of the \ref setRange interface will still reference the mathematically smaller number than the \a
  6542. upper part.
  6543. */
  6544. void QCPAxis::setRangeReversed(bool reversed)
  6545. {
  6546. mRangeReversed = reversed;
  6547. }
  6548. /*!
  6549. The axis ticker is responsible for generating the tick positions and tick labels. See the
  6550. documentation of QCPAxisTicker for details on how to work with axis tickers.
  6551. You can change the tick positioning/labeling behaviour of this axis by setting a different
  6552. QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
  6553. ticker, access it via \ref ticker.
  6554. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  6555. ticker simply by passing the same shared pointer to multiple axes.
  6556. \see ticker
  6557. */
  6558. void QCPAxis::setTicker(QSharedPointer<QCPAxisTicker> ticker)
  6559. {
  6560. if (ticker)
  6561. mTicker = ticker;
  6562. else
  6563. qDebug() << Q_FUNC_INFO << "can not set 0 as axis ticker";
  6564. // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
  6565. }
  6566. /*!
  6567. Sets whether tick marks are displayed.
  6568. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
  6569. that, see \ref setTickLabels.
  6570. \see setSubTicks
  6571. */
  6572. void QCPAxis::setTicks(bool show)
  6573. {
  6574. if (mTicks != show)
  6575. {
  6576. mTicks = show;
  6577. mCachedMarginValid = false;
  6578. }
  6579. }
  6580. /*!
  6581. Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
  6582. */
  6583. void QCPAxis::setTickLabels(bool show)
  6584. {
  6585. if (mTickLabels != show)
  6586. {
  6587. mTickLabels = show;
  6588. mCachedMarginValid = false;
  6589. if (!mTickLabels)
  6590. mTickVectorLabels.clear();
  6591. }
  6592. }
  6593. /*!
  6594. Sets the distance between the axis base line (including any outward ticks) and the tick labels.
  6595. \see setLabelPadding, setPadding
  6596. */
  6597. void QCPAxis::setTickLabelPadding(int padding)
  6598. {
  6599. if (mAxisPainter->tickLabelPadding != padding)
  6600. {
  6601. mAxisPainter->tickLabelPadding = padding;
  6602. mCachedMarginValid = false;
  6603. }
  6604. }
  6605. /*!
  6606. Sets the font of the tick labels.
  6607. \see setTickLabels, setTickLabelColor
  6608. */
  6609. void QCPAxis::setTickLabelFont(const QFont &font)
  6610. {
  6611. if (font != mTickLabelFont)
  6612. {
  6613. mTickLabelFont = font;
  6614. mCachedMarginValid = false;
  6615. }
  6616. }
  6617. /*!
  6618. Sets the color of the tick labels.
  6619. \see setTickLabels, setTickLabelFont
  6620. */
  6621. void QCPAxis::setTickLabelColor(const QColor &color)
  6622. {
  6623. mTickLabelColor = color;
  6624. }
  6625. /*!
  6626. Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
  6627. the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
  6628. from -90 to 90 degrees.
  6629. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
  6630. other angles, the label is drawn with an offset such that it seems to point toward or away from
  6631. the tick mark.
  6632. */
  6633. void QCPAxis::setTickLabelRotation(double degrees)
  6634. {
  6635. if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation))
  6636. {
  6637. mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0);
  6638. mCachedMarginValid = false;
  6639. }
  6640. }
  6641. /*!
  6642. Sets whether the tick labels (numbers) shall appear inside or outside the axis rect.
  6643. The usual and default setting is \ref lsOutside. Very compact plots sometimes require tick labels
  6644. to be inside the axis rect, to save space. If \a side is set to \ref lsInside, the tick labels
  6645. appear on the inside are additionally clipped to the axis rect.
  6646. */
  6647. void QCPAxis::setTickLabelSide(LabelSide side)
  6648. {
  6649. mAxisPainter->tickLabelSide = side;
  6650. mCachedMarginValid = false;
  6651. }
  6652. /*!
  6653. Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
  6654. of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
  6655. that, see the "Argument Formats" section in the detailed description of the QString class.
  6656. \a formatCode is a string of one, two or three characters. The first character is identical to
  6657. the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
  6658. format, 'g'/'G' scientific or fixed, whichever is shorter.
  6659. The second and third characters are optional and specific to QCustomPlot:\n
  6660. If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
  6661. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for
  6662. "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
  6663. [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
  6664. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
  6665. be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
  6666. cross and 183 (0xB7) for the dot.
  6667. Examples for \a formatCode:
  6668. \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
  6669. normal scientific format is used
  6670. \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
  6671. beautifully typeset decimal powers and a dot as multiplication sign
  6672. \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
  6673. multiplication sign
  6674. \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
  6675. powers. Format code will be reduced to 'f'.
  6676. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
  6677. code will not be changed.
  6678. */
  6679. void QCPAxis::setNumberFormat(const QString &formatCode)
  6680. {
  6681. if (formatCode.isEmpty())
  6682. {
  6683. qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
  6684. return;
  6685. }
  6686. mCachedMarginValid = false;
  6687. // interpret first char as number format char:
  6688. QString allowedFormatChars(QLatin1String("eEfgG"));
  6689. if (allowedFormatChars.contains(formatCode.at(0)))
  6690. {
  6691. mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
  6692. } else
  6693. {
  6694. qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
  6695. return;
  6696. }
  6697. if (formatCode.length() < 2)
  6698. {
  6699. mNumberBeautifulPowers = false;
  6700. mAxisPainter->numberMultiplyCross = false;
  6701. return;
  6702. }
  6703. // interpret second char as indicator for beautiful decimal powers:
  6704. if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
  6705. {
  6706. mNumberBeautifulPowers = true;
  6707. } else
  6708. {
  6709. qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
  6710. return;
  6711. }
  6712. if (formatCode.length() < 3)
  6713. {
  6714. mAxisPainter->numberMultiplyCross = false;
  6715. return;
  6716. }
  6717. // interpret third char as indicator for dot or cross multiplication symbol:
  6718. if (formatCode.at(2) == QLatin1Char('c'))
  6719. {
  6720. mAxisPainter->numberMultiplyCross = true;
  6721. } else if (formatCode.at(2) == QLatin1Char('d'))
  6722. {
  6723. mAxisPainter->numberMultiplyCross = false;
  6724. } else
  6725. {
  6726. qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
  6727. return;
  6728. }
  6729. }
  6730. /*!
  6731. Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
  6732. for details. The effect of precisions are most notably for number Formats starting with 'e', see
  6733. \ref setNumberFormat
  6734. */
  6735. void QCPAxis::setNumberPrecision(int precision)
  6736. {
  6737. if (mNumberPrecision != precision)
  6738. {
  6739. mNumberPrecision = precision;
  6740. mCachedMarginValid = false;
  6741. }
  6742. }
  6743. /*!
  6744. Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
  6745. plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
  6746. zero, the tick labels and axis label will increase their distance to the axis accordingly, so
  6747. they won't collide with the ticks.
  6748. \see setSubTickLength, setTickLengthIn, setTickLengthOut
  6749. */
  6750. void QCPAxis::setTickLength(int inside, int outside)
  6751. {
  6752. setTickLengthIn(inside);
  6753. setTickLengthOut(outside);
  6754. }
  6755. /*!
  6756. Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
  6757. inside the plot.
  6758. \see setTickLengthOut, setTickLength, setSubTickLength
  6759. */
  6760. void QCPAxis::setTickLengthIn(int inside)
  6761. {
  6762. if (mAxisPainter->tickLengthIn != inside)
  6763. {
  6764. mAxisPainter->tickLengthIn = inside;
  6765. }
  6766. }
  6767. /*!
  6768. Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
  6769. outside the plot. If \a outside is greater than zero, the tick labels and axis label will
  6770. increase their distance to the axis accordingly, so they won't collide with the ticks.
  6771. \see setTickLengthIn, setTickLength, setSubTickLength
  6772. */
  6773. void QCPAxis::setTickLengthOut(int outside)
  6774. {
  6775. if (mAxisPainter->tickLengthOut != outside)
  6776. {
  6777. mAxisPainter->tickLengthOut = outside;
  6778. mCachedMarginValid = false; // only outside tick length can change margin
  6779. }
  6780. }
  6781. /*!
  6782. Sets whether sub tick marks are displayed.
  6783. Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
  6784. \see setTicks
  6785. */
  6786. void QCPAxis::setSubTicks(bool show)
  6787. {
  6788. if (mSubTicks != show)
  6789. {
  6790. mSubTicks = show;
  6791. mCachedMarginValid = false;
  6792. }
  6793. }
  6794. /*!
  6795. Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
  6796. the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
  6797. than zero, the tick labels and axis label will increase their distance to the axis accordingly,
  6798. so they won't collide with the ticks.
  6799. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
  6800. */
  6801. void QCPAxis::setSubTickLength(int inside, int outside)
  6802. {
  6803. setSubTickLengthIn(inside);
  6804. setSubTickLengthOut(outside);
  6805. }
  6806. /*!
  6807. Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
  6808. the plot.
  6809. \see setSubTickLengthOut, setSubTickLength, setTickLength
  6810. */
  6811. void QCPAxis::setSubTickLengthIn(int inside)
  6812. {
  6813. if (mAxisPainter->subTickLengthIn != inside)
  6814. {
  6815. mAxisPainter->subTickLengthIn = inside;
  6816. }
  6817. }
  6818. /*!
  6819. Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
  6820. outside the plot. If \a outside is greater than zero, the tick labels will increase their
  6821. distance to the axis accordingly, so they won't collide with the ticks.
  6822. \see setSubTickLengthIn, setSubTickLength, setTickLength
  6823. */
  6824. void QCPAxis::setSubTickLengthOut(int outside)
  6825. {
  6826. if (mAxisPainter->subTickLengthOut != outside)
  6827. {
  6828. mAxisPainter->subTickLengthOut = outside;
  6829. mCachedMarginValid = false; // only outside tick length can change margin
  6830. }
  6831. }
  6832. /*!
  6833. Sets the pen, the axis base line is drawn with.
  6834. \see setTickPen, setSubTickPen
  6835. */
  6836. void QCPAxis::setBasePen(const QPen &pen)
  6837. {
  6838. mBasePen = pen;
  6839. }
  6840. /*!
  6841. Sets the pen, tick marks will be drawn with.
  6842. \see setTickLength, setBasePen
  6843. */
  6844. void QCPAxis::setTickPen(const QPen &pen)
  6845. {
  6846. mTickPen = pen;
  6847. }
  6848. /*!
  6849. Sets the pen, subtick marks will be drawn with.
  6850. \see setSubTickCount, setSubTickLength, setBasePen
  6851. */
  6852. void QCPAxis::setSubTickPen(const QPen &pen)
  6853. {
  6854. mSubTickPen = pen;
  6855. }
  6856. /*!
  6857. Sets the font of the axis label.
  6858. \see setLabelColor
  6859. */
  6860. void QCPAxis::setLabelFont(const QFont &font)
  6861. {
  6862. if (mLabelFont != font)
  6863. {
  6864. mLabelFont = font;
  6865. mCachedMarginValid = false;
  6866. }
  6867. }
  6868. /*!
  6869. Sets the color of the axis label.
  6870. \see setLabelFont
  6871. */
  6872. void QCPAxis::setLabelColor(const QColor &color)
  6873. {
  6874. mLabelColor = color;
  6875. }
  6876. /*!
  6877. Sets the text of the axis label that will be shown below/above or next to the axis, depending on
  6878. its orientation. To disable axis labels, pass an empty string as \a str.
  6879. */
  6880. void QCPAxis::setLabel(const QString &str)
  6881. {
  6882. if (mLabel != str)
  6883. {
  6884. mLabel = str;
  6885. mCachedMarginValid = false;
  6886. }
  6887. }
  6888. /*!
  6889. Sets the distance between the tick labels and the axis label.
  6890. \see setTickLabelPadding, setPadding
  6891. */
  6892. void QCPAxis::setLabelPadding(int padding)
  6893. {
  6894. if (mAxisPainter->labelPadding != padding)
  6895. {
  6896. mAxisPainter->labelPadding = padding;
  6897. mCachedMarginValid = false;
  6898. }
  6899. }
  6900. /*!
  6901. Sets the padding of the axis.
  6902. When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space,
  6903. that is left blank.
  6904. The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled.
  6905. \see setLabelPadding, setTickLabelPadding
  6906. */
  6907. void QCPAxis::setPadding(int padding)
  6908. {
  6909. if (mPadding != padding)
  6910. {
  6911. mPadding = padding;
  6912. mCachedMarginValid = false;
  6913. }
  6914. }
  6915. /*!
  6916. Sets the offset the axis has to its axis rect side.
  6917. If an axis rect side has multiple axes and automatic margin calculation is enabled for that side,
  6918. only the offset of the inner most axis has meaning (even if it is set to be invisible). The
  6919. offset of the other, outer axes is controlled automatically, to place them at appropriate
  6920. positions.
  6921. */
  6922. void QCPAxis::setOffset(int offset)
  6923. {
  6924. mAxisPainter->offset = offset;
  6925. }
  6926. /*!
  6927. Sets the font that is used for tick labels when they are selected.
  6928. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  6929. */
  6930. void QCPAxis::setSelectedTickLabelFont(const QFont &font)
  6931. {
  6932. if (font != mSelectedTickLabelFont)
  6933. {
  6934. mSelectedTickLabelFont = font;
  6935. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  6936. }
  6937. }
  6938. /*!
  6939. Sets the font that is used for the axis label when it is selected.
  6940. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  6941. */
  6942. void QCPAxis::setSelectedLabelFont(const QFont &font)
  6943. {
  6944. mSelectedLabelFont = font;
  6945. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  6946. }
  6947. /*!
  6948. Sets the color that is used for tick labels when they are selected.
  6949. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  6950. */
  6951. void QCPAxis::setSelectedTickLabelColor(const QColor &color)
  6952. {
  6953. if (color != mSelectedTickLabelColor)
  6954. {
  6955. mSelectedTickLabelColor = color;
  6956. }
  6957. }
  6958. /*!
  6959. Sets the color that is used for the axis label when it is selected.
  6960. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  6961. */
  6962. void QCPAxis::setSelectedLabelColor(const QColor &color)
  6963. {
  6964. mSelectedLabelColor = color;
  6965. }
  6966. /*!
  6967. Sets the pen that is used to draw the axis base line when selected.
  6968. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  6969. */
  6970. void QCPAxis::setSelectedBasePen(const QPen &pen)
  6971. {
  6972. mSelectedBasePen = pen;
  6973. }
  6974. /*!
  6975. Sets the pen that is used to draw the (major) ticks when selected.
  6976. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  6977. */
  6978. void QCPAxis::setSelectedTickPen(const QPen &pen)
  6979. {
  6980. mSelectedTickPen = pen;
  6981. }
  6982. /*!
  6983. Sets the pen that is used to draw the subticks when selected.
  6984. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  6985. */
  6986. void QCPAxis::setSelectedSubTickPen(const QPen &pen)
  6987. {
  6988. mSelectedSubTickPen = pen;
  6989. }
  6990. /*!
  6991. Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available
  6992. styles.
  6993. For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending.
  6994. Note that this meaning does not change when the axis range is reversed with \ref
  6995. setRangeReversed.
  6996. \see setUpperEnding
  6997. */
  6998. void QCPAxis::setLowerEnding(const QCPLineEnding &ending)
  6999. {
  7000. mAxisPainter->lowerEnding = ending;
  7001. }
  7002. /*!
  7003. Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available
  7004. styles.
  7005. For horizontal axes, this method refers to the right ending, for vertical axes the top ending.
  7006. Note that this meaning does not change when the axis range is reversed with \ref
  7007. setRangeReversed.
  7008. \see setLowerEnding
  7009. */
  7010. void QCPAxis::setUpperEnding(const QCPLineEnding &ending)
  7011. {
  7012. mAxisPainter->upperEnding = ending;
  7013. }
  7014. /*!
  7015. If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
  7016. bounds of the range. The range is simply moved by \a diff.
  7017. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
  7018. corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
  7019. */
  7020. void QCPAxis::moveRange(double diff)
  7021. {
  7022. QCPRange oldRange = mRange;
  7023. if (mScaleType == stLinear)
  7024. {
  7025. mRange.lower += diff;
  7026. mRange.upper += diff;
  7027. } else // mScaleType == stLogarithmic
  7028. {
  7029. mRange.lower *= diff;
  7030. mRange.upper *= diff;
  7031. }
  7032. emit rangeChanged(mRange);
  7033. emit rangeChanged(mRange, oldRange);
  7034. }
  7035. /*!
  7036. Scales the range of this axis by \a factor around the center of the current axis range. For
  7037. example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
  7038. range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
  7039. the center will have moved symmetrically closer).
  7040. If you wish to scale around a different coordinate than the current axis range center, use the
  7041. overload \ref scaleRange(double factor, double center).
  7042. */
  7043. void QCPAxis::scaleRange(double factor)
  7044. {
  7045. scaleRange(factor, range().center());
  7046. }
  7047. /*! \overload
  7048. Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
  7049. factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
  7050. coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
  7051. around 1.0 will have moved symmetrically closer to 1.0).
  7052. \see scaleRange(double factor)
  7053. */
  7054. void QCPAxis::scaleRange(double factor, double center)
  7055. {
  7056. QCPRange oldRange = mRange;
  7057. if (mScaleType == stLinear)
  7058. {
  7059. QCPRange newRange;
  7060. newRange.lower = (mRange.lower-center)*factor + center;
  7061. newRange.upper = (mRange.upper-center)*factor + center;
  7062. if (QCPRange::validRange(newRange))
  7063. mRange = newRange.sanitizedForLinScale();
  7064. } else // mScaleType == stLogarithmic
  7065. {
  7066. if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range
  7067. {
  7068. QCPRange newRange;
  7069. newRange.lower = qPow(mRange.lower/center, factor)*center;
  7070. newRange.upper = qPow(mRange.upper/center, factor)*center;
  7071. if (QCPRange::validRange(newRange))
  7072. mRange = newRange.sanitizedForLogScale();
  7073. } else
  7074. qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center;
  7075. }
  7076. emit rangeChanged(mRange);
  7077. emit rangeChanged(mRange, oldRange);
  7078. }
  7079. /*!
  7080. Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will
  7081. be done around the center of the current axis range.
  7082. For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs
  7083. plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the
  7084. axis rect has.
  7085. This is an operation that changes the range of this axis once, it doesn't fix the scale ratio
  7086. indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent
  7087. won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent
  7088. will follow.
  7089. */
  7090. void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio)
  7091. {
  7092. int otherPixelSize, ownPixelSize;
  7093. if (otherAxis->orientation() == Qt::Horizontal)
  7094. otherPixelSize = otherAxis->axisRect()->width();
  7095. else
  7096. otherPixelSize = otherAxis->axisRect()->height();
  7097. if (orientation() == Qt::Horizontal)
  7098. ownPixelSize = axisRect()->width();
  7099. else
  7100. ownPixelSize = axisRect()->height();
  7101. double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/(double)otherPixelSize;
  7102. setRange(range().center(), newRangeSize, Qt::AlignCenter);
  7103. }
  7104. /*!
  7105. Changes the axis range such that all plottables associated with this axis are fully visible in
  7106. that dimension.
  7107. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
  7108. */
  7109. void QCPAxis::rescale(bool onlyVisiblePlottables)
  7110. {
  7111. QList<QCPAbstractPlottable*> p = plottables();
  7112. QCPRange newRange;
  7113. bool haveRange = false;
  7114. for (int i=0; i<p.size(); ++i)
  7115. {
  7116. if (!p.at(i)->realVisibility() && onlyVisiblePlottables)
  7117. continue;
  7118. QCPRange plottableRange;
  7119. bool currentFoundRange;
  7120. QCP::SignDomain signDomain = QCP::sdBoth;
  7121. if (mScaleType == stLogarithmic)
  7122. signDomain = (mRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  7123. if (p.at(i)->keyAxis() == this)
  7124. plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain);
  7125. else
  7126. plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain);
  7127. if (currentFoundRange)
  7128. {
  7129. if (!haveRange)
  7130. newRange = plottableRange;
  7131. else
  7132. newRange.expand(plottableRange);
  7133. haveRange = true;
  7134. }
  7135. }
  7136. if (haveRange)
  7137. {
  7138. 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
  7139. {
  7140. 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
  7141. if (mScaleType == stLinear)
  7142. {
  7143. newRange.lower = center-mRange.size()/2.0;
  7144. newRange.upper = center+mRange.size()/2.0;
  7145. } else // mScaleType == stLogarithmic
  7146. {
  7147. newRange.lower = center/qSqrt(mRange.upper/mRange.lower);
  7148. newRange.upper = center*qSqrt(mRange.upper/mRange.lower);
  7149. }
  7150. }
  7151. setRange(newRange);
  7152. }
  7153. }
  7154. /*!
  7155. Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
  7156. */
  7157. double QCPAxis::pixelToCoord(double value) const
  7158. {
  7159. if (orientation() == Qt::Horizontal)
  7160. {
  7161. if (mScaleType == stLinear)
  7162. {
  7163. if (!mRangeReversed)
  7164. return (value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.lower;
  7165. else
  7166. return -(value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.upper;
  7167. } else // mScaleType == stLogarithmic
  7168. {
  7169. if (!mRangeReversed)
  7170. return qPow(mRange.upper/mRange.lower, (value-mAxisRect->left())/(double)mAxisRect->width())*mRange.lower;
  7171. else
  7172. return qPow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/(double)mAxisRect->width())*mRange.upper;
  7173. }
  7174. } else // orientation() == Qt::Vertical
  7175. {
  7176. if (mScaleType == stLinear)
  7177. {
  7178. if (!mRangeReversed)
  7179. return (mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.lower;
  7180. else
  7181. return -(mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.upper;
  7182. } else // mScaleType == stLogarithmic
  7183. {
  7184. if (!mRangeReversed)
  7185. return qPow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/(double)mAxisRect->height())*mRange.lower;
  7186. else
  7187. return qPow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/(double)mAxisRect->height())*mRange.upper;
  7188. }
  7189. }
  7190. }
  7191. /*!
  7192. Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
  7193. */
  7194. double QCPAxis::coordToPixel(double value) const
  7195. {
  7196. if (orientation() == Qt::Horizontal)
  7197. {
  7198. if (mScaleType == stLinear)
  7199. {
  7200. if (!mRangeReversed)
  7201. return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left();
  7202. else
  7203. return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left();
  7204. } else // mScaleType == stLogarithmic
  7205. {
  7206. if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7207. return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200;
  7208. else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7209. return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200;
  7210. else
  7211. {
  7212. if (!mRangeReversed)
  7213. return qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
  7214. else
  7215. return qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
  7216. }
  7217. }
  7218. } else // orientation() == Qt::Vertical
  7219. {
  7220. if (mScaleType == stLinear)
  7221. {
  7222. if (!mRangeReversed)
  7223. return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height();
  7224. else
  7225. return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height();
  7226. } else // mScaleType == stLogarithmic
  7227. {
  7228. if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7229. return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200;
  7230. else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7231. return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200;
  7232. else
  7233. {
  7234. if (!mRangeReversed)
  7235. return mAxisRect->bottom()-qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->height();
  7236. else
  7237. return mAxisRect->bottom()-qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->height();
  7238. }
  7239. }
  7240. }
  7241. }
  7242. /*!
  7243. Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
  7244. is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
  7245. function does not change the current selection state of the axis.
  7246. If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
  7247. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
  7248. */
  7249. QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const
  7250. {
  7251. if (!mVisible)
  7252. return spNone;
  7253. if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
  7254. return spAxis;
  7255. else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
  7256. return spTickLabels;
  7257. else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
  7258. return spAxisLabel;
  7259. else
  7260. return spNone;
  7261. }
  7262. /* inherits documentation from base class */
  7263. double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  7264. {
  7265. if (!mParentPlot) return -1;
  7266. SelectablePart part = getPartAt(pos);
  7267. if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
  7268. return -1;
  7269. if (details)
  7270. details->setValue(part);
  7271. return mParentPlot->selectionTolerance()*0.99;
  7272. }
  7273. /*!
  7274. Returns a list of all the plottables that have this axis as key or value axis.
  7275. If you are only interested in plottables of type QCPGraph, see \ref graphs.
  7276. \see graphs, items
  7277. */
  7278. QList<QCPAbstractPlottable*> QCPAxis::plottables() const
  7279. {
  7280. QList<QCPAbstractPlottable*> result;
  7281. if (!mParentPlot) return result;
  7282. for (int i=0; i<mParentPlot->mPlottables.size(); ++i)
  7283. {
  7284. if (mParentPlot->mPlottables.at(i)->keyAxis() == this ||mParentPlot->mPlottables.at(i)->valueAxis() == this)
  7285. result.append(mParentPlot->mPlottables.at(i));
  7286. }
  7287. return result;
  7288. }
  7289. /*!
  7290. Returns a list of all the graphs that have this axis as key or value axis.
  7291. \see plottables, items
  7292. */
  7293. QList<QCPGraph*> QCPAxis::graphs() const
  7294. {
  7295. QList<QCPGraph*> result;
  7296. if (!mParentPlot) return result;
  7297. for (int i=0; i<mParentPlot->mGraphs.size(); ++i)
  7298. {
  7299. if (mParentPlot->mGraphs.at(i)->keyAxis() == this || mParentPlot->mGraphs.at(i)->valueAxis() == this)
  7300. result.append(mParentPlot->mGraphs.at(i));
  7301. }
  7302. return result;
  7303. }
  7304. /*!
  7305. Returns a list of all the items that are associated with this axis. An item is considered
  7306. associated with an axis if at least one of its positions uses the axis as key or value axis.
  7307. \see plottables, graphs
  7308. */
  7309. QList<QCPAbstractItem*> QCPAxis::items() const
  7310. {
  7311. QList<QCPAbstractItem*> result;
  7312. if (!mParentPlot) return result;
  7313. for (int itemId=0; itemId<mParentPlot->mItems.size(); ++itemId)
  7314. {
  7315. QList<QCPItemPosition*> positions = mParentPlot->mItems.at(itemId)->positions();
  7316. for (int posId=0; posId<positions.size(); ++posId)
  7317. {
  7318. if (positions.at(posId)->keyAxis() == this || positions.at(posId)->valueAxis() == this)
  7319. {
  7320. result.append(mParentPlot->mItems.at(itemId));
  7321. break;
  7322. }
  7323. }
  7324. }
  7325. return result;
  7326. }
  7327. /*!
  7328. Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to
  7329. QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.)
  7330. */
  7331. QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side)
  7332. {
  7333. switch (side)
  7334. {
  7335. case QCP::msLeft: return atLeft;
  7336. case QCP::msRight: return atRight;
  7337. case QCP::msTop: return atTop;
  7338. case QCP::msBottom: return atBottom;
  7339. default: break;
  7340. }
  7341. qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << (int)side;
  7342. return atLeft;
  7343. }
  7344. /*!
  7345. Returns the axis type that describes the opposite axis of an axis with the specified \a type.
  7346. */
  7347. QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type)
  7348. {
  7349. switch (type)
  7350. {
  7351. case atLeft: return atRight; break;
  7352. case atRight: return atLeft; break;
  7353. case atBottom: return atTop; break;
  7354. case atTop: return atBottom; break;
  7355. default: qDebug() << Q_FUNC_INFO << "invalid axis type"; return atLeft; break;
  7356. }
  7357. }
  7358. /* inherits documentation from base class */
  7359. void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  7360. {
  7361. Q_UNUSED(event)
  7362. SelectablePart part = details.value<SelectablePart>();
  7363. if (mSelectableParts.testFlag(part))
  7364. {
  7365. SelectableParts selBefore = mSelectedParts;
  7366. setSelectedParts(additive ? mSelectedParts^part : part);
  7367. if (selectionStateChanged)
  7368. *selectionStateChanged = mSelectedParts != selBefore;
  7369. }
  7370. }
  7371. /* inherits documentation from base class */
  7372. void QCPAxis::deselectEvent(bool *selectionStateChanged)
  7373. {
  7374. SelectableParts selBefore = mSelectedParts;
  7375. setSelectedParts(mSelectedParts & ~mSelectableParts);
  7376. if (selectionStateChanged)
  7377. *selectionStateChanged = mSelectedParts != selBefore;
  7378. }
  7379. /*! \internal
  7380. This mouse event reimplementation provides the functionality to let the user drag individual axes
  7381. exclusively, by startig the drag on top of the axis.
  7382. For the axis to accept this event and perform the single axis drag, the parent \ref QCPAxisRect
  7383. must be configured accordingly, i.e. it must allow range dragging in the orientation of this axis
  7384. (\ref QCPAxisRect::setRangeDrag) and this axis must be a draggable axis (\ref
  7385. QCPAxisRect::setRangeDragAxes)
  7386. \seebaseclassmethod
  7387. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  7388. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  7389. */
  7390. void QCPAxis::mousePressEvent(QMouseEvent *event, const QVariant &details)
  7391. {
  7392. Q_UNUSED(details)
  7393. if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag) ||
  7394. !mAxisRect->rangeDrag().testFlag(orientation()) ||
  7395. !mAxisRect->rangeDragAxes(orientation()).contains(this))
  7396. {
  7397. event->ignore();
  7398. return;
  7399. }
  7400. if (event->buttons() & Qt::LeftButton)
  7401. {
  7402. mDragging = true;
  7403. // initialize antialiasing backup in case we start dragging:
  7404. if (mParentPlot->noAntialiasingOnDrag())
  7405. {
  7406. mAADragBackup = mParentPlot->antialiasedElements();
  7407. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  7408. }
  7409. // Mouse range dragging interaction:
  7410. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  7411. mDragStartRange = mRange;
  7412. }
  7413. }
  7414. /*! \internal
  7415. This mouse event reimplementation provides the functionality to let the user drag individual axes
  7416. exclusively, by startig the drag on top of the axis.
  7417. \seebaseclassmethod
  7418. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  7419. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  7420. \see QCPAxis::mousePressEvent
  7421. */
  7422. void QCPAxis::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  7423. {
  7424. if (mDragging)
  7425. {
  7426. const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y();
  7427. const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y();
  7428. if (mScaleType == QCPAxis::stLinear)
  7429. {
  7430. const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel);
  7431. setRange(mDragStartRange.lower+diff, mDragStartRange.upper+diff);
  7432. } else if (mScaleType == QCPAxis::stLogarithmic)
  7433. {
  7434. const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel);
  7435. setRange(mDragStartRange.lower*diff, mDragStartRange.upper*diff);
  7436. }
  7437. if (mParentPlot->noAntialiasingOnDrag())
  7438. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  7439. mParentPlot->replot(QCustomPlot::rpQueuedReplot);
  7440. }
  7441. }
  7442. /*! \internal
  7443. This mouse event reimplementation provides the functionality to let the user drag individual axes
  7444. exclusively, by startig the drag on top of the axis.
  7445. \seebaseclassmethod
  7446. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  7447. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  7448. \see QCPAxis::mousePressEvent
  7449. */
  7450. void QCPAxis::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  7451. {
  7452. Q_UNUSED(event)
  7453. Q_UNUSED(startPos)
  7454. mDragging = false;
  7455. if (mParentPlot->noAntialiasingOnDrag())
  7456. {
  7457. mParentPlot->setAntialiasedElements(mAADragBackup);
  7458. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  7459. }
  7460. }
  7461. /*! \internal
  7462. This mouse event reimplementation provides the functionality to let the user zoom individual axes
  7463. exclusively, by performing the wheel event on top of the axis.
  7464. For the axis to accept this event and perform the single axis zoom, the parent \ref QCPAxisRect
  7465. must be configured accordingly, i.e. it must allow range zooming in the orientation of this axis
  7466. (\ref QCPAxisRect::setRangeZoom) and this axis must be a zoomable axis (\ref
  7467. QCPAxisRect::setRangeZoomAxes)
  7468. \seebaseclassmethod
  7469. \note The zooming of possibly multiple axes at once by performing the wheel event anywhere in the
  7470. axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::wheelEvent.
  7471. */
  7472. void QCPAxis::wheelEvent(QWheelEvent *event)
  7473. {
  7474. // Mouse range zooming interaction:
  7475. if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom) ||
  7476. !mAxisRect->rangeZoom().testFlag(orientation()) ||
  7477. !mAxisRect->rangeZoomAxes(orientation()).contains(this))
  7478. {
  7479. event->ignore();
  7480. return;
  7481. }
  7482. const double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually
  7483. const double factor = qPow(mAxisRect->rangeZoomFactor(orientation()), wheelSteps);
  7484. scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y()));
  7485. mParentPlot->replot();
  7486. }
  7487. /*! \internal
  7488. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  7489. before drawing axis lines.
  7490. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  7491. This function takes into account the local setting of the antialiasing flag as well as the
  7492. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  7493. QCustomPlot::setNotAntialiasedElements.
  7494. \seebaseclassmethod
  7495. \see setAntialiased
  7496. */
  7497. void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const
  7498. {
  7499. applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
  7500. }
  7501. /*! \internal
  7502. Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance.
  7503. \seebaseclassmethod
  7504. */
  7505. void QCPAxis::draw(QCPPainter *painter)
  7506. {
  7507. QVector<double> subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  7508. QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  7509. QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
  7510. tickPositions.reserve(mTickVector.size());
  7511. tickLabels.reserve(mTickVector.size());
  7512. subTickPositions.reserve(mSubTickVector.size());
  7513. if (mTicks)
  7514. {
  7515. for (int i=0; i<mTickVector.size(); ++i)
  7516. {
  7517. tickPositions.append(coordToPixel(mTickVector.at(i)));
  7518. if (mTickLabels)
  7519. tickLabels.append(mTickVectorLabels.at(i));
  7520. }
  7521. if (mSubTicks)
  7522. {
  7523. const int subTickCount = mSubTickVector.size();
  7524. for (int i=0; i<subTickCount; ++i)
  7525. subTickPositions.append(coordToPixel(mSubTickVector.at(i)));
  7526. }
  7527. }
  7528. // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to draw the axis.
  7529. // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
  7530. mAxisPainter->type = mAxisType;
  7531. mAxisPainter->basePen = getBasePen();
  7532. mAxisPainter->labelFont = getLabelFont();
  7533. mAxisPainter->labelColor = getLabelColor();
  7534. mAxisPainter->label = mLabel;
  7535. mAxisPainter->substituteExponent = mNumberBeautifulPowers;
  7536. mAxisPainter->tickPen = getTickPen();
  7537. mAxisPainter->subTickPen = getSubTickPen();
  7538. mAxisPainter->tickLabelFont = getTickLabelFont();
  7539. mAxisPainter->tickLabelColor = getTickLabelColor();
  7540. mAxisPainter->axisRect = mAxisRect->rect();
  7541. mAxisPainter->viewportRect = mParentPlot->viewport();
  7542. mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic;
  7543. mAxisPainter->reversedEndings = mRangeReversed;
  7544. mAxisPainter->tickPositions = tickPositions;
  7545. mAxisPainter->tickLabels = tickLabels;
  7546. mAxisPainter->subTickPositions = subTickPositions;
  7547. mAxisPainter->draw(painter);
  7548. }
  7549. /*! \internal
  7550. Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
  7551. QCPAxisTicker::generate on the currently installed ticker.
  7552. If a change in the label text/count is detected, the cached axis margin is invalidated to make
  7553. sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
  7554. */
  7555. void QCPAxis::setupTickVectors()
  7556. {
  7557. if (!mParentPlot) return;
  7558. if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
  7559. QVector<QString> oldLabels = mTickVectorLabels;
  7560. mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : 0, mTickLabels ? &mTickVectorLabels : 0);
  7561. mCachedMarginValid &= mTickVectorLabels == oldLabels; // if labels have changed, margin might have changed, too
  7562. }
  7563. /*! \internal
  7564. Returns the pen that is used to draw the axis base line. Depending on the selection state, this
  7565. is either mSelectedBasePen or mBasePen.
  7566. */
  7567. QPen QCPAxis::getBasePen() const
  7568. {
  7569. return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
  7570. }
  7571. /*! \internal
  7572. Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
  7573. is either mSelectedTickPen or mTickPen.
  7574. */
  7575. QPen QCPAxis::getTickPen() const
  7576. {
  7577. return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
  7578. }
  7579. /*! \internal
  7580. Returns the pen that is used to draw the subticks. Depending on the selection state, this
  7581. is either mSelectedSubTickPen or mSubTickPen.
  7582. */
  7583. QPen QCPAxis::getSubTickPen() const
  7584. {
  7585. return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
  7586. }
  7587. /*! \internal
  7588. Returns the font that is used to draw the tick labels. Depending on the selection state, this
  7589. is either mSelectedTickLabelFont or mTickLabelFont.
  7590. */
  7591. QFont QCPAxis::getTickLabelFont() const
  7592. {
  7593. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
  7594. }
  7595. /*! \internal
  7596. Returns the font that is used to draw the axis label. Depending on the selection state, this
  7597. is either mSelectedLabelFont or mLabelFont.
  7598. */
  7599. QFont QCPAxis::getLabelFont() const
  7600. {
  7601. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
  7602. }
  7603. /*! \internal
  7604. Returns the color that is used to draw the tick labels. Depending on the selection state, this
  7605. is either mSelectedTickLabelColor or mTickLabelColor.
  7606. */
  7607. QColor QCPAxis::getTickLabelColor() const
  7608. {
  7609. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
  7610. }
  7611. /*! \internal
  7612. Returns the color that is used to draw the axis label. Depending on the selection state, this
  7613. is either mSelectedLabelColor or mLabelColor.
  7614. */
  7615. QColor QCPAxis::getLabelColor() const
  7616. {
  7617. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
  7618. }
  7619. /*! \internal
  7620. Returns the appropriate outward margin for this axis. It is needed if \ref
  7621. QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref
  7622. atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom
  7623. margin and so forth. For the calculation, this function goes through similar steps as \ref draw,
  7624. so changing one function likely requires the modification of the other one as well.
  7625. The margin consists of the outward tick length, tick label padding, tick label size, label
  7626. padding, label size, and padding.
  7627. The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc.
  7628. unchanged are very fast.
  7629. */
  7630. int QCPAxis::calculateMargin()
  7631. {
  7632. if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis
  7633. return 0;
  7634. if (mCachedMarginValid)
  7635. return mCachedMargin;
  7636. // run through similar steps as QCPAxis::draw, and calculate margin needed to fit axis and its labels
  7637. int margin = 0;
  7638. QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  7639. QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
  7640. tickPositions.reserve(mTickVector.size());
  7641. tickLabels.reserve(mTickVector.size());
  7642. if (mTicks)
  7643. {
  7644. for (int i=0; i<mTickVector.size(); ++i)
  7645. {
  7646. tickPositions.append(coordToPixel(mTickVector.at(i)));
  7647. if (mTickLabels)
  7648. tickLabels.append(mTickVectorLabels.at(i));
  7649. }
  7650. }
  7651. // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size.
  7652. // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
  7653. mAxisPainter->type = mAxisType;
  7654. mAxisPainter->labelFont = getLabelFont();
  7655. mAxisPainter->label = mLabel;
  7656. mAxisPainter->tickLabelFont = mTickLabelFont;
  7657. mAxisPainter->axisRect = mAxisRect->rect();
  7658. mAxisPainter->viewportRect = mParentPlot->viewport();
  7659. mAxisPainter->tickPositions = tickPositions;
  7660. mAxisPainter->tickLabels = tickLabels;
  7661. margin += mAxisPainter->size();
  7662. margin += mPadding;
  7663. mCachedMargin = margin;
  7664. mCachedMarginValid = true;
  7665. return margin;
  7666. }
  7667. /* inherits documentation from base class */
  7668. QCP::Interaction QCPAxis::selectionCategory() const
  7669. {
  7670. return QCP::iSelectAxes;
  7671. }
  7672. ////////////////////////////////////////////////////////////////////////////////////////////////////
  7673. //////////////////// QCPAxisPainterPrivate
  7674. ////////////////////////////////////////////////////////////////////////////////////////////////////
  7675. /*! \class QCPAxisPainterPrivate
  7676. \internal
  7677. \brief (Private)
  7678. This is a private class and not part of the public QCustomPlot interface.
  7679. It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and
  7680. axis label. It also buffers the labels to reduce replot times. The parameters are configured by
  7681. directly accessing the public member variables.
  7682. */
  7683. /*!
  7684. Constructs a QCPAxisPainterPrivate instance. Make sure to not create a new instance on every
  7685. redraw, to utilize the caching mechanisms.
  7686. */
  7687. QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) :
  7688. type(QCPAxis::atLeft),
  7689. basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  7690. lowerEnding(QCPLineEnding::esNone),
  7691. upperEnding(QCPLineEnding::esNone),
  7692. labelPadding(0),
  7693. tickLabelPadding(0),
  7694. tickLabelRotation(0),
  7695. tickLabelSide(QCPAxis::lsOutside),
  7696. substituteExponent(true),
  7697. numberMultiplyCross(false),
  7698. tickLengthIn(5),
  7699. tickLengthOut(0),
  7700. subTickLengthIn(2),
  7701. subTickLengthOut(0),
  7702. tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  7703. subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  7704. offset(0),
  7705. abbreviateDecimalPowers(false),
  7706. reversedEndings(false),
  7707. mParentPlot(parentPlot),
  7708. mLabelCache(16) // cache at most 16 (tick) labels
  7709. {
  7710. }
  7711. QCPAxisPainterPrivate::~QCPAxisPainterPrivate()
  7712. {
  7713. }
  7714. /*! \internal
  7715. Draws the axis with the specified \a painter.
  7716. The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set
  7717. here, too.
  7718. */
  7719. void QCPAxisPainterPrivate::draw(QCPPainter *painter)
  7720. {
  7721. QByteArray newHash = generateLabelParameterHash();
  7722. if (newHash != mLabelParameterHash)
  7723. {
  7724. mLabelCache.clear();
  7725. mLabelParameterHash = newHash;
  7726. }
  7727. QPoint origin;
  7728. switch (type)
  7729. {
  7730. case QCPAxis::atLeft: origin = axisRect.bottomLeft() +QPoint(-offset, 0); break;
  7731. case QCPAxis::atRight: origin = axisRect.bottomRight()+QPoint(+offset, 0); break;
  7732. case QCPAxis::atTop: origin = axisRect.topLeft() +QPoint(0, -offset); break;
  7733. case QCPAxis::atBottom: origin = axisRect.bottomLeft() +QPoint(0, +offset); break;
  7734. }
  7735. double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes)
  7736. switch (type)
  7737. {
  7738. case QCPAxis::atTop: yCor = -1; break;
  7739. case QCPAxis::atRight: xCor = 1; break;
  7740. default: break;
  7741. }
  7742. int margin = 0;
  7743. // draw baseline:
  7744. QLineF baseLine;
  7745. painter->setPen(basePen);
  7746. if (QCPAxis::orientation(type) == Qt::Horizontal)
  7747. baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(axisRect.width()+xCor, yCor));
  7748. else
  7749. baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -axisRect.height()+yCor));
  7750. if (reversedEndings)
  7751. baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later
  7752. painter->drawLine(baseLine);
  7753. // draw ticks:
  7754. if (!tickPositions.isEmpty())
  7755. {
  7756. painter->setPen(tickPen);
  7757. int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis)
  7758. if (QCPAxis::orientation(type) == Qt::Horizontal)
  7759. {
  7760. for (int i=0; i<tickPositions.size(); ++i)
  7761. painter->drawLine(QLineF(tickPositions.at(i)+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPositions.at(i)+xCor, origin.y()+tickLengthIn*tickDir+yCor));
  7762. } else
  7763. {
  7764. for (int i=0; i<tickPositions.size(); ++i)
  7765. painter->drawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPositions.at(i)+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPositions.at(i)+yCor));
  7766. }
  7767. }
  7768. // draw subticks:
  7769. if (!subTickPositions.isEmpty())
  7770. {
  7771. painter->setPen(subTickPen);
  7772. // direction of ticks ("inward" is right for left axis and left for right axis)
  7773. int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1;
  7774. if (QCPAxis::orientation(type) == Qt::Horizontal)
  7775. {
  7776. for (int i=0; i<subTickPositions.size(); ++i)
  7777. painter->drawLine(QLineF(subTickPositions.at(i)+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPositions.at(i)+xCor, origin.y()+subTickLengthIn*tickDir+yCor));
  7778. } else
  7779. {
  7780. for (int i=0; i<subTickPositions.size(); ++i)
  7781. painter->drawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPositions.at(i)+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPositions.at(i)+yCor));
  7782. }
  7783. }
  7784. margin += qMax(0, qMax(tickLengthOut, subTickLengthOut));
  7785. // draw axis base endings:
  7786. bool antialiasingBackup = painter->antialiasing();
  7787. painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't
  7788. painter->setBrush(QBrush(basePen.color()));
  7789. QCPVector2D baseLineVector(baseLine.dx(), baseLine.dy());
  7790. if (lowerEnding.style() != QCPLineEnding::esNone)
  7791. lowerEnding.draw(painter, QCPVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector);
  7792. if (upperEnding.style() != QCPLineEnding::esNone)
  7793. upperEnding.draw(painter, QCPVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector);
  7794. painter->setAntialiasing(antialiasingBackup);
  7795. // tick labels:
  7796. QRect oldClipRect;
  7797. if (tickLabelSide == QCPAxis::lsInside) // if using inside labels, clip them to the axis rect
  7798. {
  7799. oldClipRect = painter->clipRegion().boundingRect();
  7800. painter->setClipRect(axisRect);
  7801. }
  7802. QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label
  7803. if (!tickLabels.isEmpty())
  7804. {
  7805. if (tickLabelSide == QCPAxis::lsOutside)
  7806. margin += tickLabelPadding;
  7807. painter->setFont(tickLabelFont);
  7808. painter->setPen(QPen(tickLabelColor));
  7809. const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size());
  7810. int distanceToAxis = margin;
  7811. if (tickLabelSide == QCPAxis::lsInside)
  7812. distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding);
  7813. for (int i=0; i<maxLabelIndex; ++i)
  7814. placeTickLabel(painter, tickPositions.at(i), distanceToAxis, tickLabels.at(i), &tickLabelsSize);
  7815. if (tickLabelSide == QCPAxis::lsOutside)
  7816. margin += (QCPAxis::orientation(type) == Qt::Horizontal) ? tickLabelsSize.height() : tickLabelsSize.width();
  7817. }
  7818. if (tickLabelSide == QCPAxis::lsInside)
  7819. painter->setClipRect(oldClipRect);
  7820. // axis label:
  7821. QRect labelBounds;
  7822. if (!label.isEmpty())
  7823. {
  7824. margin += labelPadding;
  7825. painter->setFont(labelFont);
  7826. painter->setPen(QPen(labelColor));
  7827. labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label);
  7828. if (type == QCPAxis::atLeft)
  7829. {
  7830. QTransform oldTransform = painter->transform();
  7831. painter->translate((origin.x()-margin-labelBounds.height()), origin.y());
  7832. painter->rotate(-90);
  7833. painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  7834. painter->setTransform(oldTransform);
  7835. }
  7836. else if (type == QCPAxis::atRight)
  7837. {
  7838. QTransform oldTransform = painter->transform();
  7839. painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-axisRect.height());
  7840. painter->rotate(90);
  7841. painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  7842. painter->setTransform(oldTransform);
  7843. }
  7844. else if (type == QCPAxis::atTop)
  7845. painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  7846. else if (type == QCPAxis::atBottom)
  7847. painter->drawText(origin.x(), origin.y()+margin, axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  7848. }
  7849. // set selection boxes:
  7850. int selectionTolerance = 0;
  7851. if (mParentPlot)
  7852. selectionTolerance = mParentPlot->selectionTolerance();
  7853. else
  7854. qDebug() << Q_FUNC_INFO << "mParentPlot is null";
  7855. int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance);
  7856. int selAxisInSize = selectionTolerance;
  7857. int selTickLabelSize;
  7858. int selTickLabelOffset;
  7859. if (tickLabelSide == QCPAxis::lsOutside)
  7860. {
  7861. selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
  7862. selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding;
  7863. } else
  7864. {
  7865. selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
  7866. selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding);
  7867. }
  7868. int selLabelSize = labelBounds.height();
  7869. int selLabelOffset = qMax(tickLengthOut, subTickLengthOut)+(!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside ? tickLabelPadding+selTickLabelSize : 0)+labelPadding;
  7870. if (type == QCPAxis::atLeft)
  7871. {
  7872. mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, axisRect.top(), origin.x()+selAxisInSize, axisRect.bottom());
  7873. mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, axisRect.top(), origin.x()-selTickLabelOffset, axisRect.bottom());
  7874. mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, axisRect.top(), origin.x()-selLabelOffset, axisRect.bottom());
  7875. } else if (type == QCPAxis::atRight)
  7876. {
  7877. mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, axisRect.top(), origin.x()+selAxisOutSize, axisRect.bottom());
  7878. mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, axisRect.top(), origin.x()+selTickLabelOffset, axisRect.bottom());
  7879. mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, axisRect.top(), origin.x()+selLabelOffset, axisRect.bottom());
  7880. } else if (type == QCPAxis::atTop)
  7881. {
  7882. mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisOutSize, axisRect.right(), origin.y()+selAxisInSize);
  7883. mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, axisRect.right(), origin.y()-selTickLabelOffset);
  7884. mLabelSelectionBox.setCoords(axisRect.left(), origin.y()-selLabelOffset-selLabelSize, axisRect.right(), origin.y()-selLabelOffset);
  7885. } else if (type == QCPAxis::atBottom)
  7886. {
  7887. mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisInSize, axisRect.right(), origin.y()+selAxisOutSize);
  7888. mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, axisRect.right(), origin.y()+selTickLabelOffset);
  7889. mLabelSelectionBox.setCoords(axisRect.left(), origin.y()+selLabelOffset+selLabelSize, axisRect.right(), origin.y()+selLabelOffset);
  7890. }
  7891. mAxisSelectionBox = mAxisSelectionBox.normalized();
  7892. mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized();
  7893. mLabelSelectionBox = mLabelSelectionBox.normalized();
  7894. // draw hitboxes for debug purposes:
  7895. //painter->setBrush(Qt::NoBrush);
  7896. //painter->drawRects(QVector<QRect>() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox);
  7897. }
  7898. /*! \internal
  7899. Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone
  7900. direction) needed to fit the axis.
  7901. */
  7902. int QCPAxisPainterPrivate::size() const
  7903. {
  7904. int result = 0;
  7905. // get length of tick marks pointing outwards:
  7906. if (!tickPositions.isEmpty())
  7907. result += qMax(0, qMax(tickLengthOut, subTickLengthOut));
  7908. // calculate size of tick labels:
  7909. if (tickLabelSide == QCPAxis::lsOutside)
  7910. {
  7911. QSize tickLabelsSize(0, 0);
  7912. if (!tickLabels.isEmpty())
  7913. {
  7914. for (int i=0; i<tickLabels.size(); ++i)
  7915. getMaxTickLabelSize(tickLabelFont, tickLabels.at(i), &tickLabelsSize);
  7916. result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width();
  7917. result += tickLabelPadding;
  7918. }
  7919. }
  7920. // calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees):
  7921. if (!label.isEmpty())
  7922. {
  7923. QFontMetrics fontMetrics(labelFont);
  7924. QRect bounds;
  7925. bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label);
  7926. result += bounds.height() + labelPadding;
  7927. }
  7928. return result;
  7929. }
  7930. /*! \internal
  7931. Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This
  7932. method is called automatically in \ref draw, if any parameters have changed that invalidate the
  7933. cached labels, such as font, color, etc.
  7934. */
  7935. void QCPAxisPainterPrivate::clearCache()
  7936. {
  7937. mLabelCache.clear();
  7938. }
  7939. /*! \internal
  7940. Returns a hash that allows uniquely identifying whether the label parameters have changed such
  7941. that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the
  7942. return value of this method hasn't changed since the last redraw, the respective label parameters
  7943. haven't changed and cached labels may be used.
  7944. */
  7945. QByteArray QCPAxisPainterPrivate::generateLabelParameterHash() const
  7946. {
  7947. QByteArray result;
  7948. result.append(QByteArray::number(mParentPlot->bufferDevicePixelRatio()));
  7949. result.append(QByteArray::number(tickLabelRotation));
  7950. result.append(QByteArray::number((int)tickLabelSide));
  7951. result.append(QByteArray::number((int)substituteExponent));
  7952. result.append(QByteArray::number((int)numberMultiplyCross));
  7953. result.append(tickLabelColor.name().toLatin1()+QByteArray::number(tickLabelColor.alpha(), 16));
  7954. result.append(tickLabelFont.toString().toLatin1());
  7955. return result;
  7956. }
  7957. /*! \internal
  7958. Draws a single tick label with the provided \a painter, utilizing the internal label cache to
  7959. significantly speed up drawing of labels that were drawn in previous calls. The tick label is
  7960. always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in
  7961. pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence
  7962. for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate),
  7963. at which the label should be drawn.
  7964. In order to later draw the axis label in a place that doesn't overlap with the tick labels, the
  7965. largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref
  7966. drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a
  7967. tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently
  7968. holds.
  7969. The label is drawn with the font and pen that are currently set on the \a painter. To draw
  7970. superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref
  7971. getTickLabelData).
  7972. */
  7973. void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize)
  7974. {
  7975. // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly!
  7976. if (text.isEmpty()) return;
  7977. QSize finalSize;
  7978. QPointF labelAnchor;
  7979. switch (type)
  7980. {
  7981. case QCPAxis::atLeft: labelAnchor = QPointF(axisRect.left()-distanceToAxis-offset, position); break;
  7982. case QCPAxis::atRight: labelAnchor = QPointF(axisRect.right()+distanceToAxis+offset, position); break;
  7983. case QCPAxis::atTop: labelAnchor = QPointF(position, axisRect.top()-distanceToAxis-offset); break;
  7984. case QCPAxis::atBottom: labelAnchor = QPointF(position, axisRect.bottom()+distanceToAxis+offset); break;
  7985. }
  7986. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled
  7987. {
  7988. CachedLabel *cachedLabel = mLabelCache.take(text); // attempt to get label from cache
  7989. if (!cachedLabel) // no cached label existed, create it
  7990. {
  7991. cachedLabel = new CachedLabel;
  7992. TickLabelData labelData = getTickLabelData(painter->font(), text);
  7993. cachedLabel->offset = getTickLabelDrawOffset(labelData)+labelData.rotatedTotalBounds.topLeft();
  7994. if (!qFuzzyCompare(1.0, mParentPlot->bufferDevicePixelRatio()))
  7995. {
  7996. cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()*mParentPlot->bufferDevicePixelRatio());
  7997. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  7998. # ifdef QCP_DEVICEPIXELRATIO_FLOAT
  7999. cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF());
  8000. # else
  8001. cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio());
  8002. # endif
  8003. #endif
  8004. } else
  8005. cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
  8006. cachedLabel->pixmap.fill(Qt::transparent);
  8007. QCPPainter cachePainter(&cachedLabel->pixmap);
  8008. cachePainter.setPen(painter->pen());
  8009. drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData);
  8010. }
  8011. // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
  8012. bool labelClippedByBorder = false;
  8013. if (tickLabelSide == QCPAxis::lsOutside)
  8014. {
  8015. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8016. labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width()/mParentPlot->bufferDevicePixelRatio() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left();
  8017. else
  8018. labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height()/mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top();
  8019. }
  8020. if (!labelClippedByBorder)
  8021. {
  8022. painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap);
  8023. finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
  8024. }
  8025. mLabelCache.insert(text, cachedLabel); // return label to cache or insert for the first time if newly created
  8026. } else // label caching disabled, draw text directly on surface:
  8027. {
  8028. TickLabelData labelData = getTickLabelData(painter->font(), text);
  8029. QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData);
  8030. // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
  8031. bool labelClippedByBorder = false;
  8032. if (tickLabelSide == QCPAxis::lsOutside)
  8033. {
  8034. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8035. labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left();
  8036. else
  8037. labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top();
  8038. }
  8039. if (!labelClippedByBorder)
  8040. {
  8041. drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData);
  8042. finalSize = labelData.rotatedTotalBounds.size();
  8043. }
  8044. }
  8045. // expand passed tickLabelsSize if current tick label is larger:
  8046. if (finalSize.width() > tickLabelsSize->width())
  8047. tickLabelsSize->setWidth(finalSize.width());
  8048. if (finalSize.height() > tickLabelsSize->height())
  8049. tickLabelsSize->setHeight(finalSize.height());
  8050. }
  8051. /*! \internal
  8052. This is a \ref placeTickLabel helper function.
  8053. Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a
  8054. y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to
  8055. directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when
  8056. QCP::phCacheLabels plotting hint is not set.
  8057. */
  8058. void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const
  8059. {
  8060. // backup painter settings that we're about to change:
  8061. QTransform oldTransform = painter->transform();
  8062. QFont oldFont = painter->font();
  8063. // transform painter to position/rotation:
  8064. painter->translate(x, y);
  8065. if (!qFuzzyIsNull(tickLabelRotation))
  8066. painter->rotate(tickLabelRotation);
  8067. // draw text:
  8068. if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used
  8069. {
  8070. painter->setFont(labelData.baseFont);
  8071. painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart);
  8072. if (!labelData.suffixPart.isEmpty())
  8073. painter->drawText(labelData.baseBounds.width()+1+labelData.expBounds.width(), 0, 0, 0, Qt::TextDontClip, labelData.suffixPart);
  8074. painter->setFont(labelData.expFont);
  8075. painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart);
  8076. } else
  8077. {
  8078. painter->setFont(labelData.baseFont);
  8079. painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart);
  8080. }
  8081. // reset painter settings to what it was before:
  8082. painter->setTransform(oldTransform);
  8083. painter->setFont(oldFont);
  8084. }
  8085. /*! \internal
  8086. This is a \ref placeTickLabel helper function.
  8087. Transforms the passed \a text and \a font to a tickLabelData structure that can then be further
  8088. processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and
  8089. exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes.
  8090. */
  8091. QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const
  8092. {
  8093. TickLabelData result;
  8094. // determine whether beautiful decimal powers should be used
  8095. bool useBeautifulPowers = false;
  8096. int ePos = -1; // first index of exponent part, text before that will be basePart, text until eLast will be expPart
  8097. int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart
  8098. if (substituteExponent)
  8099. {
  8100. ePos = text.indexOf(QLatin1Char('e'));
  8101. if (ePos > 0 && text.at(ePos-1).isDigit())
  8102. {
  8103. eLast = ePos;
  8104. while (eLast+1 < text.size() && (text.at(eLast+1) == QLatin1Char('+') || text.at(eLast+1) == QLatin1Char('-') || text.at(eLast+1).isDigit()))
  8105. ++eLast;
  8106. if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as beautifiable power
  8107. useBeautifulPowers = true;
  8108. }
  8109. }
  8110. // calculate text bounding rects and do string preparation for beautiful decimal powers:
  8111. result.baseFont = font;
  8112. if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line
  8113. 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
  8114. if (useBeautifulPowers)
  8115. {
  8116. // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent:
  8117. result.basePart = text.left(ePos);
  8118. result.suffixPart = text.mid(eLast+1); // also drawn normally but after exponent
  8119. // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base:
  8120. if (abbreviateDecimalPowers && result.basePart == QLatin1String("1"))
  8121. result.basePart = QLatin1String("10");
  8122. else
  8123. result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + QLatin1String("10");
  8124. result.expPart = text.mid(ePos+1, eLast-ePos);
  8125. // clip "+" and leading zeros off expPart:
  8126. while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e'
  8127. result.expPart.remove(1, 1);
  8128. if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+'))
  8129. result.expPart.remove(0, 1);
  8130. // prepare smaller font for exponent:
  8131. result.expFont = font;
  8132. if (result.expFont.pointSize() > 0)
  8133. result.expFont.setPointSize(result.expFont.pointSize()*0.75);
  8134. else
  8135. result.expFont.setPixelSize(result.expFont.pixelSize()*0.75);
  8136. // calculate bounding rects of base part(s), exponent part and total one:
  8137. result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart);
  8138. result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart);
  8139. if (!result.suffixPart.isEmpty())
  8140. result.suffixBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.suffixPart);
  8141. 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
  8142. } else // useBeautifulPowers == false
  8143. {
  8144. result.basePart = text;
  8145. result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart);
  8146. }
  8147. 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
  8148. // calculate possibly different bounding rect after rotation:
  8149. result.rotatedTotalBounds = result.totalBounds;
  8150. if (!qFuzzyIsNull(tickLabelRotation))
  8151. {
  8152. QTransform transform;
  8153. transform.rotate(tickLabelRotation);
  8154. result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds);
  8155. }
  8156. return result;
  8157. }
  8158. /*! \internal
  8159. This is a \ref placeTickLabel helper function.
  8160. Calculates the offset at which the top left corner of the specified tick label shall be drawn.
  8161. The offset is relative to a point right next to the tick the label belongs to.
  8162. This function is thus responsible for e.g. centering tick labels under ticks and positioning them
  8163. appropriately when they are rotated.
  8164. */
  8165. QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const
  8166. {
  8167. /*
  8168. calculate label offset from base point at tick (non-trivial, for best visual appearance): short
  8169. explanation for bottom axis: The anchor, i.e. the point in the label that is placed
  8170. horizontally under the corresponding tick is always on the label side that is closer to the
  8171. axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height
  8172. is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text
  8173. will be centered under the tick (i.e. displaced horizontally by half its height). At the same
  8174. time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick
  8175. labels.
  8176. */
  8177. bool doRotation = !qFuzzyIsNull(tickLabelRotation);
  8178. bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes.
  8179. double radians = tickLabelRotation/180.0*M_PI;
  8180. int x=0, y=0;
  8181. if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsInside)) // Anchor at right side of tick label
  8182. {
  8183. if (doRotation)
  8184. {
  8185. if (tickLabelRotation > 0)
  8186. {
  8187. x = -qCos(radians)*labelData.totalBounds.width();
  8188. y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0;
  8189. } else
  8190. {
  8191. x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height();
  8192. y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0;
  8193. }
  8194. } else
  8195. {
  8196. x = -labelData.totalBounds.width();
  8197. y = -labelData.totalBounds.height()/2.0;
  8198. }
  8199. } else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsInside)) // Anchor at left side of tick label
  8200. {
  8201. if (doRotation)
  8202. {
  8203. if (tickLabelRotation > 0)
  8204. {
  8205. x = +qSin(radians)*labelData.totalBounds.height();
  8206. y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0;
  8207. } else
  8208. {
  8209. x = 0;
  8210. y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0;
  8211. }
  8212. } else
  8213. {
  8214. x = 0;
  8215. y = -labelData.totalBounds.height()/2.0;
  8216. }
  8217. } else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsInside)) // Anchor at bottom side of tick label
  8218. {
  8219. if (doRotation)
  8220. {
  8221. if (tickLabelRotation > 0)
  8222. {
  8223. x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0;
  8224. y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height();
  8225. } else
  8226. {
  8227. x = -qSin(-radians)*labelData.totalBounds.height()/2.0;
  8228. y = -qCos(-radians)*labelData.totalBounds.height();
  8229. }
  8230. } else
  8231. {
  8232. x = -labelData.totalBounds.width()/2.0;
  8233. y = -labelData.totalBounds.height();
  8234. }
  8235. } else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsInside)) // Anchor at top side of tick label
  8236. {
  8237. if (doRotation)
  8238. {
  8239. if (tickLabelRotation > 0)
  8240. {
  8241. x = +qSin(radians)*labelData.totalBounds.height()/2.0;
  8242. y = 0;
  8243. } else
  8244. {
  8245. x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0;
  8246. y = +qSin(-radians)*labelData.totalBounds.width();
  8247. }
  8248. } else
  8249. {
  8250. x = -labelData.totalBounds.width()/2.0;
  8251. y = 0;
  8252. }
  8253. }
  8254. return QPointF(x, y);
  8255. }
  8256. /*! \internal
  8257. Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label
  8258. to be drawn, depending on number format etc. Since only the largest tick label is wanted for the
  8259. margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a
  8260. smaller width/height.
  8261. */
  8262. void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const
  8263. {
  8264. // note: this function must return the same tick label sizes as the placeTickLabel function.
  8265. QSize finalSize;
  8266. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label
  8267. {
  8268. const CachedLabel *cachedLabel = mLabelCache.object(text);
  8269. finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
  8270. } else // label caching disabled or no label with this text cached:
  8271. {
  8272. TickLabelData labelData = getTickLabelData(font, text);
  8273. finalSize = labelData.rotatedTotalBounds.size();
  8274. }
  8275. // expand passed tickLabelsSize if current tick label is larger:
  8276. if (finalSize.width() > tickLabelsSize->width())
  8277. tickLabelsSize->setWidth(finalSize.width());
  8278. if (finalSize.height() > tickLabelsSize->height())
  8279. tickLabelsSize->setHeight(finalSize.height());
  8280. }
  8281. /* end of 'src/axis/axis.cpp' */
  8282. /* including file 'src/scatterstyle.cpp', size 17450 */
  8283. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  8284. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8285. //////////////////// QCPScatterStyle
  8286. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8287. /*! \class QCPScatterStyle
  8288. \brief Represents the visual appearance of scatter points
  8289. This class holds information about shape, color and size of scatter points. In plottables like
  8290. QCPGraph it is used to store how scatter points shall be drawn. For example, \ref
  8291. QCPGraph::setScatterStyle takes a QCPScatterStyle instance.
  8292. A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a
  8293. fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can
  8294. be controlled with \ref setSize.
  8295. \section QCPScatterStyle-defining Specifying a scatter style
  8296. You can set all these configurations either by calling the respective functions on an instance:
  8297. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-1
  8298. Or you can use one of the various constructors that take different parameter combinations, making
  8299. it easy to specify a scatter style in a single call, like so:
  8300. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-2
  8301. \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable
  8302. There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref
  8303. QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref
  8304. isPenDefined will return false. It leads to scatter points that inherit the pen from the
  8305. plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line
  8306. color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes
  8307. it very convenient to set up typical scatter settings:
  8308. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-shortcreation
  8309. Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works
  8310. because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly
  8311. into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size)
  8312. constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref
  8313. ScatterShape, where actually a QCPScatterStyle is expected.
  8314. \section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps
  8315. QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points.
  8316. For custom shapes, you can provide a QPainterPath with the desired shape to the \ref
  8317. setCustomPath function or call the constructor that takes a painter path. The scatter shape will
  8318. automatically be set to \ref ssCustom.
  8319. For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the
  8320. constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap.
  8321. Note that \ref setSize does not influence the appearance of the pixmap.
  8322. */
  8323. /* start documentation of inline functions */
  8324. /*! \fn bool QCPScatterStyle::isNone() const
  8325. Returns whether the scatter shape is \ref ssNone.
  8326. \see setShape
  8327. */
  8328. /*! \fn bool QCPScatterStyle::isPenDefined() const
  8329. Returns whether a pen has been defined for this scatter style.
  8330. The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those
  8331. are \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen
  8332. is undefined, the pen of the respective plottable will be used for drawing scatters.
  8333. If a pen was defined for this scatter style instance, and you now wish to undefine the pen, call
  8334. \ref undefinePen.
  8335. \see setPen
  8336. */
  8337. /* end documentation of inline functions */
  8338. /*!
  8339. Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined.
  8340. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
  8341. from the plottable that uses this scatter style.
  8342. */
  8343. QCPScatterStyle::QCPScatterStyle() :
  8344. mSize(6),
  8345. mShape(ssNone),
  8346. mPen(Qt::NoPen),
  8347. mBrush(Qt::NoBrush),
  8348. mPenDefined(false)
  8349. {
  8350. }
  8351. /*!
  8352. Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or
  8353. brush is defined.
  8354. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
  8355. from the plottable that uses this scatter style.
  8356. */
  8357. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) :
  8358. mSize(size),
  8359. mShape(shape),
  8360. mPen(Qt::NoPen),
  8361. mBrush(Qt::NoBrush),
  8362. mPenDefined(false)
  8363. {
  8364. }
  8365. /*!
  8366. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
  8367. and size to \a size. No brush is defined, i.e. the scatter point will not be filled.
  8368. */
  8369. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) :
  8370. mSize(size),
  8371. mShape(shape),
  8372. mPen(QPen(color)),
  8373. mBrush(Qt::NoBrush),
  8374. mPenDefined(true)
  8375. {
  8376. }
  8377. /*!
  8378. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
  8379. the brush color to \a fill (with a solid pattern), and size to \a size.
  8380. */
  8381. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) :
  8382. mSize(size),
  8383. mShape(shape),
  8384. mPen(QPen(color)),
  8385. mBrush(QBrush(fill)),
  8386. mPenDefined(true)
  8387. {
  8388. }
  8389. /*!
  8390. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the
  8391. brush to \a brush, and size to \a size.
  8392. \warning In some cases it might be tempting to directly use a pen style like <tt>Qt::NoPen</tt> as \a pen
  8393. and a color like <tt>Qt::blue</tt> as \a brush. Notice however, that the corresponding call\n
  8394. <tt>QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)</tt>\n
  8395. doesn't necessarily lead C++ to use this constructor in some cases, but might mistake
  8396. <tt>Qt::NoPen</tt> for a QColor and use the
  8397. \ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size)
  8398. constructor instead (which will lead to an unexpected look of the scatter points). To prevent
  8399. this, be more explicit with the parameter types. For example, use <tt>QBrush(Qt::blue)</tt>
  8400. instead of just <tt>Qt::blue</tt>, to clearly point out to the compiler that this constructor is
  8401. wanted.
  8402. */
  8403. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) :
  8404. mSize(size),
  8405. mShape(shape),
  8406. mPen(pen),
  8407. mBrush(brush),
  8408. mPenDefined(pen.style() != Qt::NoPen)
  8409. {
  8410. }
  8411. /*!
  8412. Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape
  8413. is set to \ref ssPixmap.
  8414. */
  8415. QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) :
  8416. mSize(5),
  8417. mShape(ssPixmap),
  8418. mPen(Qt::NoPen),
  8419. mBrush(Qt::NoBrush),
  8420. mPixmap(pixmap),
  8421. mPenDefined(false)
  8422. {
  8423. }
  8424. /*!
  8425. Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The
  8426. scatter shape is set to \ref ssCustom.
  8427. The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly
  8428. different meaning than for built-in scatter points: The custom path will be drawn scaled by a
  8429. factor of \a size/6.0. Since the default \a size is 6, the custom path will appear in its
  8430. original size by default. To for example double the size of the path, set \a size to 12.
  8431. */
  8432. QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) :
  8433. mSize(size),
  8434. mShape(ssCustom),
  8435. mPen(pen),
  8436. mBrush(brush),
  8437. mCustomPath(customPath),
  8438. mPenDefined(pen.style() != Qt::NoPen)
  8439. {
  8440. }
  8441. /*!
  8442. Copies the specified \a properties from the \a other scatter style to this scatter style.
  8443. */
  8444. void QCPScatterStyle::setFromOther(const QCPScatterStyle &other, ScatterProperties properties)
  8445. {
  8446. if (properties.testFlag(spPen))
  8447. {
  8448. setPen(other.pen());
  8449. if (!other.isPenDefined())
  8450. undefinePen();
  8451. }
  8452. if (properties.testFlag(spBrush))
  8453. setBrush(other.brush());
  8454. if (properties.testFlag(spSize))
  8455. setSize(other.size());
  8456. if (properties.testFlag(spShape))
  8457. {
  8458. setShape(other.shape());
  8459. if (other.shape() == ssPixmap)
  8460. setPixmap(other.pixmap());
  8461. else if (other.shape() == ssCustom)
  8462. setCustomPath(other.customPath());
  8463. }
  8464. }
  8465. /*!
  8466. Sets the size (pixel diameter) of the drawn scatter points to \a size.
  8467. \see setShape
  8468. */
  8469. void QCPScatterStyle::setSize(double size)
  8470. {
  8471. mSize = size;
  8472. }
  8473. /*!
  8474. Sets the shape to \a shape.
  8475. Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref
  8476. ssPixmap and \ref ssCustom, respectively.
  8477. \see setSize
  8478. */
  8479. void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape)
  8480. {
  8481. mShape = shape;
  8482. }
  8483. /*!
  8484. Sets the pen that will be used to draw scatter points to \a pen.
  8485. If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after
  8486. a call to this function, even if \a pen is <tt>Qt::NoPen</tt>. If you have defined a pen
  8487. previously by calling this function and now wish to undefine the pen, call \ref undefinePen.
  8488. \see setBrush
  8489. */
  8490. void QCPScatterStyle::setPen(const QPen &pen)
  8491. {
  8492. mPenDefined = true;
  8493. mPen = pen;
  8494. }
  8495. /*!
  8496. Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter
  8497. shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does.
  8498. \see setPen
  8499. */
  8500. void QCPScatterStyle::setBrush(const QBrush &brush)
  8501. {
  8502. mBrush = brush;
  8503. }
  8504. /*!
  8505. Sets the pixmap that will be drawn as scatter point to \a pixmap.
  8506. Note that \ref setSize does not influence the appearance of the pixmap.
  8507. The scatter shape is automatically set to \ref ssPixmap.
  8508. */
  8509. void QCPScatterStyle::setPixmap(const QPixmap &pixmap)
  8510. {
  8511. setShape(ssPixmap);
  8512. mPixmap = pixmap;
  8513. }
  8514. /*!
  8515. Sets the custom shape that will be drawn as scatter point to \a customPath.
  8516. The scatter shape is automatically set to \ref ssCustom.
  8517. */
  8518. void QCPScatterStyle::setCustomPath(const QPainterPath &customPath)
  8519. {
  8520. setShape(ssCustom);
  8521. mCustomPath = customPath;
  8522. }
  8523. /*!
  8524. Sets this scatter style to have an undefined pen (see \ref isPenDefined for what an undefined pen
  8525. implies).
  8526. A call to \ref setPen will define a pen.
  8527. */
  8528. void QCPScatterStyle::undefinePen()
  8529. {
  8530. mPenDefined = false;
  8531. }
  8532. /*!
  8533. Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an
  8534. undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead.
  8535. This function is used by plottables (or any class that wants to draw scatters) just before a
  8536. number of scatters with this style shall be drawn with the \a painter.
  8537. \see drawShape
  8538. */
  8539. void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const
  8540. {
  8541. painter->setPen(mPenDefined ? mPen : defaultPen);
  8542. painter->setBrush(mBrush);
  8543. }
  8544. /*!
  8545. Draws the scatter shape with \a painter at position \a pos.
  8546. This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be
  8547. called before scatter points are drawn with \ref drawShape.
  8548. \see applyTo
  8549. */
  8550. void QCPScatterStyle::drawShape(QCPPainter *painter, const QPointF &pos) const
  8551. {
  8552. drawShape(painter, pos.x(), pos.y());
  8553. }
  8554. /*! \overload
  8555. Draws the scatter shape with \a painter at position \a x and \a y.
  8556. */
  8557. void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const
  8558. {
  8559. double w = mSize/2.0;
  8560. switch (mShape)
  8561. {
  8562. case ssNone: break;
  8563. case ssDot:
  8564. {
  8565. painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y));
  8566. break;
  8567. }
  8568. case ssCross:
  8569. {
  8570. painter->drawLine(QLineF(x-w, y-w, x+w, y+w));
  8571. painter->drawLine(QLineF(x-w, y+w, x+w, y-w));
  8572. break;
  8573. }
  8574. case ssPlus:
  8575. {
  8576. painter->drawLine(QLineF(x-w, y, x+w, y));
  8577. painter->drawLine(QLineF( x, y+w, x, y-w));
  8578. break;
  8579. }
  8580. case ssCircle:
  8581. {
  8582. painter->drawEllipse(QPointF(x , y), w, w);
  8583. break;
  8584. }
  8585. case ssDisc:
  8586. {
  8587. QBrush b = painter->brush();
  8588. painter->setBrush(painter->pen().color());
  8589. painter->drawEllipse(QPointF(x , y), w, w);
  8590. painter->setBrush(b);
  8591. break;
  8592. }
  8593. case ssSquare:
  8594. {
  8595. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  8596. break;
  8597. }
  8598. case ssDiamond:
  8599. {
  8600. QPointF lineArray[4] = {QPointF(x-w, y),
  8601. QPointF( x, y-w),
  8602. QPointF(x+w, y),
  8603. QPointF( x, y+w)};
  8604. painter->drawPolygon(lineArray, 4);
  8605. break;
  8606. }
  8607. case ssStar:
  8608. {
  8609. painter->drawLine(QLineF(x-w, y, x+w, y));
  8610. painter->drawLine(QLineF( x, y+w, x, y-w));
  8611. painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707));
  8612. painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707));
  8613. break;
  8614. }
  8615. case ssTriangle:
  8616. {
  8617. QPointF lineArray[3] = {QPointF(x-w, y+0.755*w),
  8618. QPointF(x+w, y+0.755*w),
  8619. QPointF( x, y-0.977*w)};
  8620. painter->drawPolygon(lineArray, 3);
  8621. break;
  8622. }
  8623. case ssTriangleInverted:
  8624. {
  8625. QPointF lineArray[3] = {QPointF(x-w, y-0.755*w),
  8626. QPointF(x+w, y-0.755*w),
  8627. QPointF( x, y+0.977*w)};
  8628. painter->drawPolygon(lineArray, 3);
  8629. break;
  8630. }
  8631. case ssCrossSquare:
  8632. {
  8633. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  8634. painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95));
  8635. painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w));
  8636. break;
  8637. }
  8638. case ssPlusSquare:
  8639. {
  8640. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  8641. painter->drawLine(QLineF(x-w, y, x+w*0.95, y));
  8642. painter->drawLine(QLineF( x, y+w, x, y-w));
  8643. break;
  8644. }
  8645. case ssCrossCircle:
  8646. {
  8647. painter->drawEllipse(QPointF(x, y), w, w);
  8648. painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670));
  8649. painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707));
  8650. break;
  8651. }
  8652. case ssPlusCircle:
  8653. {
  8654. painter->drawEllipse(QPointF(x, y), w, w);
  8655. painter->drawLine(QLineF(x-w, y, x+w, y));
  8656. painter->drawLine(QLineF( x, y+w, x, y-w));
  8657. break;
  8658. }
  8659. case ssPeace:
  8660. {
  8661. painter->drawEllipse(QPointF(x, y), w, w);
  8662. painter->drawLine(QLineF(x, y-w, x, y+w));
  8663. painter->drawLine(QLineF(x, y, x-w*0.707, y+w*0.707));
  8664. painter->drawLine(QLineF(x, y, x+w*0.707, y+w*0.707));
  8665. break;
  8666. }
  8667. case ssPixmap:
  8668. {
  8669. const double widthHalf = mPixmap.width()*0.5;
  8670. const double heightHalf = mPixmap.height()*0.5;
  8671. #if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
  8672. const QRectF clipRect = painter->clipRegion().boundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf);
  8673. #else
  8674. const QRectF clipRect = painter->clipBoundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf);
  8675. #endif
  8676. if (clipRect.contains(x, y))
  8677. painter->drawPixmap(x-widthHalf, y-heightHalf, mPixmap);
  8678. break;
  8679. }
  8680. case ssCustom:
  8681. {
  8682. QTransform oldTransform = painter->transform();
  8683. painter->translate(x, y);
  8684. painter->scale(mSize/6.0, mSize/6.0);
  8685. painter->drawPath(mCustomPath);
  8686. painter->setTransform(oldTransform);
  8687. break;
  8688. }
  8689. }
  8690. }
  8691. /* end of 'src/scatterstyle.cpp' */
  8692. //amalgamation: add datacontainer.cpp
  8693. /* including file 'src/plottable.cpp', size 38845 */
  8694. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  8695. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8696. //////////////////// QCPSelectionDecorator
  8697. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8698. /*! \class QCPSelectionDecorator
  8699. \brief Controls how a plottable's data selection is drawn
  8700. Each \ref QCPAbstractPlottable instance has one \ref QCPSelectionDecorator (accessible via \ref
  8701. QCPAbstractPlottable::selectionDecorator) and uses it when drawing selected segments of its data.
  8702. The selection decorator controls both pen (\ref setPen) and brush (\ref setBrush), as well as the
  8703. scatter style (\ref setScatterStyle) if the plottable draws scatters. Since a \ref
  8704. QCPScatterStyle is itself composed of different properties such as color shape and size, the
  8705. decorator allows specifying exactly which of those properties shall be used for the selected data
  8706. point, via \ref setUsedScatterProperties.
  8707. A \ref QCPSelectionDecorator subclass instance can be passed to a plottable via \ref
  8708. QCPAbstractPlottable::setSelectionDecorator, allowing greater customizability of the appearance
  8709. of selected segments.
  8710. Use \ref copyFrom to easily transfer the settings of one decorator to another one. This is
  8711. especially useful since plottables take ownership of the passed selection decorator, and thus the
  8712. same decorator instance can not be passed to multiple plottables.
  8713. Selection decorators can also themselves perform drawing operations by reimplementing \ref
  8714. drawDecoration, which is called by the plottable's draw method. The base class \ref
  8715. QCPSelectionDecorator does not make use of this however. For example, \ref
  8716. QCPSelectionDecoratorBracket draws brackets around selected data segments.
  8717. */
  8718. /*!
  8719. Creates a new QCPSelectionDecorator instance with default values
  8720. */
  8721. QCPSelectionDecorator::QCPSelectionDecorator() :
  8722. mPen(QColor(80, 80, 255), 2.5),
  8723. mBrush(Qt::NoBrush),
  8724. mScatterStyle(),
  8725. mUsedScatterProperties(QCPScatterStyle::spNone),
  8726. mPlottable(0)
  8727. {
  8728. }
  8729. QCPSelectionDecorator::~QCPSelectionDecorator()
  8730. {
  8731. }
  8732. /*!
  8733. Sets the pen that will be used by the parent plottable to draw selected data segments.
  8734. */
  8735. void QCPSelectionDecorator::setPen(const QPen &pen)
  8736. {
  8737. mPen = pen;
  8738. }
  8739. /*!
  8740. Sets the brush that will be used by the parent plottable to draw selected data segments.
  8741. */
  8742. void QCPSelectionDecorator::setBrush(const QBrush &brush)
  8743. {
  8744. mBrush = brush;
  8745. }
  8746. /*!
  8747. Sets the scatter style that will be used by the parent plottable to draw scatters in selected
  8748. data segments.
  8749. \a usedProperties specifies which parts of the passed \a scatterStyle will be used by the
  8750. plottable. The used properties can also be changed via \ref setUsedScatterProperties.
  8751. */
  8752. void QCPSelectionDecorator::setScatterStyle(const QCPScatterStyle &scatterStyle, QCPScatterStyle::ScatterProperties usedProperties)
  8753. {
  8754. mScatterStyle = scatterStyle;
  8755. setUsedScatterProperties(usedProperties);
  8756. }
  8757. /*!
  8758. Use this method to define which properties of the scatter style (set via \ref setScatterStyle)
  8759. will be used for selected data segments. All properties of the scatter style that are not
  8760. specified in \a properties will remain as specified in the plottable's original scatter style.
  8761. \see QCPScatterStyle::ScatterProperty
  8762. */
  8763. void QCPSelectionDecorator::setUsedScatterProperties(const QCPScatterStyle::ScatterProperties &properties)
  8764. {
  8765. mUsedScatterProperties = properties;
  8766. }
  8767. /*!
  8768. Sets the pen of \a painter to the pen of this selection decorator.
  8769. \see applyBrush, getFinalScatterStyle
  8770. */
  8771. void QCPSelectionDecorator::applyPen(QCPPainter *painter) const
  8772. {
  8773. painter->setPen(mPen);
  8774. }
  8775. /*!
  8776. Sets the brush of \a painter to the brush of this selection decorator.
  8777. \see applyPen, getFinalScatterStyle
  8778. */
  8779. void QCPSelectionDecorator::applyBrush(QCPPainter *painter) const
  8780. {
  8781. painter->setBrush(mBrush);
  8782. }
  8783. /*!
  8784. Returns the scatter style that the parent plottable shall use for selected scatter points. The
  8785. plottable's original (unselected) scatter style must be passed as \a unselectedStyle. Depending
  8786. on the setting of \ref setUsedScatterProperties, the returned scatter style is a mixture of this
  8787. selecion decorator's scatter style (\ref setScatterStyle), and \a unselectedStyle.
  8788. \see applyPen, applyBrush, setScatterStyle
  8789. */
  8790. QCPScatterStyle QCPSelectionDecorator::getFinalScatterStyle(const QCPScatterStyle &unselectedStyle) const
  8791. {
  8792. QCPScatterStyle result(unselectedStyle);
  8793. result.setFromOther(mScatterStyle, mUsedScatterProperties);
  8794. // if style shall inherit pen from plottable (has no own pen defined), give it the selected
  8795. // plottable pen explicitly, so it doesn't use the unselected plottable pen when used in the
  8796. // plottable:
  8797. if (!result.isPenDefined())
  8798. result.setPen(mPen);
  8799. return result;
  8800. }
  8801. /*!
  8802. Copies all properties (e.g. color, fill, scatter style) of the \a other selection decorator to
  8803. this selection decorator.
  8804. */
  8805. void QCPSelectionDecorator::copyFrom(const QCPSelectionDecorator *other)
  8806. {
  8807. setPen(other->pen());
  8808. setBrush(other->brush());
  8809. setScatterStyle(other->scatterStyle(), other->usedScatterProperties());
  8810. }
  8811. /*!
  8812. This method is called by all plottables' draw methods to allow custom selection decorations to be
  8813. drawn. Use the passed \a painter to perform the drawing operations. \a selection carries the data
  8814. selection for which the decoration shall be drawn.
  8815. The default base class implementation of \ref QCPSelectionDecorator has no special decoration, so
  8816. this method does nothing.
  8817. */
  8818. void QCPSelectionDecorator::drawDecoration(QCPPainter *painter, QCPDataSelection selection)
  8819. {
  8820. Q_UNUSED(painter)
  8821. Q_UNUSED(selection)
  8822. }
  8823. /*! \internal
  8824. This method is called as soon as a selection decorator is associated with a plottable, by a call
  8825. to \ref QCPAbstractPlottable::setSelectionDecorator. This way the selection decorator can obtain a pointer to the plottable that uses it (e.g. to access
  8826. data points via the \ref QCPAbstractPlottable::interface1D interface).
  8827. If the selection decorator was already added to a different plottable before, this method aborts
  8828. the registration and returns false.
  8829. */
  8830. bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottable)
  8831. {
  8832. if (!mPlottable)
  8833. {
  8834. mPlottable = plottable;
  8835. return true;
  8836. } else
  8837. {
  8838. qDebug() << Q_FUNC_INFO << "This selection decorator is already registered with plottable:" << reinterpret_cast<quintptr>(mPlottable);
  8839. return false;
  8840. }
  8841. }
  8842. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8843. //////////////////// QCPAbstractPlottable
  8844. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8845. /*! \class QCPAbstractPlottable
  8846. \brief The abstract base class for all data representing objects in a plot.
  8847. It defines a very basic interface like name, pen, brush, visibility etc. Since this class is
  8848. abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to
  8849. create new ways of displaying data (see "Creating own plottables" below). Plottables that display
  8850. one-dimensional data (i.e. data points have a single key dimension and one or multiple values at
  8851. each key) are based off of the template subclass \ref QCPAbstractPlottable1D, see details
  8852. there.
  8853. All further specifics are in the subclasses, for example:
  8854. \li A normal graph with possibly a line and/or scatter points \ref QCPGraph
  8855. (typically created with \ref QCustomPlot::addGraph)
  8856. \li A parametric curve: \ref QCPCurve
  8857. \li A bar chart: \ref QCPBars
  8858. \li A statistical box plot: \ref QCPStatisticalBox
  8859. \li A color encoded two-dimensional map: \ref QCPColorMap
  8860. \li An OHLC/Candlestick chart: \ref QCPFinancial
  8861. \section plottables-subclassing Creating own plottables
  8862. Subclassing directly from QCPAbstractPlottable is only recommended if you wish to display
  8863. two-dimensional data like \ref QCPColorMap, i.e. two logical key dimensions and one (or more)
  8864. data dimensions. If you want to display data with only one logical key dimension, you should
  8865. rather derive from \ref QCPAbstractPlottable1D.
  8866. If subclassing QCPAbstractPlottable directly, these are the pure virtual functions you must
  8867. implement:
  8868. \li \ref selectTest
  8869. \li \ref draw
  8870. \li \ref drawLegendIcon
  8871. \li \ref getKeyRange
  8872. \li \ref getValueRange
  8873. See the documentation of those functions for what they need to do.
  8874. For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot
  8875. coordinates to pixel coordinates. This function is quite convenient, because it takes the
  8876. orientation of the key and value axes into account for you (x and y are swapped when the key axis
  8877. is vertical and the value axis horizontal). If you are worried about performance (i.e. you need
  8878. to translate many points in a loop like QCPGraph), you can directly use \ref
  8879. QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis
  8880. yourself.
  8881. Here are some important members you inherit from QCPAbstractPlottable:
  8882. <table>
  8883. <tr>
  8884. <td>QCustomPlot *\b mParentPlot</td>
  8885. <td>A pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.</td>
  8886. </tr><tr>
  8887. <td>QString \b mName</td>
  8888. <td>The name of the plottable.</td>
  8889. </tr><tr>
  8890. <td>QPen \b mPen</td>
  8891. <td>The generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable
  8892. (e.g QCPGraph uses this pen for its graph lines and scatters)</td>
  8893. </tr><tr>
  8894. <td>QBrush \b mBrush</td>
  8895. <td>The generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable
  8896. (e.g. QCPGraph uses this brush to control filling under the graph)</td>
  8897. </tr><tr>
  8898. <td>QPointer<\ref QCPAxis> \b mKeyAxis, \b mValueAxis</td>
  8899. <td>The key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates
  8900. to pixels in either the key or value dimension. Make sure to check whether the pointer is null before using it. If one of
  8901. the axes is null, don't draw the plottable.</td>
  8902. </tr><tr>
  8903. <td>\ref QCPSelectionDecorator \b mSelectionDecorator</td>
  8904. <td>The currently set selection decorator which specifies how selected data of the plottable shall be drawn and decorated.
  8905. When drawing your data, you must consult this decorator for the appropriate pen/brush before drawing unselected/selected data segments.
  8906. Finally, you should call its \ref QCPSelectionDecorator::drawDecoration method at the end of your \ref draw implementation.</td>
  8907. </tr><tr>
  8908. <td>\ref QCP::SelectionType \b mSelectable</td>
  8909. <td>In which composition, if at all, this plottable's data may be selected. Enforcing this setting on the data selection is done
  8910. by QCPAbstractPlottable automatically.</td>
  8911. </tr><tr>
  8912. <td>\ref QCPDataSelection \b mSelection</td>
  8913. <td>Holds the current selection state of the plottable's data, i.e. the selected data ranges (\ref QCPDataRange).</td>
  8914. </tr>
  8915. </table>
  8916. */
  8917. /* start of documentation of inline functions */
  8918. /*! \fn QCPSelectionDecorator *QCPAbstractPlottable::selectionDecorator() const
  8919. Provides access to the selection decorator of this plottable. The selection decorator controls
  8920. how selected data ranges are drawn (e.g. their pen color and fill), see \ref
  8921. QCPSelectionDecorator for details.
  8922. If you wish to use an own \ref QCPSelectionDecorator subclass, pass an instance of it to \ref
  8923. setSelectionDecorator.
  8924. */
  8925. /*! \fn bool QCPAbstractPlottable::selected() const
  8926. Returns true if there are any data points of the plottable currently selected. Use \ref selection
  8927. to retrieve the current \ref QCPDataSelection.
  8928. */
  8929. /*! \fn QCPDataSelection QCPAbstractPlottable::selection() const
  8930. Returns a \ref QCPDataSelection encompassing all the data points that are currently selected on
  8931. this plottable.
  8932. \see selected, setSelection, setSelectable
  8933. */
  8934. /*! \fn virtual QCPPlottableInterface1D *QCPAbstractPlottable::interface1D()
  8935. If this plottable is a one-dimensional plottable, i.e. it implements the \ref
  8936. QCPPlottableInterface1D, returns the \a this pointer with that type. Otherwise (e.g. in the case
  8937. of a \ref QCPColorMap) returns zero.
  8938. You can use this method to gain read access to data coordinates while holding a pointer to the
  8939. abstract base class only.
  8940. */
  8941. /* end of documentation of inline functions */
  8942. /* start of documentation of pure virtual functions */
  8943. /*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0
  8944. \internal
  8945. called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation
  8946. of this plottable inside \a rect, next to the plottable name.
  8947. The passed \a painter has its cliprect set to \a rect, so painting outside of \a rect won't
  8948. appear outside the legend icon border.
  8949. */
  8950. /*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const = 0
  8951. Returns the coordinate range that all data in this plottable span in the key axis dimension. For
  8952. logarithmic plots, one can set \a inSignDomain to either \ref QCP::sdNegative or \ref
  8953. QCP::sdPositive in order to restrict the returned range to that sign domain. E.g. when only
  8954. negative range is wanted, set \a inSignDomain to \ref QCP::sdNegative and all positive points
  8955. will be ignored for range calculation. For no restriction, just set \a inSignDomain to \ref
  8956. QCP::sdBoth (default). \a foundRange is an output parameter that indicates whether a range could
  8957. be found or not. If this is false, you shouldn't use the returned range (e.g. no points in data).
  8958. Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
  8959. this function may have size zero (e.g. when there is only one data point). In this case \a
  8960. foundRange would return true, but the returned range is not a valid range in terms of \ref
  8961. QCPRange::validRange.
  8962. \see rescaleAxes, getValueRange
  8963. */
  8964. /*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const = 0
  8965. Returns the coordinate range that the data points in the specified key range (\a inKeyRange) span
  8966. in the value axis dimension. For logarithmic plots, one can set \a inSignDomain to either \ref
  8967. QCP::sdNegative or \ref QCP::sdPositive in order to restrict the returned range to that sign
  8968. domain. E.g. when only negative range is wanted, set \a inSignDomain to \ref QCP::sdNegative and
  8969. all positive points will be ignored for range calculation. For no restriction, just set \a
  8970. inSignDomain to \ref QCP::sdBoth (default). \a foundRange is an output parameter that indicates
  8971. whether a range could be found or not. If this is false, you shouldn't use the returned range
  8972. (e.g. no points in data).
  8973. If \a inKeyRange has both lower and upper bound set to zero (is equal to <tt>QCPRange()</tt>),
  8974. all data points are considered, without any restriction on the keys.
  8975. Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
  8976. this function may have size zero (e.g. when there is only one data point). In this case \a
  8977. foundRange would return true, but the returned range is not a valid range in terms of \ref
  8978. QCPRange::validRange.
  8979. \see rescaleAxes, getKeyRange
  8980. */
  8981. /* end of documentation of pure virtual functions */
  8982. /* start of documentation of signals */
  8983. /*! \fn void QCPAbstractPlottable::selectionChanged(bool selected)
  8984. This signal is emitted when the selection state of this plottable has changed, either by user
  8985. interaction or by a direct call to \ref setSelection. The parameter \a selected indicates whether
  8986. there are any points selected or not.
  8987. \see selectionChanged(const QCPDataSelection &selection)
  8988. */
  8989. /*! \fn void QCPAbstractPlottable::selectionChanged(const QCPDataSelection &selection)
  8990. This signal is emitted when the selection state of this plottable has changed, either by user
  8991. interaction or by a direct call to \ref setSelection. The parameter \a selection holds the
  8992. currently selected data ranges.
  8993. \see selectionChanged(bool selected)
  8994. */
  8995. /*! \fn void QCPAbstractPlottable::selectableChanged(QCP::SelectionType selectable);
  8996. This signal is emitted when the selectability of this plottable has changed.
  8997. \see setSelectable
  8998. */
  8999. /* end of documentation of signals */
  9000. /*!
  9001. Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as
  9002. its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance
  9003. and have perpendicular orientations. If either of these restrictions is violated, a corresponding
  9004. message is printed to the debug output (qDebug), the construction is not aborted, though.
  9005. Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables,
  9006. it can't be directly instantiated.
  9007. You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead.
  9008. */
  9009. QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  9010. QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect()),
  9011. mName(),
  9012. mAntialiasedFill(true),
  9013. mAntialiasedScatters(true),
  9014. mPen(Qt::black),
  9015. mBrush(Qt::NoBrush),
  9016. mKeyAxis(keyAxis),
  9017. mValueAxis(valueAxis),
  9018. mSelectable(QCP::stWhole),
  9019. mSelectionDecorator(0)
  9020. {
  9021. if (keyAxis->parentPlot() != valueAxis->parentPlot())
  9022. qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
  9023. if (keyAxis->orientation() == valueAxis->orientation())
  9024. qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other.";
  9025. mParentPlot->registerPlottable(this);
  9026. setSelectionDecorator(new QCPSelectionDecorator);
  9027. }
  9028. QCPAbstractPlottable::~QCPAbstractPlottable()
  9029. {
  9030. if (mSelectionDecorator)
  9031. {
  9032. delete mSelectionDecorator;
  9033. mSelectionDecorator = 0;
  9034. }
  9035. }
  9036. /*!
  9037. The name is the textual representation of this plottable as it is displayed in the legend
  9038. (\ref QCPLegend). It may contain any UTF-8 characters, including newlines.
  9039. */
  9040. void QCPAbstractPlottable::setName(const QString &name)
  9041. {
  9042. mName = name;
  9043. }
  9044. /*!
  9045. Sets whether fills of this plottable are drawn antialiased or not.
  9046. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  9047. QCustomPlot::setNotAntialiasedElements.
  9048. */
  9049. void QCPAbstractPlottable::setAntialiasedFill(bool enabled)
  9050. {
  9051. mAntialiasedFill = enabled;
  9052. }
  9053. /*!
  9054. Sets whether the scatter symbols of this plottable are drawn antialiased or not.
  9055. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  9056. QCustomPlot::setNotAntialiasedElements.
  9057. */
  9058. void QCPAbstractPlottable::setAntialiasedScatters(bool enabled)
  9059. {
  9060. mAntialiasedScatters = enabled;
  9061. }
  9062. /*!
  9063. The pen is used to draw basic lines that make up the plottable representation in the
  9064. plot.
  9065. For example, the \ref QCPGraph subclass draws its graph lines with this pen.
  9066. \see setBrush
  9067. */
  9068. void QCPAbstractPlottable::setPen(const QPen &pen)
  9069. {
  9070. mPen = pen;
  9071. }
  9072. /*!
  9073. The brush is used to draw basic fills of the plottable representation in the
  9074. plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
  9075. For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when
  9076. it's not set to Qt::NoBrush.
  9077. \see setPen
  9078. */
  9079. void QCPAbstractPlottable::setBrush(const QBrush &brush)
  9080. {
  9081. mBrush = brush;
  9082. }
  9083. /*!
  9084. The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
  9085. to the plottable's value axis. This function performs no checks to make sure this is the case.
  9086. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
  9087. y-axis (QCustomPlot::yAxis) as value axis.
  9088. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  9089. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  9090. \see setValueAxis
  9091. */
  9092. void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis)
  9093. {
  9094. mKeyAxis = axis;
  9095. }
  9096. /*!
  9097. The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is
  9098. orthogonal to the plottable's key axis. This function performs no checks to make sure this is the
  9099. case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and
  9100. the y-axis (QCustomPlot::yAxis) as value axis.
  9101. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  9102. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  9103. \see setKeyAxis
  9104. */
  9105. void QCPAbstractPlottable::setValueAxis(QCPAxis *axis)
  9106. {
  9107. mValueAxis = axis;
  9108. }
  9109. /*!
  9110. Sets which data ranges of this plottable are selected. Selected data ranges are drawn differently
  9111. (e.g. color) in the plot. This can be controlled via the selection decorator (see \ref
  9112. selectionDecorator).
  9113. The entire selection mechanism for plottables is handled automatically when \ref
  9114. QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
  9115. you wish to change the selection state programmatically.
  9116. Using \ref setSelectable you can further specify for each plottable whether and to which
  9117. granularity it is selectable. If \a selection is not compatible with the current \ref
  9118. QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted
  9119. accordingly (see \ref QCPDataSelection::enforceType).
  9120. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  9121. \see setSelectable, selectTest
  9122. */
  9123. void QCPAbstractPlottable::setSelection(QCPDataSelection selection)
  9124. {
  9125. selection.enforceType(mSelectable);
  9126. if (mSelection != selection)
  9127. {
  9128. mSelection = selection;
  9129. emit selectionChanged(selected());
  9130. emit selectionChanged(mSelection);
  9131. }
  9132. }
  9133. /*!
  9134. Use this method to set an own QCPSelectionDecorator (subclass) instance. This allows you to
  9135. customize the visual representation of selected data ranges further than by using the default
  9136. QCPSelectionDecorator.
  9137. The plottable takes ownership of the \a decorator.
  9138. The currently set decorator can be accessed via \ref selectionDecorator.
  9139. */
  9140. void QCPAbstractPlottable::setSelectionDecorator(QCPSelectionDecorator *decorator)
  9141. {
  9142. if (decorator)
  9143. {
  9144. if (decorator->registerWithPlottable(this))
  9145. {
  9146. if (mSelectionDecorator) // delete old decorator if necessary
  9147. delete mSelectionDecorator;
  9148. mSelectionDecorator = decorator;
  9149. }
  9150. } else if (mSelectionDecorator) // just clear decorator
  9151. {
  9152. delete mSelectionDecorator;
  9153. mSelectionDecorator = 0;
  9154. }
  9155. }
  9156. /*!
  9157. Sets whether and to which granularity this plottable can be selected.
  9158. A selection can happen by clicking on the QCustomPlot surface (When \ref
  9159. QCustomPlot::setInteractions contains \ref QCP::iSelectPlottables), by dragging a selection rect
  9160. (When \ref QCustomPlot::setSelectionRectMode is \ref QCP::srmSelect), or programmatically by
  9161. calling \ref setSelection.
  9162. \see setSelection, QCP::SelectionType
  9163. */
  9164. void QCPAbstractPlottable::setSelectable(QCP::SelectionType selectable)
  9165. {
  9166. if (mSelectable != selectable)
  9167. {
  9168. mSelectable = selectable;
  9169. QCPDataSelection oldSelection = mSelection;
  9170. mSelection.enforceType(mSelectable);
  9171. emit selectableChanged(mSelectable);
  9172. if (mSelection != oldSelection)
  9173. {
  9174. emit selectionChanged(selected());
  9175. emit selectionChanged(mSelection);
  9176. }
  9177. }
  9178. }
  9179. /*!
  9180. Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface,
  9181. taking the orientations of the axes associated with this plottable into account (e.g. whether key
  9182. represents x or y).
  9183. \a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y.
  9184. \see pixelsToCoords, QCPAxis::coordToPixel
  9185. */
  9186. void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const
  9187. {
  9188. QCPAxis *keyAxis = mKeyAxis.data();
  9189. QCPAxis *valueAxis = mValueAxis.data();
  9190. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  9191. if (keyAxis->orientation() == Qt::Horizontal)
  9192. {
  9193. x = keyAxis->coordToPixel(key);
  9194. y = valueAxis->coordToPixel(value);
  9195. } else
  9196. {
  9197. y = keyAxis->coordToPixel(key);
  9198. x = valueAxis->coordToPixel(value);
  9199. }
  9200. }
  9201. /*! \overload
  9202. Transforms the given \a key and \a value to pixel coordinates and returns them in a QPointF.
  9203. */
  9204. const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const
  9205. {
  9206. QCPAxis *keyAxis = mKeyAxis.data();
  9207. QCPAxis *valueAxis = mValueAxis.data();
  9208. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
  9209. if (keyAxis->orientation() == Qt::Horizontal)
  9210. return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value));
  9211. else
  9212. return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key));
  9213. }
  9214. /*!
  9215. Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates,
  9216. taking the orientations of the axes associated with this plottable into account (e.g. whether key
  9217. represents x or y).
  9218. \a x and \a y are transformed to the plot coodinates and are written to \a key and \a value.
  9219. \see coordsToPixels, QCPAxis::coordToPixel
  9220. */
  9221. void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const
  9222. {
  9223. QCPAxis *keyAxis = mKeyAxis.data();
  9224. QCPAxis *valueAxis = mValueAxis.data();
  9225. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  9226. if (keyAxis->orientation() == Qt::Horizontal)
  9227. {
  9228. key = keyAxis->pixelToCoord(x);
  9229. value = valueAxis->pixelToCoord(y);
  9230. } else
  9231. {
  9232. key = keyAxis->pixelToCoord(y);
  9233. value = valueAxis->pixelToCoord(x);
  9234. }
  9235. }
  9236. /*! \overload
  9237. Returns the pixel input \a pixelPos as plot coordinates \a key and \a value.
  9238. */
  9239. void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
  9240. {
  9241. pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value);
  9242. }
  9243. /*!
  9244. Rescales the key and value axes associated with this plottable to contain all displayed data, so
  9245. the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make
  9246. sure not to rescale to an illegal range i.e. a range containing different signs and/or zero.
  9247. Instead it will stay in the current sign domain and ignore all parts of the plottable that lie
  9248. outside of that domain.
  9249. \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show
  9250. multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has
  9251. \a onlyEnlarge set to false (the default), and all subsequent set to true.
  9252. \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale
  9253. */
  9254. void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const
  9255. {
  9256. rescaleKeyAxis(onlyEnlarge);
  9257. rescaleValueAxis(onlyEnlarge);
  9258. }
  9259. /*!
  9260. Rescales the key axis of the plottable so the whole plottable is visible.
  9261. See \ref rescaleAxes for detailed behaviour.
  9262. */
  9263. void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const
  9264. {
  9265. QCPAxis *keyAxis = mKeyAxis.data();
  9266. if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
  9267. QCP::SignDomain signDomain = QCP::sdBoth;
  9268. if (keyAxis->scaleType() == QCPAxis::stLogarithmic)
  9269. signDomain = (keyAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  9270. bool foundRange;
  9271. QCPRange newRange = getKeyRange(foundRange, signDomain);
  9272. if (foundRange)
  9273. {
  9274. if (onlyEnlarge)
  9275. newRange.expand(keyAxis->range());
  9276. 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
  9277. {
  9278. 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
  9279. if (keyAxis->scaleType() == QCPAxis::stLinear)
  9280. {
  9281. newRange.lower = center-keyAxis->range().size()/2.0;
  9282. newRange.upper = center+keyAxis->range().size()/2.0;
  9283. } else // scaleType() == stLogarithmic
  9284. {
  9285. newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower);
  9286. newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower);
  9287. }
  9288. }
  9289. keyAxis->setRange(newRange);
  9290. }
  9291. }
  9292. /*!
  9293. Rescales the value axis of the plottable so the whole plottable is visible. If \a inKeyRange is
  9294. set to true, only the data points which are in the currently visible key axis range are
  9295. considered.
  9296. Returns true if the axis was actually scaled. This might not be the case if this plottable has an
  9297. invalid range, e.g. because it has no data points.
  9298. See \ref rescaleAxes for detailed behaviour.
  9299. */
  9300. void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const
  9301. {
  9302. QCPAxis *keyAxis = mKeyAxis.data();
  9303. QCPAxis *valueAxis = mValueAxis.data();
  9304. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  9305. QCP::SignDomain signDomain = QCP::sdBoth;
  9306. if (valueAxis->scaleType() == QCPAxis::stLogarithmic)
  9307. signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  9308. bool foundRange;
  9309. QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange());
  9310. if (foundRange)
  9311. {
  9312. if (onlyEnlarge)
  9313. newRange.expand(valueAxis->range());
  9314. 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
  9315. {
  9316. 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
  9317. if (valueAxis->scaleType() == QCPAxis::stLinear)
  9318. {
  9319. newRange.lower = center-valueAxis->range().size()/2.0;
  9320. newRange.upper = center+valueAxis->range().size()/2.0;
  9321. } else // scaleType() == stLogarithmic
  9322. {
  9323. newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  9324. newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  9325. }
  9326. }
  9327. valueAxis->setRange(newRange);
  9328. }
  9329. }
  9330. /*! \overload
  9331. Adds this plottable to the specified \a legend.
  9332. Creates a QCPPlottableLegendItem which is inserted into the legend. Returns true on success, i.e.
  9333. when the legend exists and a legend item associated with this plottable isn't already in the
  9334. legend.
  9335. If the plottable needs a more specialized representation in the legend, you can create a
  9336. corresponding subclass of \ref QCPPlottableLegendItem and add it to the legend manually instead
  9337. of calling this method.
  9338. \see removeFromLegend, QCPLegend::addItem
  9339. */
  9340. bool QCPAbstractPlottable::addToLegend(QCPLegend *legend)
  9341. {
  9342. if (!legend)
  9343. {
  9344. qDebug() << Q_FUNC_INFO << "passed legend is null";
  9345. return false;
  9346. }
  9347. if (legend->parentPlot() != mParentPlot)
  9348. {
  9349. qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable";
  9350. return false;
  9351. }
  9352. if (!legend->hasItemWithPlottable(this))
  9353. {
  9354. legend->addItem(new QCPPlottableLegendItem(legend, this));
  9355. return true;
  9356. } else
  9357. return false;
  9358. }
  9359. /*! \overload
  9360. Adds this plottable to the legend of the parent QCustomPlot (\ref QCustomPlot::legend).
  9361. \see removeFromLegend
  9362. */
  9363. bool QCPAbstractPlottable::addToLegend()
  9364. {
  9365. if (!mParentPlot || !mParentPlot->legend)
  9366. return false;
  9367. else
  9368. return addToLegend(mParentPlot->legend);
  9369. }
  9370. /*! \overload
  9371. Removes the plottable from the specifed \a legend. This means the \ref QCPPlottableLegendItem
  9372. that is associated with this plottable is removed.
  9373. Returns true on success, i.e. if the legend exists and a legend item associated with this
  9374. plottable was found and removed.
  9375. \see addToLegend, QCPLegend::removeItem
  9376. */
  9377. bool QCPAbstractPlottable::removeFromLegend(QCPLegend *legend) const
  9378. {
  9379. if (!legend)
  9380. {
  9381. qDebug() << Q_FUNC_INFO << "passed legend is null";
  9382. return false;
  9383. }
  9384. if (QCPPlottableLegendItem *lip = legend->itemWithPlottable(this))
  9385. return legend->removeItem(lip);
  9386. else
  9387. return false;
  9388. }
  9389. /*! \overload
  9390. Removes the plottable from the legend of the parent QCustomPlot.
  9391. \see addToLegend
  9392. */
  9393. bool QCPAbstractPlottable::removeFromLegend() const
  9394. {
  9395. if (!mParentPlot || !mParentPlot->legend)
  9396. return false;
  9397. else
  9398. return removeFromLegend(mParentPlot->legend);
  9399. }
  9400. /* inherits documentation from base class */
  9401. QRect QCPAbstractPlottable::clipRect() const
  9402. {
  9403. if (mKeyAxis && mValueAxis)
  9404. return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect();
  9405. else
  9406. return QRect();
  9407. }
  9408. /* inherits documentation from base class */
  9409. QCP::Interaction QCPAbstractPlottable::selectionCategory() const
  9410. {
  9411. return QCP::iSelectPlottables;
  9412. }
  9413. /*! \internal
  9414. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  9415. before drawing plottable lines.
  9416. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  9417. This function takes into account the local setting of the antialiasing flag as well as the
  9418. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  9419. QCustomPlot::setNotAntialiasedElements.
  9420. \seebaseclassmethod
  9421. \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint
  9422. */
  9423. void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const
  9424. {
  9425. applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables);
  9426. }
  9427. /*! \internal
  9428. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  9429. before drawing plottable fills.
  9430. This function takes into account the local setting of the antialiasing flag as well as the
  9431. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  9432. QCustomPlot::setNotAntialiasedElements.
  9433. \see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint
  9434. */
  9435. void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const
  9436. {
  9437. applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills);
  9438. }
  9439. /*! \internal
  9440. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  9441. before drawing plottable scatter points.
  9442. This function takes into account the local setting of the antialiasing flag as well as the
  9443. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  9444. QCustomPlot::setNotAntialiasedElements.
  9445. \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint
  9446. */
  9447. void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const
  9448. {
  9449. applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
  9450. }
  9451. /* inherits documentation from base class */
  9452. void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  9453. {
  9454. Q_UNUSED(event)
  9455. if (mSelectable != QCP::stNone)
  9456. {
  9457. QCPDataSelection newSelection = details.value<QCPDataSelection>();
  9458. QCPDataSelection selectionBefore = mSelection;
  9459. if (additive)
  9460. {
  9461. if (mSelectable == QCP::stWhole) // in whole selection mode, we toggle to no selection even if currently unselected point was hit
  9462. {
  9463. if (selected())
  9464. setSelection(QCPDataSelection());
  9465. else
  9466. setSelection(newSelection);
  9467. } else // in all other selection modes we toggle selections of homogeneously selected/unselected segments
  9468. {
  9469. if (mSelection.contains(newSelection)) // if entire newSelection is already selected, toggle selection
  9470. setSelection(mSelection-newSelection);
  9471. else
  9472. setSelection(mSelection+newSelection);
  9473. }
  9474. } else
  9475. setSelection(newSelection);
  9476. if (selectionStateChanged)
  9477. *selectionStateChanged = mSelection != selectionBefore;
  9478. }
  9479. }
  9480. /* inherits documentation from base class */
  9481. void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged)
  9482. {
  9483. if (mSelectable != QCP::stNone)
  9484. {
  9485. QCPDataSelection selectionBefore = mSelection;
  9486. setSelection(QCPDataSelection());
  9487. if (selectionStateChanged)
  9488. *selectionStateChanged = mSelection != selectionBefore;
  9489. }
  9490. }
  9491. /* end of 'src/plottable.cpp' */
  9492. /* including file 'src/item.cpp', size 49269 */
  9493. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  9494. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9495. //////////////////// QCPItemAnchor
  9496. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9497. /*! \class QCPItemAnchor
  9498. \brief An anchor of an item to which positions can be attached to.
  9499. An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't
  9500. control anything on its item, but provides a way to tie other items via their positions to the
  9501. anchor.
  9502. For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight.
  9503. Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can
  9504. attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by
  9505. calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the
  9506. QCPItemRect. This way the start of the line will now always follow the respective anchor location
  9507. on the rect item.
  9508. Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an
  9509. anchor to other positions.
  9510. To learn how to provide anchors in your own item subclasses, see the subclassing section of the
  9511. QCPAbstractItem documentation.
  9512. */
  9513. /* start documentation of inline functions */
  9514. /*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition()
  9515. Returns 0 if this instance is merely a QCPItemAnchor, and a valid pointer of type QCPItemPosition* if
  9516. it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor).
  9517. This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids
  9518. dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with
  9519. gcc compiler).
  9520. */
  9521. /* end documentation of inline functions */
  9522. /*!
  9523. Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if
  9524. you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as
  9525. explained in the subclassing section of the QCPAbstractItem documentation.
  9526. */
  9527. QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId) :
  9528. mName(name),
  9529. mParentPlot(parentPlot),
  9530. mParentItem(parentItem),
  9531. mAnchorId(anchorId)
  9532. {
  9533. }
  9534. QCPItemAnchor::~QCPItemAnchor()
  9535. {
  9536. // unregister as parent at children:
  9537. foreach (QCPItemPosition *child, mChildrenX.toList())
  9538. {
  9539. if (child->parentAnchorX() == this)
  9540. child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX
  9541. }
  9542. foreach (QCPItemPosition *child, mChildrenY.toList())
  9543. {
  9544. if (child->parentAnchorY() == this)
  9545. child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY
  9546. }
  9547. }
  9548. /*!
  9549. Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface.
  9550. The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the
  9551. parent item, QCPItemAnchor is just an intermediary.
  9552. */
  9553. QPointF QCPItemAnchor::pixelPosition() const
  9554. {
  9555. if (mParentItem)
  9556. {
  9557. if (mAnchorId > -1)
  9558. {
  9559. return mParentItem->anchorPixelPosition(mAnchorId);
  9560. } else
  9561. {
  9562. qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId;
  9563. return QPointF();
  9564. }
  9565. } else
  9566. {
  9567. qDebug() << Q_FUNC_INFO << "no parent item set";
  9568. return QPointF();
  9569. }
  9570. }
  9571. /*! \internal
  9572. Adds \a pos to the childX list of this anchor, which keeps track of which children use this
  9573. anchor as parent anchor for the respective coordinate. This is necessary to notify the children
  9574. prior to destruction of the anchor.
  9575. Note that this function does not change the parent setting in \a pos.
  9576. */
  9577. void QCPItemAnchor::addChildX(QCPItemPosition *pos)
  9578. {
  9579. if (!mChildrenX.contains(pos))
  9580. mChildrenX.insert(pos);
  9581. else
  9582. qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
  9583. }
  9584. /*! \internal
  9585. Removes \a pos from the childX list of this anchor.
  9586. Note that this function does not change the parent setting in \a pos.
  9587. */
  9588. void QCPItemAnchor::removeChildX(QCPItemPosition *pos)
  9589. {
  9590. if (!mChildrenX.remove(pos))
  9591. qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
  9592. }
  9593. /*! \internal
  9594. Adds \a pos to the childY list of this anchor, which keeps track of which children use this
  9595. anchor as parent anchor for the respective coordinate. This is necessary to notify the children
  9596. prior to destruction of the anchor.
  9597. Note that this function does not change the parent setting in \a pos.
  9598. */
  9599. void QCPItemAnchor::addChildY(QCPItemPosition *pos)
  9600. {
  9601. if (!mChildrenY.contains(pos))
  9602. mChildrenY.insert(pos);
  9603. else
  9604. qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
  9605. }
  9606. /*! \internal
  9607. Removes \a pos from the childY list of this anchor.
  9608. Note that this function does not change the parent setting in \a pos.
  9609. */
  9610. void QCPItemAnchor::removeChildY(QCPItemPosition *pos)
  9611. {
  9612. if (!mChildrenY.remove(pos))
  9613. qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
  9614. }
  9615. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9616. //////////////////// QCPItemPosition
  9617. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9618. /*! \class QCPItemPosition
  9619. \brief Manages the position of an item.
  9620. Every item has at least one public QCPItemPosition member pointer which provides ways to position the
  9621. item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two:
  9622. \a topLeft and \a bottomRight.
  9623. QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type
  9624. defines how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel
  9625. coordinates, as plot coordinates of certain axes, etc. For more advanced plots it is also
  9626. possible to assign different types per X/Y coordinate of the position (see \ref setTypeX, \ref
  9627. setTypeY). This way an item could be positioned at a fixed pixel distance from the top in the Y
  9628. direction, while following a plot coordinate in the X direction.
  9629. A QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. This way you can tie
  9630. multiple items together. If the QCPItemPosition has a parent, its coordinates (\ref setCoords)
  9631. are considered to be absolute pixels in the reference frame of the parent anchor, where (0, 0)
  9632. means directly ontop of the parent anchor. For example, You could attach the \a start position of
  9633. a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting point of the line
  9634. always be centered under the text label, no matter where the text is moved to. For more advanced
  9635. plots, it is possible to assign different parent anchors per X/Y coordinate of the position, see
  9636. \ref setParentAnchorX, \ref setParentAnchorY. This way an item could follow another item in the X
  9637. direction but stay at a fixed position in the Y direction. Or even follow item A in X, and item B
  9638. in Y.
  9639. Note that every QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent
  9640. anchor for other positions.
  9641. To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPosition. This
  9642. works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref
  9643. setPixelPosition transforms the coordinates appropriately, to make the position appear at the specified
  9644. pixel values.
  9645. */
  9646. /* start documentation of inline functions */
  9647. /*! \fn QCPItemPosition::PositionType *QCPItemPosition::type() const
  9648. Returns the current position type.
  9649. If different types were set for X and Y (\ref setTypeX, \ref setTypeY), this method returns the
  9650. type of the X coordinate. In that case rather use \a typeX() and \a typeY().
  9651. \see setType
  9652. */
  9653. /*! \fn QCPItemAnchor *QCPItemPosition::parentAnchor() const
  9654. Returns the current parent anchor.
  9655. If different parent anchors were set for X and Y (\ref setParentAnchorX, \ref setParentAnchorY),
  9656. this method returns the parent anchor of the Y coordinate. In that case rather use \a
  9657. parentAnchorX() and \a parentAnchorY().
  9658. \see setParentAnchor
  9659. */
  9660. /* end documentation of inline functions */
  9661. /*!
  9662. Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if
  9663. you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as
  9664. explained in the subclassing section of the QCPAbstractItem documentation.
  9665. */
  9666. QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name) :
  9667. QCPItemAnchor(parentPlot, parentItem, name),
  9668. mPositionTypeX(ptAbsolute),
  9669. mPositionTypeY(ptAbsolute),
  9670. mKey(0),
  9671. mValue(0),
  9672. mParentAnchorX(0),
  9673. mParentAnchorY(0)
  9674. {
  9675. }
  9676. QCPItemPosition::~QCPItemPosition()
  9677. {
  9678. // unregister as parent at children:
  9679. // Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then
  9680. // the setParentAnchor(0) call the correct QCPItemPosition::pixelPosition function instead of QCPItemAnchor::pixelPosition
  9681. foreach (QCPItemPosition *child, mChildrenX.toList())
  9682. {
  9683. if (child->parentAnchorX() == this)
  9684. child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX
  9685. }
  9686. foreach (QCPItemPosition *child, mChildrenY.toList())
  9687. {
  9688. if (child->parentAnchorY() == this)
  9689. child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY
  9690. }
  9691. // unregister as child in parent:
  9692. if (mParentAnchorX)
  9693. mParentAnchorX->removeChildX(this);
  9694. if (mParentAnchorY)
  9695. mParentAnchorY->removeChildY(this);
  9696. }
  9697. /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
  9698. QCPAxisRect *QCPItemPosition::axisRect() const
  9699. {
  9700. return mAxisRect.data();
  9701. }
  9702. /*!
  9703. Sets the type of the position. The type defines how the coordinates passed to \ref setCoords
  9704. should be handled and how the QCPItemPosition should behave in the plot.
  9705. The possible values for \a type can be separated in two main categories:
  9706. \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords
  9707. and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes.
  9708. By default, the QCustomPlot's x- and yAxis are used.
  9709. \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This
  9710. corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref
  9711. ptAxisRectRatio. They differ only in the way the absolute position is described, see the
  9712. documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify
  9713. the axis rect with \ref setAxisRect. By default this is set to the main axis rect.
  9714. Note that the position type \ref ptPlotCoords is only available (and sensible) when the position
  9715. has no parent anchor (\ref setParentAnchor).
  9716. If the type is changed, the apparent pixel position on the plot is preserved. This means
  9717. the coordinates as retrieved with coords() and set with \ref setCoords may change in the process.
  9718. This method sets the type for both X and Y directions. It is also possible to set different types
  9719. for X and Y, see \ref setTypeX, \ref setTypeY.
  9720. */
  9721. void QCPItemPosition::setType(QCPItemPosition::PositionType type)
  9722. {
  9723. setTypeX(type);
  9724. setTypeY(type);
  9725. }
  9726. /*!
  9727. This method sets the position type of the X coordinate to \a type.
  9728. For a detailed description of what a position type is, see the documentation of \ref setType.
  9729. \see setType, setTypeY
  9730. */
  9731. void QCPItemPosition::setTypeX(QCPItemPosition::PositionType type)
  9732. {
  9733. if (mPositionTypeX != type)
  9734. {
  9735. // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
  9736. // were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning.
  9737. bool retainPixelPosition = true;
  9738. if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
  9739. retainPixelPosition = false;
  9740. if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
  9741. retainPixelPosition = false;
  9742. QPointF pixel;
  9743. if (retainPixelPosition)
  9744. pixel = pixelPosition();
  9745. mPositionTypeX = type;
  9746. if (retainPixelPosition)
  9747. setPixelPosition(pixel);
  9748. }
  9749. }
  9750. /*!
  9751. This method sets the position type of the Y coordinate to \a type.
  9752. For a detailed description of what a position type is, see the documentation of \ref setType.
  9753. \see setType, setTypeX
  9754. */
  9755. void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type)
  9756. {
  9757. if (mPositionTypeY != type)
  9758. {
  9759. // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
  9760. // were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning.
  9761. bool retainPixelPosition = true;
  9762. if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
  9763. retainPixelPosition = false;
  9764. if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
  9765. retainPixelPosition = false;
  9766. QPointF pixel;
  9767. if (retainPixelPosition)
  9768. pixel = pixelPosition();
  9769. mPositionTypeY = type;
  9770. if (retainPixelPosition)
  9771. setPixelPosition(pixel);
  9772. }
  9773. }
  9774. /*!
  9775. Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now
  9776. follow any position changes of the anchor. The local coordinate system of positions with a parent
  9777. anchor always is absolute pixels, with (0, 0) being exactly on top of the parent anchor. (Hence
  9778. the type shouldn't be set to \ref ptPlotCoords for positions with parent anchors.)
  9779. if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved
  9780. during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position
  9781. will be exactly on top of the parent anchor.
  9782. To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to 0.
  9783. If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is
  9784. set to \ref ptAbsolute, to keep the position in a valid state.
  9785. This method sets the parent anchor for both X and Y directions. It is also possible to set
  9786. different parents for X and Y, see \ref setParentAnchorX, \ref setParentAnchorY.
  9787. */
  9788. bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
  9789. {
  9790. bool successX = setParentAnchorX(parentAnchor, keepPixelPosition);
  9791. bool successY = setParentAnchorY(parentAnchor, keepPixelPosition);
  9792. return successX && successY;
  9793. }
  9794. /*!
  9795. This method sets the parent anchor of the X coordinate to \a parentAnchor.
  9796. For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor.
  9797. \see setParentAnchor, setParentAnchorY
  9798. */
  9799. bool QCPItemPosition::setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
  9800. {
  9801. // make sure self is not assigned as parent:
  9802. if (parentAnchor == this)
  9803. {
  9804. qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
  9805. return false;
  9806. }
  9807. // make sure no recursive parent-child-relationships are created:
  9808. QCPItemAnchor *currentParent = parentAnchor;
  9809. while (currentParent)
  9810. {
  9811. if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
  9812. {
  9813. // is a QCPItemPosition, might have further parent, so keep iterating
  9814. if (currentParentPos == this)
  9815. {
  9816. qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
  9817. return false;
  9818. }
  9819. currentParent = currentParentPos->parentAnchorX();
  9820. } else
  9821. {
  9822. // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
  9823. // same, to prevent a position being child of an anchor which itself depends on the position,
  9824. // because they're both on the same item:
  9825. if (currentParent->mParentItem == mParentItem)
  9826. {
  9827. qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
  9828. return false;
  9829. }
  9830. break;
  9831. }
  9832. }
  9833. // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
  9834. if (!mParentAnchorX && mPositionTypeX == ptPlotCoords)
  9835. setTypeX(ptAbsolute);
  9836. // save pixel position:
  9837. QPointF pixelP;
  9838. if (keepPixelPosition)
  9839. pixelP = pixelPosition();
  9840. // unregister at current parent anchor:
  9841. if (mParentAnchorX)
  9842. mParentAnchorX->removeChildX(this);
  9843. // register at new parent anchor:
  9844. if (parentAnchor)
  9845. parentAnchor->addChildX(this);
  9846. mParentAnchorX = parentAnchor;
  9847. // restore pixel position under new parent:
  9848. if (keepPixelPosition)
  9849. setPixelPosition(pixelP);
  9850. else
  9851. setCoords(0, coords().y());
  9852. return true;
  9853. }
  9854. /*!
  9855. This method sets the parent anchor of the Y coordinate to \a parentAnchor.
  9856. For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor.
  9857. \see setParentAnchor, setParentAnchorX
  9858. */
  9859. bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
  9860. {
  9861. // make sure self is not assigned as parent:
  9862. if (parentAnchor == this)
  9863. {
  9864. qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
  9865. return false;
  9866. }
  9867. // make sure no recursive parent-child-relationships are created:
  9868. QCPItemAnchor *currentParent = parentAnchor;
  9869. while (currentParent)
  9870. {
  9871. if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
  9872. {
  9873. // is a QCPItemPosition, might have further parent, so keep iterating
  9874. if (currentParentPos == this)
  9875. {
  9876. qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
  9877. return false;
  9878. }
  9879. currentParent = currentParentPos->parentAnchorY();
  9880. } else
  9881. {
  9882. // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
  9883. // same, to prevent a position being child of an anchor which itself depends on the position,
  9884. // because they're both on the same item:
  9885. if (currentParent->mParentItem == mParentItem)
  9886. {
  9887. qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
  9888. return false;
  9889. }
  9890. break;
  9891. }
  9892. }
  9893. // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
  9894. if (!mParentAnchorY && mPositionTypeY == ptPlotCoords)
  9895. setTypeY(ptAbsolute);
  9896. // save pixel position:
  9897. QPointF pixelP;
  9898. if (keepPixelPosition)
  9899. pixelP = pixelPosition();
  9900. // unregister at current parent anchor:
  9901. if (mParentAnchorY)
  9902. mParentAnchorY->removeChildY(this);
  9903. // register at new parent anchor:
  9904. if (parentAnchor)
  9905. parentAnchor->addChildY(this);
  9906. mParentAnchorY = parentAnchor;
  9907. // restore pixel position under new parent:
  9908. if (keepPixelPosition)
  9909. setPixelPosition(pixelP);
  9910. else
  9911. setCoords(coords().x(), 0);
  9912. return true;
  9913. }
  9914. /*!
  9915. Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type
  9916. (\ref setType, \ref setTypeX, \ref setTypeY).
  9917. For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position
  9918. on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the
  9919. QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the
  9920. plot coordinate system defined by the axes set by \ref setAxes. By default those are the
  9921. QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available
  9922. coordinate types and their meaning.
  9923. If different types were configured for X and Y (\ref setTypeX, \ref setTypeY), \a key and \a
  9924. value must also be provided in the different coordinate systems. Here, the X type refers to \a
  9925. key, and the Y type refers to \a value.
  9926. \see setPixelPosition
  9927. */
  9928. void QCPItemPosition::setCoords(double key, double value)
  9929. {
  9930. mKey = key;
  9931. mValue = value;
  9932. }
  9933. /*! \overload
  9934. Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the
  9935. meaning of \a value of the \ref setCoords(double key, double value) method.
  9936. */
  9937. void QCPItemPosition::setCoords(const QPointF &pos)
  9938. {
  9939. setCoords(pos.x(), pos.y());
  9940. }
  9941. /*!
  9942. Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It
  9943. includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor).
  9944. \see setPixelPosition
  9945. */
  9946. QPointF QCPItemPosition::pixelPosition() const
  9947. {
  9948. QPointF result;
  9949. // determine X:
  9950. switch (mPositionTypeX)
  9951. {
  9952. case ptAbsolute:
  9953. {
  9954. result.rx() = mKey;
  9955. if (mParentAnchorX)
  9956. result.rx() += mParentAnchorX->pixelPosition().x();
  9957. break;
  9958. }
  9959. case ptViewportRatio:
  9960. {
  9961. result.rx() = mKey*mParentPlot->viewport().width();
  9962. if (mParentAnchorX)
  9963. result.rx() += mParentAnchorX->pixelPosition().x();
  9964. else
  9965. result.rx() += mParentPlot->viewport().left();
  9966. break;
  9967. }
  9968. case ptAxisRectRatio:
  9969. {
  9970. if (mAxisRect)
  9971. {
  9972. result.rx() = mKey*mAxisRect.data()->width();
  9973. if (mParentAnchorX)
  9974. result.rx() += mParentAnchorX->pixelPosition().x();
  9975. else
  9976. result.rx() += mAxisRect.data()->left();
  9977. } else
  9978. qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
  9979. break;
  9980. }
  9981. case ptPlotCoords:
  9982. {
  9983. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
  9984. result.rx() = mKeyAxis.data()->coordToPixel(mKey);
  9985. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
  9986. result.rx() = mValueAxis.data()->coordToPixel(mValue);
  9987. else
  9988. qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined";
  9989. break;
  9990. }
  9991. }
  9992. // determine Y:
  9993. switch (mPositionTypeY)
  9994. {
  9995. case ptAbsolute:
  9996. {
  9997. result.ry() = mValue;
  9998. if (mParentAnchorY)
  9999. result.ry() += mParentAnchorY->pixelPosition().y();
  10000. break;
  10001. }
  10002. case ptViewportRatio:
  10003. {
  10004. result.ry() = mValue*mParentPlot->viewport().height();
  10005. if (mParentAnchorY)
  10006. result.ry() += mParentAnchorY->pixelPosition().y();
  10007. else
  10008. result.ry() += mParentPlot->viewport().top();
  10009. break;
  10010. }
  10011. case ptAxisRectRatio:
  10012. {
  10013. if (mAxisRect)
  10014. {
  10015. result.ry() = mValue*mAxisRect.data()->height();
  10016. if (mParentAnchorY)
  10017. result.ry() += mParentAnchorY->pixelPosition().y();
  10018. else
  10019. result.ry() += mAxisRect.data()->top();
  10020. } else
  10021. qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
  10022. break;
  10023. }
  10024. case ptPlotCoords:
  10025. {
  10026. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
  10027. result.ry() = mKeyAxis.data()->coordToPixel(mKey);
  10028. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
  10029. result.ry() = mValueAxis.data()->coordToPixel(mValue);
  10030. else
  10031. qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined";
  10032. break;
  10033. }
  10034. }
  10035. return result;
  10036. }
  10037. /*!
  10038. When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the
  10039. coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and
  10040. yAxis of the QCustomPlot.
  10041. */
  10042. void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis)
  10043. {
  10044. mKeyAxis = keyAxis;
  10045. mValueAxis = valueAxis;
  10046. }
  10047. /*!
  10048. When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the
  10049. coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of
  10050. the QCustomPlot.
  10051. */
  10052. void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect)
  10053. {
  10054. mAxisRect = axisRect;
  10055. }
  10056. /*!
  10057. Sets the apparent pixel position. This works no matter what type (\ref setType) this
  10058. QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed
  10059. appropriately, to make the position finally appear at the specified pixel values.
  10060. Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is
  10061. identical to that of \ref setCoords.
  10062. \see pixelPosition, setCoords
  10063. */
  10064. void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition)
  10065. {
  10066. double x = pixelPosition.x();
  10067. double y = pixelPosition.y();
  10068. switch (mPositionTypeX)
  10069. {
  10070. case ptAbsolute:
  10071. {
  10072. if (mParentAnchorX)
  10073. x -= mParentAnchorX->pixelPosition().x();
  10074. break;
  10075. }
  10076. case ptViewportRatio:
  10077. {
  10078. if (mParentAnchorX)
  10079. x -= mParentAnchorX->pixelPosition().x();
  10080. else
  10081. x -= mParentPlot->viewport().left();
  10082. x /= (double)mParentPlot->viewport().width();
  10083. break;
  10084. }
  10085. case ptAxisRectRatio:
  10086. {
  10087. if (mAxisRect)
  10088. {
  10089. if (mParentAnchorX)
  10090. x -= mParentAnchorX->pixelPosition().x();
  10091. else
  10092. x -= mAxisRect.data()->left();
  10093. x /= (double)mAxisRect.data()->width();
  10094. } else
  10095. qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
  10096. break;
  10097. }
  10098. case ptPlotCoords:
  10099. {
  10100. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
  10101. x = mKeyAxis.data()->pixelToCoord(x);
  10102. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
  10103. y = mValueAxis.data()->pixelToCoord(x);
  10104. else
  10105. qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined";
  10106. break;
  10107. }
  10108. }
  10109. switch (mPositionTypeY)
  10110. {
  10111. case ptAbsolute:
  10112. {
  10113. if (mParentAnchorY)
  10114. y -= mParentAnchorY->pixelPosition().y();
  10115. break;
  10116. }
  10117. case ptViewportRatio:
  10118. {
  10119. if (mParentAnchorY)
  10120. y -= mParentAnchorY->pixelPosition().y();
  10121. else
  10122. y -= mParentPlot->viewport().top();
  10123. y /= (double)mParentPlot->viewport().height();
  10124. break;
  10125. }
  10126. case ptAxisRectRatio:
  10127. {
  10128. if (mAxisRect)
  10129. {
  10130. if (mParentAnchorY)
  10131. y -= mParentAnchorY->pixelPosition().y();
  10132. else
  10133. y -= mAxisRect.data()->top();
  10134. y /= (double)mAxisRect.data()->height();
  10135. } else
  10136. qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
  10137. break;
  10138. }
  10139. case ptPlotCoords:
  10140. {
  10141. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
  10142. x = mKeyAxis.data()->pixelToCoord(y);
  10143. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
  10144. y = mValueAxis.data()->pixelToCoord(y);
  10145. else
  10146. qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined";
  10147. break;
  10148. }
  10149. }
  10150. setCoords(x, y);
  10151. }
  10152. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10153. //////////////////// QCPAbstractItem
  10154. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10155. /*! \class QCPAbstractItem
  10156. \brief The abstract base class for all items in a plot.
  10157. In QCustomPlot, items are supplemental graphical elements that are neither plottables
  10158. (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus
  10159. plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each
  10160. specific item has at least one QCPItemPosition member which controls the positioning. Some items
  10161. are defined by more than one coordinate and thus have two or more QCPItemPosition members (For
  10162. example, QCPItemRect has \a topLeft and \a bottomRight).
  10163. This abstract base class defines a very basic interface like visibility and clipping. Since this
  10164. class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass
  10165. yourself to create new items.
  10166. The built-in items are:
  10167. <table>
  10168. <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>
  10169. <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>
  10170. <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>
  10171. <tr><td>QCPItemRect</td><td>A rectangle</td></tr>
  10172. <tr><td>QCPItemEllipse</td><td>An ellipse</td></tr>
  10173. <tr><td>QCPItemPixmap</td><td>An arbitrary pixmap</td></tr>
  10174. <tr><td>QCPItemText</td><td>A text label</td></tr>
  10175. <tr><td>QCPItemBracket</td><td>A bracket which may be used to reference/highlight certain parts in the plot.</td></tr>
  10176. <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>
  10177. </table>
  10178. \section items-clipping Clipping
  10179. Items are by default clipped to the main axis rect (they are only visible inside the axis rect).
  10180. To make an item visible outside that axis rect, disable clipping via \ref setClipToAxisRect
  10181. "setClipToAxisRect(false)".
  10182. On the other hand if you want the item to be clipped to a different axis rect, specify it via
  10183. \ref setClipAxisRect. This clipAxisRect property of an item is only used for clipping behaviour, and
  10184. in principle is independent of the coordinate axes the item might be tied to via its position
  10185. members (\ref QCPItemPosition::setAxes). However, it is common that the axis rect for clipping
  10186. also contains the axes used for the item positions.
  10187. \section items-using Using items
  10188. First you instantiate the item you want to use and add it to the plot:
  10189. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-1
  10190. by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just
  10191. set the plot coordinates where the line should start/end:
  10192. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-2
  10193. If we don't want the line to be positioned in plot coordinates but a different coordinate system,
  10194. e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like this:
  10195. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-3
  10196. Then we can set the coordinates, this time in pixels:
  10197. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-4
  10198. and make the line visible on the entire QCustomPlot, by disabling clipping to the axis rect:
  10199. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-5
  10200. For more advanced plots, it is even possible to set different types and parent anchors per X/Y
  10201. coordinate of an item position, using for example \ref QCPItemPosition::setTypeX or \ref
  10202. QCPItemPosition::setParentAnchorX. For details, see the documentation of \ref QCPItemPosition.
  10203. \section items-subclassing Creating own items
  10204. To create an own item, you implement a subclass of QCPAbstractItem. These are the pure
  10205. virtual functions, you must implement:
  10206. \li \ref selectTest
  10207. \li \ref draw
  10208. See the documentation of those functions for what they need to do.
  10209. \subsection items-positioning Allowing the item to be positioned
  10210. As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall
  10211. have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add
  10212. a public member of type QCPItemPosition like so:
  10213. \code QCPItemPosition * const myPosition;\endcode
  10214. the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition
  10215. instance it points to, can be modified, of course).
  10216. The initialization of this pointer is made easy with the \ref createPosition function. Just assign
  10217. the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition
  10218. takes a string which is the name of the position, typically this is identical to the variable name.
  10219. For example, the constructor of QCPItemExample could look like this:
  10220. \code
  10221. QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) :
  10222. QCPAbstractItem(parentPlot),
  10223. myPosition(createPosition("myPosition"))
  10224. {
  10225. // other constructor code
  10226. }
  10227. \endcode
  10228. \subsection items-drawing The draw function
  10229. To give your item a visual representation, reimplement the \ref draw function and use the passed
  10230. QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the
  10231. position member(s) via \ref QCPItemPosition::pixelPosition.
  10232. To optimize performance you should calculate a bounding rect first (don't forget to take the pen
  10233. width into account), check whether it intersects the \ref clipRect, and only draw the item at all
  10234. if this is the case.
  10235. \subsection items-selection The selectTest function
  10236. Your implementation of the \ref selectTest function may use the helpers \ref
  10237. QCPVector2D::distanceSquaredToLine and \ref rectDistance. With these, the implementation of the
  10238. selection test becomes significantly simpler for most items. See the documentation of \ref
  10239. selectTest for what the function parameters mean and what the function should return.
  10240. \subsection anchors Providing anchors
  10241. Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public
  10242. member, e.g.
  10243. \code QCPItemAnchor * const bottom;\endcode
  10244. and create it in the constructor with the \ref createAnchor function, assigning it a name and an
  10245. anchor id (an integer enumerating all anchors on the item, you may create an own enum for this).
  10246. Since anchors can be placed anywhere, relative to the item's position(s), your item needs to
  10247. provide the position of every anchor with the reimplementation of the \ref anchorPixelPosition(int
  10248. anchorId) function.
  10249. In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel
  10250. position when anything attached to the anchor needs to know the coordinates.
  10251. */
  10252. /* start of documentation of inline functions */
  10253. /*! \fn QList<QCPItemPosition*> QCPAbstractItem::positions() const
  10254. Returns all positions of the item in a list.
  10255. \see anchors, position
  10256. */
  10257. /*! \fn QList<QCPItemAnchor*> QCPAbstractItem::anchors() const
  10258. Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always
  10259. also an anchor, the list will also contain the positions of this item.
  10260. \see positions, anchor
  10261. */
  10262. /* end of documentation of inline functions */
  10263. /* start documentation of pure virtual functions */
  10264. /*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0
  10265. \internal
  10266. Draws this item with the provided \a painter.
  10267. The cliprect of the provided painter is set to the rect returned by \ref clipRect before this
  10268. function is called. The clipRect depends on the clipping settings defined by \ref
  10269. setClipToAxisRect and \ref setClipAxisRect.
  10270. */
  10271. /* end documentation of pure virtual functions */
  10272. /* start documentation of signals */
  10273. /*! \fn void QCPAbstractItem::selectionChanged(bool selected)
  10274. This signal is emitted when the selection state of this item has changed, either by user interaction
  10275. or by a direct call to \ref setSelected.
  10276. */
  10277. /* end documentation of signals */
  10278. /*!
  10279. Base class constructor which initializes base class members.
  10280. */
  10281. QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) :
  10282. QCPLayerable(parentPlot),
  10283. mClipToAxisRect(false),
  10284. mSelectable(true),
  10285. mSelected(false)
  10286. {
  10287. parentPlot->registerItem(this);
  10288. QList<QCPAxisRect*> rects = parentPlot->axisRects();
  10289. if (rects.size() > 0)
  10290. {
  10291. setClipToAxisRect(true);
  10292. setClipAxisRect(rects.first());
  10293. }
  10294. }
  10295. QCPAbstractItem::~QCPAbstractItem()
  10296. {
  10297. // don't delete mPositions because every position is also an anchor and thus in mAnchors
  10298. qDeleteAll(mAnchors);
  10299. }
  10300. /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
  10301. QCPAxisRect *QCPAbstractItem::clipAxisRect() const
  10302. {
  10303. return mClipAxisRect.data();
  10304. }
  10305. /*!
  10306. Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the
  10307. entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect.
  10308. \see setClipAxisRect
  10309. */
  10310. void QCPAbstractItem::setClipToAxisRect(bool clip)
  10311. {
  10312. mClipToAxisRect = clip;
  10313. if (mClipToAxisRect)
  10314. setParentLayerable(mClipAxisRect.data());
  10315. }
  10316. /*!
  10317. Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref
  10318. setClipToAxisRect is set to true.
  10319. \see setClipToAxisRect
  10320. */
  10321. void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect)
  10322. {
  10323. mClipAxisRect = rect;
  10324. if (mClipToAxisRect)
  10325. setParentLayerable(mClipAxisRect.data());
  10326. }
  10327. /*!
  10328. Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface.
  10329. (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.)
  10330. However, even when \a selectable was set to false, it is possible to set the selection manually,
  10331. by calling \ref setSelected.
  10332. \see QCustomPlot::setInteractions, setSelected
  10333. */
  10334. void QCPAbstractItem::setSelectable(bool selectable)
  10335. {
  10336. if (mSelectable != selectable)
  10337. {
  10338. mSelectable = selectable;
  10339. emit selectableChanged(mSelectable);
  10340. }
  10341. }
  10342. /*!
  10343. Sets whether this item is selected or not. When selected, it might use a different visual
  10344. appearance (e.g. pen and brush), this depends on the specific item though.
  10345. The entire selection mechanism for items is handled automatically when \ref
  10346. QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this
  10347. function when you wish to change the selection state manually.
  10348. This function can change the selection state even when \ref setSelectable was set to false.
  10349. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  10350. \see setSelectable, selectTest
  10351. */
  10352. void QCPAbstractItem::setSelected(bool selected)
  10353. {
  10354. if (mSelected != selected)
  10355. {
  10356. mSelected = selected;
  10357. emit selectionChanged(mSelected);
  10358. }
  10359. }
  10360. /*!
  10361. Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by
  10362. that name, returns 0.
  10363. This function provides an alternative way to access item positions. Normally, you access
  10364. positions direcly by their member pointers (which typically have the same variable name as \a
  10365. name).
  10366. \see positions, anchor
  10367. */
  10368. QCPItemPosition *QCPAbstractItem::position(const QString &name) const
  10369. {
  10370. for (int i=0; i<mPositions.size(); ++i)
  10371. {
  10372. if (mPositions.at(i)->name() == name)
  10373. return mPositions.at(i);
  10374. }
  10375. qDebug() << Q_FUNC_INFO << "position with name not found:" << name;
  10376. return 0;
  10377. }
  10378. /*!
  10379. Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by
  10380. that name, returns 0.
  10381. This function provides an alternative way to access item anchors. Normally, you access
  10382. anchors direcly by their member pointers (which typically have the same variable name as \a
  10383. name).
  10384. \see anchors, position
  10385. */
  10386. QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const
  10387. {
  10388. for (int i=0; i<mAnchors.size(); ++i)
  10389. {
  10390. if (mAnchors.at(i)->name() == name)
  10391. return mAnchors.at(i);
  10392. }
  10393. qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name;
  10394. return 0;
  10395. }
  10396. /*!
  10397. Returns whether this item has an anchor with the specified \a name.
  10398. Note that you can check for positions with this function, too. This is because every position is
  10399. also an anchor (QCPItemPosition inherits from QCPItemAnchor).
  10400. \see anchor, position
  10401. */
  10402. bool QCPAbstractItem::hasAnchor(const QString &name) const
  10403. {
  10404. for (int i=0; i<mAnchors.size(); ++i)
  10405. {
  10406. if (mAnchors.at(i)->name() == name)
  10407. return true;
  10408. }
  10409. return false;
  10410. }
  10411. /*! \internal
  10412. Returns the rect the visual representation of this item is clipped to. This depends on the
  10413. current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect.
  10414. If the item is not clipped to an axis rect, QCustomPlot's viewport rect is returned.
  10415. \see draw
  10416. */
  10417. QRect QCPAbstractItem::clipRect() const
  10418. {
  10419. if (mClipToAxisRect && mClipAxisRect)
  10420. return mClipAxisRect.data()->rect();
  10421. else
  10422. return mParentPlot->viewport();
  10423. }
  10424. /*! \internal
  10425. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  10426. before drawing item lines.
  10427. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  10428. This function takes into account the local setting of the antialiasing flag as well as the
  10429. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  10430. QCustomPlot::setNotAntialiasedElements.
  10431. \see setAntialiased
  10432. */
  10433. void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
  10434. {
  10435. applyAntialiasingHint(painter, mAntialiased, QCP::aeItems);
  10436. }
  10437. /*! \internal
  10438. A convenience function which returns the selectTest value for a specified \a rect and a specified
  10439. click position \a pos. \a filledRect defines whether a click inside the rect should also be
  10440. considered a hit or whether only the rect border is sensitive to hits.
  10441. This function may be used to help with the implementation of the \ref selectTest function for
  10442. specific items.
  10443. For example, if your item consists of four rects, call this function four times, once for each
  10444. rect, in your \ref selectTest reimplementation. Finally, return the minimum (non -1) of all four
  10445. returned values.
  10446. */
  10447. double QCPAbstractItem::rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const
  10448. {
  10449. double result = -1;
  10450. // distance to border:
  10451. QList<QLineF> lines;
  10452. lines << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight())
  10453. << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight());
  10454. double minDistSqr = std::numeric_limits<double>::max();
  10455. for (int i=0; i<lines.size(); ++i)
  10456. {
  10457. double distSqr = QCPVector2D(pos).distanceSquaredToLine(lines.at(i).p1(), lines.at(i).p2());
  10458. if (distSqr < minDistSqr)
  10459. minDistSqr = distSqr;
  10460. }
  10461. result = qSqrt(minDistSqr);
  10462. // filled rect, allow click inside to count as hit:
  10463. if (filledRect && result > mParentPlot->selectionTolerance()*0.99)
  10464. {
  10465. if (rect.contains(pos))
  10466. result = mParentPlot->selectionTolerance()*0.99;
  10467. }
  10468. return result;
  10469. }
  10470. /*! \internal
  10471. Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in
  10472. item subclasses if they want to provide anchors (QCPItemAnchor).
  10473. For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor
  10474. ids and returns the respective pixel points of the specified anchor.
  10475. \see createAnchor
  10476. */
  10477. QPointF QCPAbstractItem::anchorPixelPosition(int anchorId) const
  10478. {
  10479. qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId;
  10480. return QPointF();
  10481. }
  10482. /*! \internal
  10483. Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified
  10484. \a name must be a unique string that is usually identical to the variable name of the position
  10485. member (This is needed to provide the name-based \ref position access to positions).
  10486. Don't delete positions created by this function manually, as the item will take care of it.
  10487. Use this function in the constructor (initialization list) of the specific item subclass to
  10488. create each position member. Don't create QCPItemPositions with \b new yourself, because they
  10489. won't be registered with the item properly.
  10490. \see createAnchor
  10491. */
  10492. QCPItemPosition *QCPAbstractItem::createPosition(const QString &name)
  10493. {
  10494. if (hasAnchor(name))
  10495. qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
  10496. QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name);
  10497. mPositions.append(newPosition);
  10498. mAnchors.append(newPosition); // every position is also an anchor
  10499. newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis);
  10500. newPosition->setType(QCPItemPosition::ptPlotCoords);
  10501. if (mParentPlot->axisRect())
  10502. newPosition->setAxisRect(mParentPlot->axisRect());
  10503. newPosition->setCoords(0, 0);
  10504. return newPosition;
  10505. }
  10506. /*! \internal
  10507. Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified
  10508. \a name must be a unique string that is usually identical to the variable name of the anchor
  10509. member (This is needed to provide the name based \ref anchor access to anchors).
  10510. The \a anchorId must be a number identifying the created anchor. It is recommended to create an
  10511. enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor
  10512. to identify itself when it calls QCPAbstractItem::anchorPixelPosition. That function then returns
  10513. the correct pixel coordinates for the passed anchor id.
  10514. Don't delete anchors created by this function manually, as the item will take care of it.
  10515. Use this function in the constructor (initialization list) of the specific item subclass to
  10516. create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they
  10517. won't be registered with the item properly.
  10518. \see createPosition
  10519. */
  10520. QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId)
  10521. {
  10522. if (hasAnchor(name))
  10523. qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
  10524. QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId);
  10525. mAnchors.append(newAnchor);
  10526. return newAnchor;
  10527. }
  10528. /* inherits documentation from base class */
  10529. void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  10530. {
  10531. Q_UNUSED(event)
  10532. Q_UNUSED(details)
  10533. if (mSelectable)
  10534. {
  10535. bool selBefore = mSelected;
  10536. setSelected(additive ? !mSelected : true);
  10537. if (selectionStateChanged)
  10538. *selectionStateChanged = mSelected != selBefore;
  10539. }
  10540. }
  10541. /* inherits documentation from base class */
  10542. void QCPAbstractItem::deselectEvent(bool *selectionStateChanged)
  10543. {
  10544. if (mSelectable)
  10545. {
  10546. bool selBefore = mSelected;
  10547. setSelected(false);
  10548. if (selectionStateChanged)
  10549. *selectionStateChanged = mSelected != selBefore;
  10550. }
  10551. }
  10552. /* inherits documentation from base class */
  10553. QCP::Interaction QCPAbstractItem::selectionCategory() const
  10554. {
  10555. return QCP::iSelectItems;
  10556. }
  10557. /* end of 'src/item.cpp' */
  10558. /* including file 'src/core.cpp', size 125037 */
  10559. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  10560. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10561. //////////////////// QCustomPlot
  10562. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10563. /*! \class QCustomPlot
  10564. \brief The central class of the library. This is the QWidget which displays the plot and
  10565. interacts with the user.
  10566. For tutorials on how to use QCustomPlot, see the website\n
  10567. http://www.qcustomplot.com/
  10568. */
  10569. /* start of documentation of inline functions */
  10570. /*! \fn QCPSelectionRect *QCustomPlot::selectionRect() const
  10571. Allows access to the currently used QCPSelectionRect instance (or subclass thereof), that is used
  10572. to handle and draw selection rect interactions (see \ref setSelectionRectMode).
  10573. \see setSelectionRect
  10574. */
  10575. /*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const
  10576. Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just
  10577. one cell with the main QCPAxisRect inside.
  10578. */
  10579. /* end of documentation of inline functions */
  10580. /* start of documentation of signals */
  10581. /*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event)
  10582. This signal is emitted when the QCustomPlot receives a mouse double click event.
  10583. */
  10584. /*! \fn void QCustomPlot::mousePress(QMouseEvent *event)
  10585. This signal is emitted when the QCustomPlot receives a mouse press event.
  10586. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
  10587. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
  10588. QCPAxisRect::setRangeDragAxes.
  10589. */
  10590. /*! \fn void QCustomPlot::mouseMove(QMouseEvent *event)
  10591. This signal is emitted when the QCustomPlot receives a mouse move event.
  10592. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
  10593. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
  10594. QCPAxisRect::setRangeDragAxes.
  10595. \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here,
  10596. because the dragging starting point was saved the moment the mouse was pressed. Thus it only has
  10597. a meaning for the range drag axes that were set at that moment. If you want to change the drag
  10598. axes, consider doing this in the \ref mousePress signal instead.
  10599. */
  10600. /*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event)
  10601. This signal is emitted when the QCustomPlot receives a mouse release event.
  10602. It is emitted before QCustomPlot handles any other mechanisms like object selection. So a
  10603. slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or
  10604. \ref QCPAbstractPlottable::setSelectable.
  10605. */
  10606. /*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event)
  10607. This signal is emitted when the QCustomPlot receives a mouse wheel event.
  10608. It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot
  10609. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref
  10610. QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor.
  10611. */
  10612. /*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event)
  10613. This signal is emitted when a plottable is clicked.
  10614. \a event is the mouse event that caused the click and \a plottable is the plottable that received
  10615. the click. The parameter \a dataIndex indicates the data point that was closest to the click
  10616. position.
  10617. \see plottableDoubleClick
  10618. */
  10619. /*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event)
  10620. This signal is emitted when a plottable is double clicked.
  10621. \a event is the mouse event that caused the click and \a plottable is the plottable that received
  10622. the click. The parameter \a dataIndex indicates the data point that was closest to the click
  10623. position.
  10624. \see plottableClick
  10625. */
  10626. /*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event)
  10627. This signal is emitted when an item is clicked.
  10628. \a event is the mouse event that caused the click and \a item is the item that received the
  10629. click.
  10630. \see itemDoubleClick
  10631. */
  10632. /*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event)
  10633. This signal is emitted when an item is double clicked.
  10634. \a event is the mouse event that caused the click and \a item is the item that received the
  10635. click.
  10636. \see itemClick
  10637. */
  10638. /*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
  10639. This signal is emitted when an axis is clicked.
  10640. \a event is the mouse event that caused the click, \a axis is the axis that received the click and
  10641. \a part indicates the part of the axis that was clicked.
  10642. \see axisDoubleClick
  10643. */
  10644. /*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
  10645. This signal is emitted when an axis is double clicked.
  10646. \a event is the mouse event that caused the click, \a axis is the axis that received the click and
  10647. \a part indicates the part of the axis that was clicked.
  10648. \see axisClick
  10649. */
  10650. /*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
  10651. This signal is emitted when a legend (item) is clicked.
  10652. \a event is the mouse event that caused the click, \a legend is the legend that received the
  10653. click and \a item is the legend item that received the click. If only the legend and no item is
  10654. clicked, \a item is 0. This happens for a click inside the legend padding or the space between
  10655. two items.
  10656. \see legendDoubleClick
  10657. */
  10658. /*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
  10659. This signal is emitted when a legend (item) is double clicked.
  10660. \a event is the mouse event that caused the click, \a legend is the legend that received the
  10661. click and \a item is the legend item that received the click. If only the legend and no item is
  10662. clicked, \a item is 0. This happens for a click inside the legend padding or the space between
  10663. two items.
  10664. \see legendClick
  10665. */
  10666. /*! \fn void QCustomPlot::selectionChangedByUser()
  10667. This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by
  10668. clicking. It is not emitted when the selection state of an object has changed programmatically by
  10669. a direct call to <tt>setSelected()</tt>/<tt>setSelection()</tt> on an object or by calling \ref
  10670. deselectAll.
  10671. In addition to this signal, selectable objects also provide individual signals, for example \ref
  10672. QCPAxis::selectionChanged or \ref QCPAbstractPlottable::selectionChanged. Note that those signals
  10673. are emitted even if the selection state is changed programmatically.
  10674. See the documentation of \ref setInteractions for details about the selection mechanism.
  10675. \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends
  10676. */
  10677. /*! \fn void QCustomPlot::beforeReplot()
  10678. This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref
  10679. replot).
  10680. It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
  10681. replot synchronously, it won't cause an infinite recursion.
  10682. \see replot, afterReplot
  10683. */
  10684. /*! \fn void QCustomPlot::afterReplot()
  10685. This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref
  10686. replot).
  10687. It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
  10688. replot synchronously, it won't cause an infinite recursion.
  10689. \see replot, beforeReplot
  10690. */
  10691. /* end of documentation of signals */
  10692. /* start of documentation of public members */
  10693. /*! \var QCPAxis *QCustomPlot::xAxis
  10694. A pointer to the primary x Axis (bottom) of the main axis rect of the plot.
  10695. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  10696. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  10697. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  10698. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  10699. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  10700. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  10701. axis rect), the corresponding pointers become 0.
  10702. If an axis convenience pointer is currently zero and a new axis rect or a corresponding axis is
  10703. added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the
  10704. according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is
  10705. added after the main legend was removed before.
  10706. */
  10707. /*! \var QCPAxis *QCustomPlot::yAxis
  10708. A pointer to the primary y Axis (left) of the main axis rect of the plot.
  10709. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  10710. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  10711. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  10712. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  10713. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  10714. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  10715. axis rect), the corresponding pointers become 0.
  10716. If an axis convenience pointer is currently zero and a new axis rect or a corresponding axis is
  10717. added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the
  10718. according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is
  10719. added after the main legend was removed before.
  10720. */
  10721. /*! \var QCPAxis *QCustomPlot::xAxis2
  10722. A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are
  10723. invisible by default. Use QCPAxis::setVisible to change this (or use \ref
  10724. QCPAxisRect::setupFullAxesBox).
  10725. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  10726. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  10727. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  10728. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  10729. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  10730. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  10731. axis rect), the corresponding pointers become 0.
  10732. If an axis convenience pointer is currently zero and a new axis rect or a corresponding axis is
  10733. added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the
  10734. according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is
  10735. added after the main legend was removed before.
  10736. */
  10737. /*! \var QCPAxis *QCustomPlot::yAxis2
  10738. A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are
  10739. invisible by default. Use QCPAxis::setVisible to change this (or use \ref
  10740. QCPAxisRect::setupFullAxesBox).
  10741. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  10742. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  10743. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  10744. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  10745. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  10746. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  10747. axis rect), the corresponding pointers become 0.
  10748. If an axis convenience pointer is currently zero and a new axis rect or a corresponding axis is
  10749. added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the
  10750. according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is
  10751. added after the main legend was removed before.
  10752. */
  10753. /*! \var QCPLegend *QCustomPlot::legend
  10754. A pointer to the default legend of the main axis rect. The legend is invisible by default. Use
  10755. QCPLegend::setVisible to change this.
  10756. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  10757. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  10758. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  10759. layout system\endlink to add multiple legends to the plot, use the layout system interface to
  10760. access the new legend. For example, legends can be placed inside an axis rect's \ref
  10761. QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If
  10762. the default legend is removed due to manipulation of the layout system (e.g. by removing the main
  10763. axis rect), the corresponding pointer becomes 0.
  10764. If an axis convenience pointer is currently zero and a new axis rect or a corresponding axis is
  10765. added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the
  10766. according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is
  10767. added after the main legend was removed before.
  10768. */
  10769. /* end of documentation of public members */
  10770. /*!
  10771. Constructs a QCustomPlot and sets reasonable default values.
  10772. */
  10773. QCustomPlot::QCustomPlot(QWidget *parent) :
  10774. QWidget(parent),
  10775. xAxis(0),
  10776. yAxis(0),
  10777. xAxis2(0),
  10778. yAxis2(0),
  10779. legend(0),
  10780. mBufferDevicePixelRatio(1.0), // will be adapted to primary screen below
  10781. mPlotLayout(0),
  10782. mAutoAddPlottableToLegend(true),
  10783. mAntialiasedElements(QCP::aeNone),
  10784. mNotAntialiasedElements(QCP::aeNone),
  10785. mInteractions(0),
  10786. mSelectionTolerance(8),
  10787. mNoAntialiasingOnDrag(false),
  10788. mBackgroundBrush(Qt::white, Qt::SolidPattern),
  10789. mBackgroundScaled(true),
  10790. mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
  10791. mCurrentLayer(0),
  10792. mPlottingHints(QCP::phCacheLabels|QCP::phImmediateRefresh),
  10793. mMultiSelectModifier(Qt::ControlModifier),
  10794. mSelectionRectMode(QCP::srmNone),
  10795. mSelectionRect(0),
  10796. mOpenGl(false),
  10797. mMouseHasMoved(false),
  10798. mMouseEventLayerable(0),
  10799. mMouseSignalLayerable(0),
  10800. mReplotting(false),
  10801. mReplotQueued(false),
  10802. mOpenGlMultisamples(16),
  10803. mOpenGlAntialiasedElementsBackup(QCP::aeNone),
  10804. mOpenGlCacheLabelsBackup(true)
  10805. {
  10806. setAttribute(Qt::WA_NoMousePropagation);
  10807. setAttribute(Qt::WA_OpaquePaintEvent);
  10808. setFocusPolicy(Qt::ClickFocus);
  10809. setMouseTracking(true);
  10810. QLocale currentLocale = locale();
  10811. currentLocale.setNumberOptions(QLocale::OmitGroupSeparator);
  10812. setLocale(currentLocale);
  10813. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  10814. # ifdef QCP_DEVICEPIXELRATIO_FLOAT
  10815. setBufferDevicePixelRatio(QWidget::devicePixelRatioF());
  10816. # else
  10817. setBufferDevicePixelRatio(QWidget::devicePixelRatio());
  10818. # endif
  10819. #endif
  10820. mOpenGlAntialiasedElementsBackup = mAntialiasedElements;
  10821. mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels);
  10822. // create initial layers:
  10823. mLayers.append(new QCPLayer(this, QLatin1String("background")));
  10824. mLayers.append(new QCPLayer(this, QLatin1String("grid")));
  10825. mLayers.append(new QCPLayer(this, QLatin1String("main")));
  10826. mLayers.append(new QCPLayer(this, QLatin1String("axes")));
  10827. mLayers.append(new QCPLayer(this, QLatin1String("legend")));
  10828. mLayers.append(new QCPLayer(this, QLatin1String("overlay")));
  10829. updateLayerIndices();
  10830. setCurrentLayer(QLatin1String("main"));
  10831. layer(QLatin1String("overlay"))->setMode(QCPLayer::lmBuffered);
  10832. // create initial layout, axis rect and legend:
  10833. mPlotLayout = new QCPLayoutGrid;
  10834. mPlotLayout->initializeParentPlot(this);
  10835. mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry
  10836. mPlotLayout->setLayer(QLatin1String("main"));
  10837. QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true);
  10838. mPlotLayout->addElement(0, 0, defaultAxisRect);
  10839. xAxis = defaultAxisRect->axis(QCPAxis::atBottom);
  10840. yAxis = defaultAxisRect->axis(QCPAxis::atLeft);
  10841. xAxis2 = defaultAxisRect->axis(QCPAxis::atTop);
  10842. yAxis2 = defaultAxisRect->axis(QCPAxis::atRight);
  10843. legend = new QCPLegend;
  10844. legend->setVisible(false);
  10845. defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop);
  10846. defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12));
  10847. defaultAxisRect->setLayer(QLatin1String("background"));
  10848. xAxis->setLayer(QLatin1String("axes"));
  10849. yAxis->setLayer(QLatin1String("axes"));
  10850. xAxis2->setLayer(QLatin1String("axes"));
  10851. yAxis2->setLayer(QLatin1String("axes"));
  10852. xAxis->grid()->setLayer(QLatin1String("grid"));
  10853. yAxis->grid()->setLayer(QLatin1String("grid"));
  10854. xAxis2->grid()->setLayer(QLatin1String("grid"));
  10855. yAxis2->grid()->setLayer(QLatin1String("grid"));
  10856. legend->setLayer(QLatin1String("legend"));
  10857. // create selection rect instance:
  10858. mSelectionRect = new QCPSelectionRect(this);
  10859. mSelectionRect->setLayer(QLatin1String("overlay"));
  10860. setViewport(rect()); // needs to be called after mPlotLayout has been created
  10861. replot(rpQueuedReplot);
  10862. }
  10863. QCustomPlot::~QCustomPlot()
  10864. {
  10865. clearPlottables();
  10866. clearItems();
  10867. if (mPlotLayout)
  10868. {
  10869. delete mPlotLayout;
  10870. mPlotLayout = 0;
  10871. }
  10872. mCurrentLayer = 0;
  10873. qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed
  10874. mLayers.clear();
  10875. }
  10876. /*!
  10877. Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement.
  10878. This overrides the antialiasing settings for whole element groups, normally controlled with the
  10879. \a setAntialiasing function on the individual elements. If an element is neither specified in
  10880. \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
  10881. each individual element instance is used.
  10882. For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be
  10883. drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
  10884. to.
  10885. if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is
  10886. removed from there.
  10887. \see setNotAntialiasedElements
  10888. */
  10889. void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements)
  10890. {
  10891. mAntialiasedElements = antialiasedElements;
  10892. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  10893. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  10894. mNotAntialiasedElements |= ~mAntialiasedElements;
  10895. }
  10896. /*!
  10897. Sets whether the specified \a antialiasedElement is forcibly drawn antialiased.
  10898. See \ref setAntialiasedElements for details.
  10899. \see setNotAntialiasedElement
  10900. */
  10901. void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled)
  10902. {
  10903. if (!enabled && mAntialiasedElements.testFlag(antialiasedElement))
  10904. mAntialiasedElements &= ~antialiasedElement;
  10905. else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement))
  10906. mAntialiasedElements |= antialiasedElement;
  10907. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  10908. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  10909. mNotAntialiasedElements |= ~mAntialiasedElements;
  10910. }
  10911. /*!
  10912. Sets which elements are forcibly drawn not antialiased as an \a or combination of
  10913. QCP::AntialiasedElement.
  10914. This overrides the antialiasing settings for whole element groups, normally controlled with the
  10915. \a setAntialiasing function on the individual elements. If an element is neither specified in
  10916. \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
  10917. each individual element instance is used.
  10918. For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be
  10919. drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
  10920. to.
  10921. if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is
  10922. removed from there.
  10923. \see setAntialiasedElements
  10924. */
  10925. void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements &notAntialiasedElements)
  10926. {
  10927. mNotAntialiasedElements = notAntialiasedElements;
  10928. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  10929. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  10930. mAntialiasedElements |= ~mNotAntialiasedElements;
  10931. }
  10932. /*!
  10933. Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased.
  10934. See \ref setNotAntialiasedElements for details.
  10935. \see setAntialiasedElement
  10936. */
  10937. void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled)
  10938. {
  10939. if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement))
  10940. mNotAntialiasedElements &= ~notAntialiasedElement;
  10941. else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement))
  10942. mNotAntialiasedElements |= notAntialiasedElement;
  10943. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  10944. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  10945. mAntialiasedElements |= ~mNotAntialiasedElements;
  10946. }
  10947. /*!
  10948. If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the
  10949. plottable to the legend (QCustomPlot::legend).
  10950. \see addGraph, QCPLegend::addItem
  10951. */
  10952. void QCustomPlot::setAutoAddPlottableToLegend(bool on)
  10953. {
  10954. mAutoAddPlottableToLegend = on;
  10955. }
  10956. /*!
  10957. Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction
  10958. enums. There are the following types of interactions:
  10959. <b>Axis range manipulation</b> is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the
  10960. respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel.
  10961. For details how to control which axes the user may drag/zoom and in what orientations, see \ref
  10962. QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes,
  10963. \ref QCPAxisRect::setRangeZoomAxes.
  10964. <b>Plottable data selection</b> is controlled by \ref QCP::iSelectPlottables. If \ref
  10965. QCP::iSelectPlottables is set, the user may select plottables (graphs, curves, bars,...) and
  10966. their data by clicking on them or in their vicinity (\ref setSelectionTolerance). Whether the
  10967. user can actually select a plottable and its data can further be restricted with the \ref
  10968. QCPAbstractPlottable::setSelectable method on the specific plottable. For details, see the
  10969. special page about the \ref dataselection "data selection mechanism". To retrieve a list of all
  10970. currently selected plottables, call \ref selectedPlottables. If you're only interested in
  10971. QCPGraphs, you may use the convenience function \ref selectedGraphs.
  10972. <b>Item selection</b> is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user
  10973. may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find
  10974. out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of
  10975. all currently selected items, call \ref selectedItems.
  10976. <b>Axis selection</b> is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user
  10977. may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick
  10978. labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for
  10979. each axis. To retrieve a list of all axes that currently contain selected parts, call \ref
  10980. selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts().
  10981. <b>Legend selection</b> is controlled with \ref QCP::iSelectLegend. If this is set, the user may
  10982. select the legend itself or individual items by clicking on them. What parts exactly are
  10983. selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the
  10984. legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To
  10985. find out which child items are selected, call \ref QCPLegend::selectedItems.
  10986. <b>All other selectable elements</b> The selection of all other selectable objects (e.g.
  10987. QCPTextElement, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the
  10988. user may select those objects by clicking on them. To find out which are currently selected, you
  10989. need to check their selected state explicitly.
  10990. If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is
  10991. emitted. Each selectable object additionally emits an individual selectionChanged signal whenever
  10992. their selection state has changed, i.e. not only by user interaction.
  10993. To allow multiple objects to be selected by holding the selection modifier (\ref
  10994. setMultiSelectModifier), set the flag \ref QCP::iMultiSelect.
  10995. \note In addition to the selection mechanism presented here, QCustomPlot always emits
  10996. corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and
  10997. \ref plottableDoubleClick for example.
  10998. \see setInteraction, setSelectionTolerance
  10999. */
  11000. void QCustomPlot::setInteractions(const QCP::Interactions &interactions)
  11001. {
  11002. mInteractions = interactions;
  11003. }
  11004. /*!
  11005. Sets the single \a interaction of this QCustomPlot to \a enabled.
  11006. For details about the interaction system, see \ref setInteractions.
  11007. \see setInteractions
  11008. */
  11009. void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled)
  11010. {
  11011. if (!enabled && mInteractions.testFlag(interaction))
  11012. mInteractions &= ~interaction;
  11013. else if (enabled && !mInteractions.testFlag(interaction))
  11014. mInteractions |= interaction;
  11015. }
  11016. /*!
  11017. Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or
  11018. not.
  11019. If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a
  11020. potential selection when the minimum distance between the click position and the graph line is
  11021. smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks
  11022. directly inside the area and ignore this selection tolerance. In other words, it only has meaning
  11023. for parts of objects that are too thin to exactly hit with a click and thus need such a
  11024. tolerance.
  11025. \see setInteractions, QCPLayerable::selectTest
  11026. */
  11027. void QCustomPlot::setSelectionTolerance(int pixels)
  11028. {
  11029. mSelectionTolerance = pixels;
  11030. }
  11031. /*!
  11032. Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes
  11033. ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves
  11034. performance during dragging. Thus it creates a more responsive user experience. As soon as the
  11035. user stops dragging, the last replot is done with normal antialiasing, to restore high image
  11036. quality.
  11037. \see setAntialiasedElements, setNotAntialiasedElements
  11038. */
  11039. void QCustomPlot::setNoAntialiasingOnDrag(bool enabled)
  11040. {
  11041. mNoAntialiasingOnDrag = enabled;
  11042. }
  11043. /*!
  11044. Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint.
  11045. \see setPlottingHint
  11046. */
  11047. void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints)
  11048. {
  11049. mPlottingHints = hints;
  11050. }
  11051. /*!
  11052. Sets the specified plotting \a hint to \a enabled.
  11053. \see setPlottingHints
  11054. */
  11055. void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled)
  11056. {
  11057. QCP::PlottingHints newHints = mPlottingHints;
  11058. if (!enabled)
  11059. newHints &= ~hint;
  11060. else
  11061. newHints |= hint;
  11062. if (newHints != mPlottingHints)
  11063. setPlottingHints(newHints);
  11064. }
  11065. /*!
  11066. Sets the keyboard modifier that will be recognized as multi-select-modifier.
  11067. If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple
  11068. objects (or data points) by clicking on them one after the other while holding down \a modifier.
  11069. By default the multi-select-modifier is set to Qt::ControlModifier.
  11070. \see setInteractions
  11071. */
  11072. void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier)
  11073. {
  11074. mMultiSelectModifier = modifier;
  11075. }
  11076. /*!
  11077. Sets how QCustomPlot processes mouse click-and-drag interactions by the user.
  11078. If \a mode is \ref QCP::srmNone, the mouse drag is forwarded to the underlying objects. For
  11079. example, QCPAxisRect may process a mouse drag by dragging axis ranges, see \ref
  11080. QCPAxisRect::setRangeDrag. If \a mode is not \ref QCP::srmNone, the current selection rect (\ref
  11081. selectionRect) becomes activated and allows e.g. rect zooming and data point selection.
  11082. If you wish to provide your user both with axis range dragging and data selection/range zooming,
  11083. use this method to switch between the modes just before the interaction is processed, e.g. in
  11084. reaction to the \ref mousePress or \ref mouseMove signals. For example you could check whether
  11085. the user is holding a certain keyboard modifier, and then decide which \a mode shall be set.
  11086. If a selection rect interaction is currently active, and \a mode is set to \ref QCP::srmNone, the
  11087. interaction is canceled (\ref QCPSelectionRect::cancel). Switching between any of the other modes
  11088. will keep the selection rect active. Upon completion of the interaction, the behaviour is as
  11089. defined by the currently set \a mode, not the mode that was set when the interaction started.
  11090. \see setInteractions, setSelectionRect, QCPSelectionRect
  11091. */
  11092. void QCustomPlot::setSelectionRectMode(QCP::SelectionRectMode mode)
  11093. {
  11094. if (mSelectionRect)
  11095. {
  11096. if (mode == QCP::srmNone)
  11097. mSelectionRect->cancel(); // when switching to none, we immediately want to abort a potentially active selection rect
  11098. // disconnect old connections:
  11099. if (mSelectionRectMode == QCP::srmSelect)
  11100. disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
  11101. else if (mSelectionRectMode == QCP::srmZoom)
  11102. disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
  11103. // establish new ones:
  11104. if (mode == QCP::srmSelect)
  11105. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
  11106. else if (mode == QCP::srmZoom)
  11107. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
  11108. }
  11109. mSelectionRectMode = mode;
  11110. }
  11111. /*!
  11112. Sets the \ref QCPSelectionRect instance that QCustomPlot will use if \a mode is not \ref
  11113. QCP::srmNone and the user performs a click-and-drag interaction. QCustomPlot takes ownership of
  11114. the passed \a selectionRect. It can be accessed later via \ref selectionRect.
  11115. This method is useful if you wish to replace the default QCPSelectionRect instance with an
  11116. instance of a QCPSelectionRect subclass, to introduce custom behaviour of the selection rect.
  11117. \see setSelectionRectMode
  11118. */
  11119. void QCustomPlot::setSelectionRect(QCPSelectionRect *selectionRect)
  11120. {
  11121. if (mSelectionRect)
  11122. delete mSelectionRect;
  11123. mSelectionRect = selectionRect;
  11124. if (mSelectionRect)
  11125. {
  11126. // establish connections with new selection rect:
  11127. if (mSelectionRectMode == QCP::srmSelect)
  11128. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
  11129. else if (mSelectionRectMode == QCP::srmZoom)
  11130. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
  11131. }
  11132. }
  11133. /*!
  11134. \warning This is still an experimental feature and its performance depends on the system that it
  11135. runs on. Having multiple QCustomPlot widgets in one application with enabled OpenGL rendering
  11136. might cause context conflicts on some systems.
  11137. This method allows to enable OpenGL plot rendering, for increased plotting performance of
  11138. graphically demanding plots (thick lines, translucent fills, etc.).
  11139. If \a enabled is set to true, QCustomPlot will try to initialize OpenGL and, if successful,
  11140. continue plotting with hardware acceleration. The parameter \a multisampling controls how many
  11141. samples will be used per pixel, it essentially controls the antialiasing quality. If \a
  11142. multisampling is set too high for the current graphics hardware, the maximum allowed value will
  11143. be used.
  11144. You can test whether switching to OpenGL rendering was successful by checking whether the
  11145. according getter \a QCustomPlot::openGl() returns true. If the OpenGL initialization fails,
  11146. rendering continues with the regular software rasterizer, and an according qDebug output is
  11147. generated.
  11148. If switching to OpenGL was successful, this method disables label caching (\ref setPlottingHint
  11149. "setPlottingHint(QCP::phCacheLabels, false)") and turns on QCustomPlot's antialiasing override
  11150. for all elements (\ref setAntialiasedElements "setAntialiasedElements(QCP::aeAll)"), leading to a
  11151. higher quality output. The antialiasing override allows for pixel-grid aligned drawing in the
  11152. OpenGL paint device. As stated before, in OpenGL rendering the actual antialiasing of the plot is
  11153. controlled with \a multisampling. If \a enabled is set to false, the antialiasing/label caching
  11154. settings are restored to what they were before OpenGL was enabled, if they weren't altered in the
  11155. meantime.
  11156. \note OpenGL support is only enabled if QCustomPlot is compiled with the macro \c QCUSTOMPLOT_USE_OPENGL
  11157. defined. This define must be set before including the QCustomPlot header both during compilation
  11158. of the QCustomPlot library as well as when compiling your application. It is best to just include
  11159. the line <tt>DEFINES += QCUSTOMPLOT_USE_OPENGL</tt> in the respective qmake project files.
  11160. \note If you are using a Qt version before 5.0, you must also add the module "opengl" to your \c
  11161. QT variable in the qmake project files. For Qt versions 5.0 and higher, QCustomPlot switches to a
  11162. newer OpenGL interface which is already in the "gui" module.
  11163. */
  11164. void QCustomPlot::setOpenGl(bool enabled, int multisampling)
  11165. {
  11166. mOpenGlMultisamples = qMax(0, multisampling);
  11167. #ifdef QCUSTOMPLOT_USE_OPENGL
  11168. mOpenGl = enabled;
  11169. if (mOpenGl)
  11170. {
  11171. if (setupOpenGl())
  11172. {
  11173. // backup antialiasing override and labelcaching setting so we can restore upon disabling OpenGL
  11174. mOpenGlAntialiasedElementsBackup = mAntialiasedElements;
  11175. mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels);
  11176. // set antialiasing override to antialias all (aligns gl pixel grid properly), and disable label caching (would use software rasterizer for pixmap caches):
  11177. setAntialiasedElements(QCP::aeAll);
  11178. setPlottingHint(QCP::phCacheLabels, false);
  11179. } else
  11180. {
  11181. qDebug() << Q_FUNC_INFO << "Failed to enable OpenGL, continuing plotting without hardware acceleration.";
  11182. mOpenGl = false;
  11183. }
  11184. } else
  11185. {
  11186. // restore antialiasing override and labelcaching to what it was before enabling OpenGL, if nobody changed it in the meantime:
  11187. if (mAntialiasedElements == QCP::aeAll)
  11188. setAntialiasedElements(mOpenGlAntialiasedElementsBackup);
  11189. if (!mPlottingHints.testFlag(QCP::phCacheLabels))
  11190. setPlottingHint(QCP::phCacheLabels, mOpenGlCacheLabelsBackup);
  11191. freeOpenGl();
  11192. }
  11193. // recreate all paint buffers:
  11194. mPaintBuffers.clear();
  11195. setupPaintBuffers();
  11196. #else
  11197. Q_UNUSED(enabled)
  11198. 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)";
  11199. #endif
  11200. }
  11201. /*!
  11202. Sets the viewport of this QCustomPlot. Usually users of QCustomPlot don't need to change the
  11203. viewport manually.
  11204. The viewport is the area in which the plot is drawn. All mechanisms, e.g. margin caluclation take
  11205. the viewport to be the outer border of the plot. The viewport normally is the rect() of the
  11206. QCustomPlot widget, i.e. a rect with top left (0, 0) and size of the QCustomPlot widget.
  11207. Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically
  11208. an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger
  11209. and contains also the axes themselves, their tick numbers, their labels, or even additional axis
  11210. rects, color scales and other layout elements.
  11211. This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref
  11212. savePdf, etc. by temporarily changing the viewport size.
  11213. */
  11214. void QCustomPlot::setViewport(const QRect &rect)
  11215. {
  11216. mViewport = rect;
  11217. if (mPlotLayout)
  11218. mPlotLayout->setOuterRect(mViewport);
  11219. }
  11220. /*!
  11221. Sets the device pixel ratio used by the paint buffers of this QCustomPlot instance.
  11222. Normally, this doesn't need to be set manually, because it is initialized with the regular \a
  11223. QWidget::devicePixelRatio which is configured by Qt to fit the display device (e.g. 1 for normal
  11224. displays, 2 for High-DPI displays).
  11225. Device pixel ratios are supported by Qt only for Qt versions since 5.4. If this method is called
  11226. when QCustomPlot is being used with older Qt versions, outputs an according qDebug message and
  11227. leaves the internal buffer device pixel ratio at 1.0.
  11228. */
  11229. void QCustomPlot::setBufferDevicePixelRatio(double ratio)
  11230. {
  11231. if (!qFuzzyCompare(ratio, mBufferDevicePixelRatio))
  11232. {
  11233. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  11234. mBufferDevicePixelRatio = ratio;
  11235. for (int i=0; i<mPaintBuffers.size(); ++i)
  11236. mPaintBuffers.at(i)->setDevicePixelRatio(mBufferDevicePixelRatio);
  11237. // Note: axis label cache has devicePixelRatio as part of cache hash, so no need to manually clear cache here
  11238. #else
  11239. qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
  11240. mBufferDevicePixelRatio = 1.0;
  11241. #endif
  11242. }
  11243. }
  11244. /*!
  11245. Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn
  11246. below all other objects in the plot.
  11247. For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be
  11248. enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is
  11249. preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  11250. consider using the overloaded version of this function.
  11251. If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will
  11252. first be filled with that brush, before drawing the background pixmap. This can be useful for
  11253. background pixmaps with translucent areas.
  11254. \see setBackgroundScaled, setBackgroundScaledMode
  11255. */
  11256. void QCustomPlot::setBackground(const QPixmap &pm)
  11257. {
  11258. mBackgroundPixmap = pm;
  11259. mScaledBackgroundPixmap = QPixmap();
  11260. }
  11261. /*!
  11262. Sets the background brush of the viewport (see \ref setViewport).
  11263. Before drawing everything else, the background is filled with \a brush. If a background pixmap
  11264. was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport
  11265. before the background pixmap is drawn. This can be useful for background pixmaps with translucent
  11266. areas.
  11267. Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be
  11268. useful for exporting to image formats which support transparency, e.g. \ref savePng.
  11269. \see setBackgroundScaled, setBackgroundScaledMode
  11270. */
  11271. void QCustomPlot::setBackground(const QBrush &brush)
  11272. {
  11273. mBackgroundBrush = brush;
  11274. }
  11275. /*! \overload
  11276. Allows setting the background pixmap of the viewport, whether it shall be scaled and how it
  11277. shall be scaled in one call.
  11278. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  11279. */
  11280. void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
  11281. {
  11282. mBackgroundPixmap = pm;
  11283. mScaledBackgroundPixmap = QPixmap();
  11284. mBackgroundScaled = scaled;
  11285. mBackgroundScaledMode = mode;
  11286. }
  11287. /*!
  11288. Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is
  11289. set to true, control whether and how the aspect ratio of the original pixmap is preserved with
  11290. \ref setBackgroundScaledMode.
  11291. Note that the scaled version of the original pixmap is buffered, so there is no performance
  11292. penalty on replots. (Except when the viewport dimensions are changed continuously.)
  11293. \see setBackground, setBackgroundScaledMode
  11294. */
  11295. void QCustomPlot::setBackgroundScaled(bool scaled)
  11296. {
  11297. mBackgroundScaled = scaled;
  11298. }
  11299. /*!
  11300. If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this
  11301. function to define whether and how the aspect ratio of the original pixmap is preserved.
  11302. \see setBackground, setBackgroundScaled
  11303. */
  11304. void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  11305. {
  11306. mBackgroundScaledMode = mode;
  11307. }
  11308. /*!
  11309. Returns the plottable with \a index. If the index is invalid, returns 0.
  11310. There is an overloaded version of this function with no parameter which returns the last added
  11311. plottable, see QCustomPlot::plottable()
  11312. \see plottableCount
  11313. */
  11314. QCPAbstractPlottable *QCustomPlot::plottable(int index)
  11315. {
  11316. if (index >= 0 && index < mPlottables.size())
  11317. {
  11318. return mPlottables.at(index);
  11319. } else
  11320. {
  11321. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  11322. return 0;
  11323. }
  11324. }
  11325. /*! \overload
  11326. Returns the last plottable that was added to the plot. If there are no plottables in the plot,
  11327. returns 0.
  11328. \see plottableCount
  11329. */
  11330. QCPAbstractPlottable *QCustomPlot::plottable()
  11331. {
  11332. if (!mPlottables.isEmpty())
  11333. {
  11334. return mPlottables.last();
  11335. } else
  11336. return 0;
  11337. }
  11338. /*!
  11339. Removes the specified plottable from the plot and deletes it. If necessary, the corresponding
  11340. legend item is also removed from the default legend (QCustomPlot::legend).
  11341. Returns true on success.
  11342. \see clearPlottables
  11343. */
  11344. bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable)
  11345. {
  11346. if (!mPlottables.contains(plottable))
  11347. {
  11348. qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast<quintptr>(plottable);
  11349. return false;
  11350. }
  11351. // remove plottable from legend:
  11352. plottable->removeFromLegend();
  11353. // special handling for QCPGraphs to maintain the simple graph interface:
  11354. if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable))
  11355. mGraphs.removeOne(graph);
  11356. // remove plottable:
  11357. delete plottable;
  11358. mPlottables.removeOne(plottable);
  11359. return true;
  11360. }
  11361. /*! \overload
  11362. Removes and deletes the plottable by its \a index.
  11363. */
  11364. bool QCustomPlot::removePlottable(int index)
  11365. {
  11366. if (index >= 0 && index < mPlottables.size())
  11367. return removePlottable(mPlottables[index]);
  11368. else
  11369. {
  11370. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  11371. return false;
  11372. }
  11373. }
  11374. /*!
  11375. Removes all plottables from the plot and deletes them. Corresponding legend items are also
  11376. removed from the default legend (QCustomPlot::legend).
  11377. Returns the number of plottables removed.
  11378. \see removePlottable
  11379. */
  11380. int QCustomPlot::clearPlottables()
  11381. {
  11382. int c = mPlottables.size();
  11383. for (int i=c-1; i >= 0; --i)
  11384. removePlottable(mPlottables[i]);
  11385. return c;
  11386. }
  11387. /*!
  11388. Returns the number of currently existing plottables in the plot
  11389. \see plottable
  11390. */
  11391. int QCustomPlot::plottableCount() const
  11392. {
  11393. return mPlottables.size();
  11394. }
  11395. /*!
  11396. Returns a list of the selected plottables. If no plottables are currently selected, the list is empty.
  11397. There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs.
  11398. \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection
  11399. */
  11400. QList<QCPAbstractPlottable*> QCustomPlot::selectedPlottables() const
  11401. {
  11402. QList<QCPAbstractPlottable*> result;
  11403. foreach (QCPAbstractPlottable *plottable, mPlottables)
  11404. {
  11405. if (plottable->selected())
  11406. result.append(plottable);
  11407. }
  11408. return result;
  11409. }
  11410. /*!
  11411. Returns the plottable at the pixel position \a pos. Plottables that only consist of single lines
  11412. (like graphs) have a tolerance band around them, see \ref setSelectionTolerance. If multiple
  11413. plottables come into consideration, the one closest to \a pos is returned.
  11414. If \a onlySelectable is true, only plottables that are selectable
  11415. (QCPAbstractPlottable::setSelectable) are considered.
  11416. If there is no plottable at \a pos, the return value is 0.
  11417. \see itemAt, layoutElementAt
  11418. */
  11419. QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable) const
  11420. {
  11421. QCPAbstractPlottable *resultPlottable = 0;
  11422. double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value
  11423. foreach (QCPAbstractPlottable *plottable, mPlottables)
  11424. {
  11425. if (onlySelectable && !plottable->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPabstractPlottable::selectable
  11426. continue;
  11427. if ((plottable->keyAxis()->axisRect()->rect() & plottable->valueAxis()->axisRect()->rect()).contains(pos.toPoint())) // only consider clicks inside the rect that is spanned by the plottable's key/value axes
  11428. {
  11429. double currentDistance = plottable->selectTest(pos, false);
  11430. if (currentDistance >= 0 && currentDistance < resultDistance)
  11431. {
  11432. resultPlottable = plottable;
  11433. resultDistance = currentDistance;
  11434. }
  11435. }
  11436. }
  11437. return resultPlottable;
  11438. }
  11439. /*!
  11440. Returns whether this QCustomPlot instance contains the \a plottable.
  11441. */
  11442. bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const
  11443. {
  11444. return mPlottables.contains(plottable);
  11445. }
  11446. /*!
  11447. Returns the graph with \a index. If the index is invalid, returns 0.
  11448. There is an overloaded version of this function with no parameter which returns the last created
  11449. graph, see QCustomPlot::graph()
  11450. \see graphCount, addGraph
  11451. */
  11452. QCPGraph *QCustomPlot::graph(int index) const
  11453. {
  11454. if (index >= 0 && index < mGraphs.size())
  11455. {
  11456. return mGraphs.at(index);
  11457. } else
  11458. {
  11459. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  11460. return 0;
  11461. }
  11462. }
  11463. /*! \overload
  11464. Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot,
  11465. returns 0.
  11466. \see graphCount, addGraph
  11467. */
  11468. QCPGraph *QCustomPlot::graph() const
  11469. {
  11470. if (!mGraphs.isEmpty())
  11471. {
  11472. return mGraphs.last();
  11473. } else
  11474. return 0;
  11475. }
  11476. /*!
  11477. Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the
  11478. bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a
  11479. keyAxis and \a valueAxis must reside in this QCustomPlot.
  11480. \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically
  11481. "y") for the graph.
  11482. Returns a pointer to the newly created graph, or 0 if adding the graph failed.
  11483. \see graph, graphCount, removeGraph, clearGraphs
  11484. */
  11485. QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis)
  11486. {
  11487. if (!keyAxis) keyAxis = xAxis;
  11488. if (!valueAxis) valueAxis = yAxis;
  11489. if (!keyAxis || !valueAxis)
  11490. {
  11491. qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)";
  11492. return 0;
  11493. }
  11494. if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this)
  11495. {
  11496. qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent";
  11497. return 0;
  11498. }
  11499. QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis);
  11500. newGraph->setName(QLatin1String("Graph ")+QString::number(mGraphs.size()));
  11501. return newGraph;
  11502. }
  11503. /*!
  11504. Removes the specified \a graph from the plot and deletes it. If necessary, the corresponding
  11505. legend item is also removed from the default legend (QCustomPlot::legend). If any other graphs in
  11506. the plot have a channel fill set towards the removed graph, the channel fill property of those
  11507. graphs is reset to zero (no channel fill).
  11508. Returns true on success.
  11509. \see clearGraphs
  11510. */
  11511. bool QCustomPlot::removeGraph(QCPGraph *graph)
  11512. {
  11513. return removePlottable(graph);
  11514. }
  11515. /*! \overload
  11516. Removes and deletes the graph by its \a index.
  11517. */
  11518. bool QCustomPlot::removeGraph(int index)
  11519. {
  11520. if (index >= 0 && index < mGraphs.size())
  11521. return removeGraph(mGraphs[index]);
  11522. else
  11523. return false;
  11524. }
  11525. /*!
  11526. Removes all graphs from the plot and deletes them. Corresponding legend items are also removed
  11527. from the default legend (QCustomPlot::legend).
  11528. Returns the number of graphs removed.
  11529. \see removeGraph
  11530. */
  11531. int QCustomPlot::clearGraphs()
  11532. {
  11533. int c = mGraphs.size();
  11534. for (int i=c-1; i >= 0; --i)
  11535. removeGraph(mGraphs[i]);
  11536. return c;
  11537. }
  11538. /*!
  11539. Returns the number of currently existing graphs in the plot
  11540. \see graph, addGraph
  11541. */
  11542. int QCustomPlot::graphCount() const
  11543. {
  11544. return mGraphs.size();
  11545. }
  11546. /*!
  11547. Returns a list of the selected graphs. If no graphs are currently selected, the list is empty.
  11548. If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars,
  11549. etc., use \ref selectedPlottables.
  11550. \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection
  11551. */
  11552. QList<QCPGraph*> QCustomPlot::selectedGraphs() const
  11553. {
  11554. QList<QCPGraph*> result;
  11555. foreach (QCPGraph *graph, mGraphs)
  11556. {
  11557. if (graph->selected())
  11558. result.append(graph);
  11559. }
  11560. return result;
  11561. }
  11562. /*!
  11563. Returns the item with \a index. If the index is invalid, returns 0.
  11564. There is an overloaded version of this function with no parameter which returns the last added
  11565. item, see QCustomPlot::item()
  11566. \see itemCount
  11567. */
  11568. QCPAbstractItem *QCustomPlot::item(int index) const
  11569. {
  11570. if (index >= 0 && index < mItems.size())
  11571. {
  11572. return mItems.at(index);
  11573. } else
  11574. {
  11575. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  11576. return 0;
  11577. }
  11578. }
  11579. /*! \overload
  11580. Returns the last item that was added to this plot. If there are no items in the plot,
  11581. returns 0.
  11582. \see itemCount
  11583. */
  11584. QCPAbstractItem *QCustomPlot::item() const
  11585. {
  11586. if (!mItems.isEmpty())
  11587. {
  11588. return mItems.last();
  11589. } else
  11590. return 0;
  11591. }
  11592. /*!
  11593. Removes the specified item from the plot and deletes it.
  11594. Returns true on success.
  11595. \see clearItems
  11596. */
  11597. bool QCustomPlot::removeItem(QCPAbstractItem *item)
  11598. {
  11599. if (mItems.contains(item))
  11600. {
  11601. delete item;
  11602. mItems.removeOne(item);
  11603. return true;
  11604. } else
  11605. {
  11606. qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast<quintptr>(item);
  11607. return false;
  11608. }
  11609. }
  11610. /*! \overload
  11611. Removes and deletes the item by its \a index.
  11612. */
  11613. bool QCustomPlot::removeItem(int index)
  11614. {
  11615. if (index >= 0 && index < mItems.size())
  11616. return removeItem(mItems[index]);
  11617. else
  11618. {
  11619. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  11620. return false;
  11621. }
  11622. }
  11623. /*!
  11624. Removes all items from the plot and deletes them.
  11625. Returns the number of items removed.
  11626. \see removeItem
  11627. */
  11628. int QCustomPlot::clearItems()
  11629. {
  11630. int c = mItems.size();
  11631. for (int i=c-1; i >= 0; --i)
  11632. removeItem(mItems[i]);
  11633. return c;
  11634. }
  11635. /*!
  11636. Returns the number of currently existing items in the plot
  11637. \see item
  11638. */
  11639. int QCustomPlot::itemCount() const
  11640. {
  11641. return mItems.size();
  11642. }
  11643. /*!
  11644. Returns a list of the selected items. If no items are currently selected, the list is empty.
  11645. \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected
  11646. */
  11647. QList<QCPAbstractItem*> QCustomPlot::selectedItems() const
  11648. {
  11649. QList<QCPAbstractItem*> result;
  11650. foreach (QCPAbstractItem *item, mItems)
  11651. {
  11652. if (item->selected())
  11653. result.append(item);
  11654. }
  11655. return result;
  11656. }
  11657. /*!
  11658. Returns the item at the pixel position \a pos. Items that only consist of single lines (e.g. \ref
  11659. QCPItemLine or \ref QCPItemCurve) have a tolerance band around them, see \ref
  11660. setSelectionTolerance. If multiple items come into consideration, the one closest to \a pos is
  11661. returned.
  11662. If \a onlySelectable is true, only items that are selectable (QCPAbstractItem::setSelectable) are
  11663. considered.
  11664. If there is no item at \a pos, the return value is 0.
  11665. \see plottableAt, layoutElementAt
  11666. */
  11667. QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const
  11668. {
  11669. QCPAbstractItem *resultItem = 0;
  11670. double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value
  11671. foreach (QCPAbstractItem *item, mItems)
  11672. {
  11673. if (onlySelectable && !item->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable
  11674. continue;
  11675. if (!item->clipToAxisRect() || item->clipRect().contains(pos.toPoint())) // only consider clicks inside axis cliprect of the item if actually clipped to it
  11676. {
  11677. double currentDistance = item->selectTest(pos, false);
  11678. if (currentDistance >= 0 && currentDistance < resultDistance)
  11679. {
  11680. resultItem = item;
  11681. resultDistance = currentDistance;
  11682. }
  11683. }
  11684. }
  11685. return resultItem;
  11686. }
  11687. /*!
  11688. Returns whether this QCustomPlot contains the \a item.
  11689. \see item
  11690. */
  11691. bool QCustomPlot::hasItem(QCPAbstractItem *item) const
  11692. {
  11693. return mItems.contains(item);
  11694. }
  11695. /*!
  11696. Returns the layer with the specified \a name. If there is no layer with the specified name, 0 is
  11697. returned.
  11698. Layer names are case-sensitive.
  11699. \see addLayer, moveLayer, removeLayer
  11700. */
  11701. QCPLayer *QCustomPlot::layer(const QString &name) const
  11702. {
  11703. foreach (QCPLayer *layer, mLayers)
  11704. {
  11705. if (layer->name() == name)
  11706. return layer;
  11707. }
  11708. return 0;
  11709. }
  11710. /*! \overload
  11711. Returns the layer by \a index. If the index is invalid, 0 is returned.
  11712. \see addLayer, moveLayer, removeLayer
  11713. */
  11714. QCPLayer *QCustomPlot::layer(int index) const
  11715. {
  11716. if (index >= 0 && index < mLayers.size())
  11717. {
  11718. return mLayers.at(index);
  11719. } else
  11720. {
  11721. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  11722. return 0;
  11723. }
  11724. }
  11725. /*!
  11726. Returns the layer that is set as current layer (see \ref setCurrentLayer).
  11727. */
  11728. QCPLayer *QCustomPlot::currentLayer() const
  11729. {
  11730. return mCurrentLayer;
  11731. }
  11732. /*!
  11733. Sets the layer with the specified \a name to be the current layer. All layerables (\ref
  11734. QCPLayerable), e.g. plottables and items, are created on the current layer.
  11735. Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot.
  11736. Layer names are case-sensitive.
  11737. \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer
  11738. */
  11739. bool QCustomPlot::setCurrentLayer(const QString &name)
  11740. {
  11741. if (QCPLayer *newCurrentLayer = layer(name))
  11742. {
  11743. return setCurrentLayer(newCurrentLayer);
  11744. } else
  11745. {
  11746. qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name;
  11747. return false;
  11748. }
  11749. }
  11750. /*! \overload
  11751. Sets the provided \a layer to be the current layer.
  11752. Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot.
  11753. \see addLayer, moveLayer, removeLayer
  11754. */
  11755. bool QCustomPlot::setCurrentLayer(QCPLayer *layer)
  11756. {
  11757. if (!mLayers.contains(layer))
  11758. {
  11759. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  11760. return false;
  11761. }
  11762. mCurrentLayer = layer;
  11763. return true;
  11764. }
  11765. /*!
  11766. Returns the number of currently existing layers in the plot
  11767. \see layer, addLayer
  11768. */
  11769. int QCustomPlot::layerCount() const
  11770. {
  11771. return mLayers.size();
  11772. }
  11773. /*!
  11774. Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which
  11775. must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer.
  11776. Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a
  11777. valid layer inside this QCustomPlot.
  11778. If \a otherLayer is 0, the highest layer in the QCustomPlot will be used.
  11779. For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer.
  11780. \see layer, moveLayer, removeLayer
  11781. */
  11782. bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
  11783. {
  11784. if (!otherLayer)
  11785. otherLayer = mLayers.last();
  11786. if (!mLayers.contains(otherLayer))
  11787. {
  11788. qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
  11789. return false;
  11790. }
  11791. if (layer(name))
  11792. {
  11793. qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name;
  11794. return false;
  11795. }
  11796. QCPLayer *newLayer = new QCPLayer(this, name);
  11797. mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer);
  11798. updateLayerIndices();
  11799. setupPaintBuffers(); // associates new layer with the appropriate paint buffer
  11800. return true;
  11801. }
  11802. /*!
  11803. Removes the specified \a layer and returns true on success.
  11804. All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below
  11805. \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both
  11806. cases, the total rendering order of all layerables in the QCustomPlot is preserved.
  11807. If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom
  11808. layer) becomes the new current layer.
  11809. It is not possible to remove the last layer of the plot.
  11810. \see layer, addLayer, moveLayer
  11811. */
  11812. bool QCustomPlot::removeLayer(QCPLayer *layer)
  11813. {
  11814. if (!mLayers.contains(layer))
  11815. {
  11816. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  11817. return false;
  11818. }
  11819. if (mLayers.size() < 2)
  11820. {
  11821. qDebug() << Q_FUNC_INFO << "can't remove last layer";
  11822. return false;
  11823. }
  11824. // append all children of this layer to layer below (if this is lowest layer, prepend to layer above)
  11825. int removedIndex = layer->index();
  11826. bool isFirstLayer = removedIndex==0;
  11827. QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1);
  11828. QList<QCPLayerable*> children = layer->children();
  11829. if (isFirstLayer) // prepend in reverse order (so order relative to each other stays the same)
  11830. {
  11831. for (int i=children.size()-1; i>=0; --i)
  11832. children.at(i)->moveToLayer(targetLayer, true);
  11833. } else // append normally
  11834. {
  11835. for (int i=0; i<children.size(); ++i)
  11836. children.at(i)->moveToLayer(targetLayer, false);
  11837. }
  11838. // if removed layer is current layer, change current layer to layer below/above:
  11839. if (layer == mCurrentLayer)
  11840. setCurrentLayer(targetLayer);
  11841. // invalidate the paint buffer that was responsible for this layer:
  11842. if (!layer->mPaintBuffer.isNull())
  11843. layer->mPaintBuffer.data()->setInvalidated();
  11844. // remove layer:
  11845. delete layer;
  11846. mLayers.removeOne(layer);
  11847. updateLayerIndices();
  11848. return true;
  11849. }
  11850. /*!
  11851. Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or
  11852. below is controlled with \a insertMode.
  11853. Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the
  11854. QCustomPlot.
  11855. \see layer, addLayer, moveLayer
  11856. */
  11857. bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
  11858. {
  11859. if (!mLayers.contains(layer))
  11860. {
  11861. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  11862. return false;
  11863. }
  11864. if (!mLayers.contains(otherLayer))
  11865. {
  11866. qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
  11867. return false;
  11868. }
  11869. if (layer->index() > otherLayer->index())
  11870. mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0));
  11871. else if (layer->index() < otherLayer->index())
  11872. mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 0:-1));
  11873. // invalidate the paint buffers that are responsible for the layers:
  11874. if (!layer->mPaintBuffer.isNull())
  11875. layer->mPaintBuffer.data()->setInvalidated();
  11876. if (!otherLayer->mPaintBuffer.isNull())
  11877. otherLayer->mPaintBuffer.data()->setInvalidated();
  11878. updateLayerIndices();
  11879. return true;
  11880. }
  11881. /*!
  11882. Returns the number of axis rects in the plot.
  11883. All axis rects can be accessed via QCustomPlot::axisRect().
  11884. Initially, only one axis rect exists in the plot.
  11885. \see axisRect, axisRects
  11886. */
  11887. int QCustomPlot::axisRectCount() const
  11888. {
  11889. return axisRects().size();
  11890. }
  11891. /*!
  11892. Returns the axis rect with \a index.
  11893. Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were
  11894. added, all of them may be accessed with this function in a linear fashion (even when they are
  11895. nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout).
  11896. \see axisRectCount, axisRects
  11897. */
  11898. QCPAxisRect *QCustomPlot::axisRect(int index) const
  11899. {
  11900. const QList<QCPAxisRect*> rectList = axisRects();
  11901. if (index >= 0 && index < rectList.size())
  11902. {
  11903. return rectList.at(index);
  11904. } else
  11905. {
  11906. qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index;
  11907. return 0;
  11908. }
  11909. }
  11910. /*!
  11911. Returns all axis rects in the plot.
  11912. \see axisRectCount, axisRect
  11913. */
  11914. QList<QCPAxisRect*> QCustomPlot::axisRects() const
  11915. {
  11916. QList<QCPAxisRect*> result;
  11917. QStack<QCPLayoutElement*> elementStack;
  11918. if (mPlotLayout)
  11919. elementStack.push(mPlotLayout);
  11920. while (!elementStack.isEmpty())
  11921. {
  11922. foreach (QCPLayoutElement *element, elementStack.pop()->elements(false))
  11923. {
  11924. if (element)
  11925. {
  11926. elementStack.push(element);
  11927. if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(element))
  11928. result.append(ar);
  11929. }
  11930. }
  11931. }
  11932. return result;
  11933. }
  11934. /*!
  11935. Returns the layout element at pixel position \a pos. If there is no element at that position,
  11936. returns 0.
  11937. Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on
  11938. any of its parent elements is set to false, it will not be considered.
  11939. \see itemAt, plottableAt
  11940. */
  11941. QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const
  11942. {
  11943. QCPLayoutElement *currentElement = mPlotLayout;
  11944. bool searchSubElements = true;
  11945. while (searchSubElements && currentElement)
  11946. {
  11947. searchSubElements = false;
  11948. foreach (QCPLayoutElement *subElement, currentElement->elements(false))
  11949. {
  11950. if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
  11951. {
  11952. currentElement = subElement;
  11953. searchSubElements = true;
  11954. break;
  11955. }
  11956. }
  11957. }
  11958. return currentElement;
  11959. }
  11960. /*!
  11961. Returns the layout element of type \ref QCPAxisRect at pixel position \a pos. This method ignores
  11962. other layout elements even if they are visually in front of the axis rect (e.g. a \ref
  11963. QCPLegend). If there is no axis rect at that position, returns 0.
  11964. Only visible axis rects are used. If \ref QCPLayoutElement::setVisible on the axis rect itself or
  11965. on any of its parent elements is set to false, it will not be considered.
  11966. \see layoutElementAt
  11967. */
  11968. QCPAxisRect *QCustomPlot::axisRectAt(const QPointF &pos) const
  11969. {
  11970. QCPAxisRect *result = 0;
  11971. QCPLayoutElement *currentElement = mPlotLayout;
  11972. bool searchSubElements = true;
  11973. while (searchSubElements && currentElement)
  11974. {
  11975. searchSubElements = false;
  11976. foreach (QCPLayoutElement *subElement, currentElement->elements(false))
  11977. {
  11978. if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
  11979. {
  11980. currentElement = subElement;
  11981. searchSubElements = true;
  11982. if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(currentElement))
  11983. result = ar;
  11984. break;
  11985. }
  11986. }
  11987. }
  11988. return result;
  11989. }
  11990. /*!
  11991. Returns the axes that currently have selected parts, i.e. whose selection state is not \ref
  11992. QCPAxis::spNone.
  11993. \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts,
  11994. QCPAxis::setSelectableParts
  11995. */
  11996. QList<QCPAxis*> QCustomPlot::selectedAxes() const
  11997. {
  11998. QList<QCPAxis*> result, allAxes;
  11999. foreach (QCPAxisRect *rect, axisRects())
  12000. allAxes << rect->axes();
  12001. foreach (QCPAxis *axis, allAxes)
  12002. {
  12003. if (axis->selectedParts() != QCPAxis::spNone)
  12004. result.append(axis);
  12005. }
  12006. return result;
  12007. }
  12008. /*!
  12009. Returns the legends that currently have selected parts, i.e. whose selection state is not \ref
  12010. QCPLegend::spNone.
  12011. \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts,
  12012. QCPLegend::setSelectableParts, QCPLegend::selectedItems
  12013. */
  12014. QList<QCPLegend*> QCustomPlot::selectedLegends() const
  12015. {
  12016. QList<QCPLegend*> result;
  12017. QStack<QCPLayoutElement*> elementStack;
  12018. if (mPlotLayout)
  12019. elementStack.push(mPlotLayout);
  12020. while (!elementStack.isEmpty())
  12021. {
  12022. foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false))
  12023. {
  12024. if (subElement)
  12025. {
  12026. elementStack.push(subElement);
  12027. if (QCPLegend *leg = qobject_cast<QCPLegend*>(subElement))
  12028. {
  12029. if (leg->selectedParts() != QCPLegend::spNone)
  12030. result.append(leg);
  12031. }
  12032. }
  12033. }
  12034. }
  12035. return result;
  12036. }
  12037. /*!
  12038. Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot.
  12039. Since calling this function is not a user interaction, this does not emit the \ref
  12040. selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the
  12041. objects were previously selected.
  12042. \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends
  12043. */
  12044. void QCustomPlot::deselectAll()
  12045. {
  12046. foreach (QCPLayer *layer, mLayers)
  12047. {
  12048. foreach (QCPLayerable *layerable, layer->children())
  12049. layerable->deselectEvent(0);
  12050. }
  12051. }
  12052. /*!
  12053. Causes a complete replot into the internal paint buffer(s). Finally, the widget surface is
  12054. refreshed with the new buffer contents. This is the method that must be called to make changes to
  12055. the plot, e.g. on the axis ranges or data points of graphs, visible.
  12056. The parameter \a refreshPriority can be used to fine-tune the timing of the replot. For example
  12057. if your application calls \ref replot very quickly in succession (e.g. multiple independent
  12058. functions change some aspects of the plot and each wants to make sure the change gets replotted),
  12059. it is advisable to set \a refreshPriority to \ref QCustomPlot::rpQueuedReplot. This way, the
  12060. actual replotting is deferred to the next event loop iteration. Multiple successive calls of \ref
  12061. replot with this priority will only cause a single replot, avoiding redundant replots and
  12062. improving performance.
  12063. Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the
  12064. QCustomPlot widget and user interactions (object selection and range dragging/zooming).
  12065. Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref
  12066. afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two
  12067. signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite
  12068. recursion.
  12069. If a layer is in mode \ref QCPLayer::lmBuffered (\ref QCPLayer::setMode), it is also possible to
  12070. replot only that specific layer via \ref QCPLayer::replot. See the documentation there for
  12071. details.
  12072. */
  12073. void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority)
  12074. {
  12075. if (refreshPriority == QCustomPlot::rpQueuedReplot)
  12076. {
  12077. if (!mReplotQueued)
  12078. {
  12079. mReplotQueued = true;
  12080. QTimer::singleShot(0, this, SLOT(replot()));
  12081. }
  12082. return;
  12083. }
  12084. if (mReplotting) // incase signals loop back to replot slot
  12085. return;
  12086. mReplotting = true;
  12087. mReplotQueued = false;
  12088. emit beforeReplot();
  12089. updateLayout();
  12090. // draw all layered objects (grid, axes, plottables, items, legend,...) into their buffers:
  12091. setupPaintBuffers();
  12092. foreach (QCPLayer *layer, mLayers)
  12093. layer->drawToPaintBuffer();
  12094. for (int i=0; i<mPaintBuffers.size(); ++i)
  12095. mPaintBuffers.at(i)->setInvalidated(false);
  12096. if ((refreshPriority == rpRefreshHint && mPlottingHints.testFlag(QCP::phImmediateRefresh)) || refreshPriority==rpImmediateRefresh)
  12097. repaint();
  12098. else
  12099. update();
  12100. emit afterReplot();
  12101. mReplotting = false;
  12102. }
  12103. /*!
  12104. Rescales the axes such that all plottables (like graphs) in the plot are fully visible.
  12105. if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true
  12106. (QCPLayerable::setVisible), will be used to rescale the axes.
  12107. \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale
  12108. */
  12109. void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables)
  12110. {
  12111. QList<QCPAxis*> allAxes;
  12112. foreach (QCPAxisRect *rect, axisRects())
  12113. allAxes << rect->axes();
  12114. foreach (QCPAxis *axis, allAxes)
  12115. axis->rescale(onlyVisiblePlottables);
  12116. }
  12117. /*!
  12118. Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale
  12119. of texts and lines will be derived from the specified \a width and \a height. This means, the
  12120. output will look like the normal on-screen output of a QCustomPlot widget with the corresponding
  12121. pixel width and height. If either \a width or \a height is zero, the exported image will have the
  12122. same dimensions as the QCustomPlot widget currently has.
  12123. Setting \a exportPen to \ref QCP::epNoCosmetic allows to disable the use of cosmetic pens when
  12124. drawing to the PDF file. Cosmetic pens are pens with numerical width 0, which are always drawn as
  12125. a one pixel wide line, no matter what zoom factor is set in the PDF-Viewer. For more information
  12126. about cosmetic pens, see the QPainter and QPen documentation.
  12127. The objects of the plot will appear in the current selection state. If you don't want any
  12128. selected objects to be painted in their selected look, deselect everything with \ref deselectAll
  12129. before calling this function.
  12130. Returns true on success.
  12131. \warning
  12132. \li If you plan on editing the exported PDF file with a vector graphics editor like Inkscape, it
  12133. is advised to set \a exportPen to \ref QCP::epNoCosmetic to avoid losing those cosmetic lines
  12134. (which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks).
  12135. \li If calling this function inside the constructor of the parent of the QCustomPlot widget
  12136. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12137. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12138. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12139. aren't defined yet inside the constructor, so you would get an image that has strange
  12140. widths/heights.
  12141. \a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting
  12142. PDF file.
  12143. \note On Android systems, this method does nothing and issues an according qDebug warning
  12144. message. This is also the case if for other reasons the define flag \c QT_NO_PRINTER is set.
  12145. \see savePng, saveBmp, saveJpg, saveRastered
  12146. */
  12147. bool QCustomPlot::savePdf(const QString &fileName, int width, int height, QCP::ExportPen exportPen, const QString &pdfCreator, const QString &pdfTitle)
  12148. {
  12149. bool success = false;
  12150. #ifdef QT_NO_PRINTER
  12151. Q_UNUSED(fileName)
  12152. Q_UNUSED(exportPen)
  12153. Q_UNUSED(width)
  12154. Q_UNUSED(height)
  12155. Q_UNUSED(pdfCreator)
  12156. Q_UNUSED(pdfTitle)
  12157. qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created.";
  12158. #else
  12159. int newWidth, newHeight;
  12160. if (width == 0 || height == 0)
  12161. {
  12162. newWidth = this->width();
  12163. newHeight = this->height();
  12164. } else
  12165. {
  12166. newWidth = width;
  12167. newHeight = height;
  12168. }
  12169. QPrinter printer(QPrinter::ScreenResolution);
  12170. printer.setOutputFileName(fileName);
  12171. printer.setOutputFormat(QPrinter::PdfFormat);
  12172. printer.setColorMode(QPrinter::Color);
  12173. printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator);
  12174. printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle);
  12175. QRect oldViewport = viewport();
  12176. setViewport(QRect(0, 0, newWidth, newHeight));
  12177. #if QT_VERSION < QT_VERSION_CHECK(5, 3, 0)
  12178. printer.setFullPage(true);
  12179. printer.setPaperSize(viewport().size(), QPrinter::DevicePixel);
  12180. #else
  12181. QPageLayout pageLayout;
  12182. pageLayout.setMode(QPageLayout::FullPageMode);
  12183. pageLayout.setOrientation(QPageLayout::Portrait);
  12184. pageLayout.setMargins(QMarginsF(0, 0, 0, 0));
  12185. pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch));
  12186. printer.setPageLayout(pageLayout);
  12187. #endif
  12188. QCPPainter printpainter;
  12189. if (printpainter.begin(&printer))
  12190. {
  12191. printpainter.setMode(QCPPainter::pmVectorized);
  12192. printpainter.setMode(QCPPainter::pmNoCaching);
  12193. printpainter.setMode(QCPPainter::pmNonCosmetic, exportPen==QCP::epNoCosmetic);
  12194. printpainter.setWindow(mViewport);
  12195. if (mBackgroundBrush.style() != Qt::NoBrush &&
  12196. mBackgroundBrush.color() != Qt::white &&
  12197. mBackgroundBrush.color() != Qt::transparent &&
  12198. mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent
  12199. printpainter.fillRect(viewport(), mBackgroundBrush);
  12200. draw(&printpainter);
  12201. printpainter.end();
  12202. success = true;
  12203. }
  12204. setViewport(oldViewport);
  12205. #endif // QT_NO_PRINTER
  12206. return success;
  12207. }
  12208. /*!
  12209. Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width
  12210. and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
  12211. current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
  12212. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
  12213. parameter.
  12214. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  12215. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  12216. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  12217. 200*200 pixel resolution.
  12218. If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
  12219. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  12220. QCustomPlot to place objects with sub-pixel accuracy.
  12221. image compression can be controlled with the \a quality parameter which must be between 0 and 100
  12222. or -1 to use the default setting.
  12223. The \a resolution will be written to the image file header and has no direct consequence for the
  12224. quality or the pixel size. However, if opening the image with a tool which respects the metadata,
  12225. it will be able to scale the image to match either a given size in real units of length (inch,
  12226. centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
  12227. given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
  12228. resolution unit internally.
  12229. Returns true on success. If this function fails, most likely the PNG format isn't supported by
  12230. the system, see Qt docs about QImageWriter::supportedImageFormats().
  12231. The objects of the plot will appear in the current selection state. If you don't want any selected
  12232. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  12233. this function.
  12234. If you want the PNG to have a transparent background, call \ref setBackground(const QBrush &brush)
  12235. with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving.
  12236. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  12237. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12238. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12239. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12240. aren't defined yet inside the constructor, so you would get an image that has strange
  12241. widths/heights.
  12242. \see savePdf, saveBmp, saveJpg, saveRastered
  12243. */
  12244. bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
  12245. {
  12246. return saveRastered(fileName, width, height, scale, "PNG", quality, resolution, resolutionUnit);
  12247. }
  12248. /*!
  12249. Saves a JPEG image file to \a fileName on disc. The output plot will have the dimensions \a width
  12250. and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
  12251. current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
  12252. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
  12253. parameter.
  12254. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  12255. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  12256. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  12257. 200*200 pixel resolution.
  12258. If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
  12259. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  12260. QCustomPlot to place objects with sub-pixel accuracy.
  12261. image compression can be controlled with the \a quality parameter which must be between 0 and 100
  12262. or -1 to use the default setting.
  12263. The \a resolution will be written to the image file header and has no direct consequence for the
  12264. quality or the pixel size. However, if opening the image with a tool which respects the metadata,
  12265. it will be able to scale the image to match either a given size in real units of length (inch,
  12266. centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
  12267. given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
  12268. resolution unit internally.
  12269. Returns true on success. If this function fails, most likely the JPEG format isn't supported by
  12270. the system, see Qt docs about QImageWriter::supportedImageFormats().
  12271. The objects of the plot will appear in the current selection state. If you don't want any selected
  12272. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  12273. this function.
  12274. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  12275. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12276. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12277. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12278. aren't defined yet inside the constructor, so you would get an image that has strange
  12279. widths/heights.
  12280. \see savePdf, savePng, saveBmp, saveRastered
  12281. */
  12282. bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
  12283. {
  12284. return saveRastered(fileName, width, height, scale, "JPG", quality, resolution, resolutionUnit);
  12285. }
  12286. /*!
  12287. Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width
  12288. and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
  12289. current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
  12290. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
  12291. parameter.
  12292. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  12293. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  12294. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  12295. 200*200 pixel resolution.
  12296. If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
  12297. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  12298. QCustomPlot to place objects with sub-pixel accuracy.
  12299. The \a resolution will be written to the image file header and has no direct consequence for the
  12300. quality or the pixel size. However, if opening the image with a tool which respects the metadata,
  12301. it will be able to scale the image to match either a given size in real units of length (inch,
  12302. centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
  12303. given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
  12304. resolution unit internally.
  12305. Returns true on success. If this function fails, most likely the BMP format isn't supported by
  12306. the system, see Qt docs about QImageWriter::supportedImageFormats().
  12307. The objects of the plot will appear in the current selection state. If you don't want any selected
  12308. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  12309. this function.
  12310. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  12311. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12312. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12313. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12314. aren't defined yet inside the constructor, so you would get an image that has strange
  12315. widths/heights.
  12316. \see savePdf, savePng, saveJpg, saveRastered
  12317. */
  12318. bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale, int resolution, QCP::ResolutionUnit resolutionUnit)
  12319. {
  12320. return saveRastered(fileName, width, height, scale, "BMP", -1, resolution, resolutionUnit);
  12321. }
  12322. /*! \internal
  12323. Returns a minimum size hint that corresponds to the minimum size of the top level layout
  12324. (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum
  12325. size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot.
  12326. This is especially important, when placed in a QLayout where other components try to take in as
  12327. much space as possible (e.g. QMdiArea).
  12328. */
  12329. QSize QCustomPlot::minimumSizeHint() const
  12330. {
  12331. return mPlotLayout->minimumOuterSizeHint();
  12332. }
  12333. /*! \internal
  12334. Returns a size hint that is the same as \ref minimumSizeHint.
  12335. */
  12336. QSize QCustomPlot::sizeHint() const
  12337. {
  12338. return mPlotLayout->minimumOuterSizeHint();
  12339. }
  12340. /*! \internal
  12341. Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but
  12342. draws the internal buffer on the widget surface.
  12343. */
  12344. void QCustomPlot::paintEvent(QPaintEvent *event)
  12345. {
  12346. Q_UNUSED(event);
  12347. QCPPainter painter(this);
  12348. if (painter.isActive())
  12349. {
  12350. painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem
  12351. if (mBackgroundBrush.style() != Qt::NoBrush)
  12352. painter.fillRect(mViewport, mBackgroundBrush);
  12353. drawBackground(&painter);
  12354. for (int bufferIndex = 0; bufferIndex < mPaintBuffers.size(); ++bufferIndex)
  12355. mPaintBuffers.at(bufferIndex)->draw(&painter);
  12356. }
  12357. }
  12358. /*! \internal
  12359. Event handler for a resize of the QCustomPlot widget. The viewport (which becomes the outer rect
  12360. of mPlotLayout) is resized appropriately. Finally a \ref replot is performed.
  12361. */
  12362. void QCustomPlot::resizeEvent(QResizeEvent *event)
  12363. {
  12364. Q_UNUSED(event)
  12365. // resize and repaint the buffer:
  12366. setViewport(rect());
  12367. replot(rpQueuedRefresh); // queued refresh is important here, to prevent painting issues in some contexts (e.g. MDI subwindow)
  12368. }
  12369. /*! \internal
  12370. Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then
  12371. determines the layerable under the cursor and forwards the event to it. Finally, emits the
  12372. specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref
  12373. axisDoubleClick, etc.).
  12374. \see mousePressEvent, mouseReleaseEvent
  12375. */
  12376. void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event)
  12377. {
  12378. emit mouseDoubleClick(event);
  12379. mMouseHasMoved = false;
  12380. mMousePressPos = event->pos();
  12381. // determine layerable under the cursor (this event is called instead of the second press event in a double-click):
  12382. QList<QVariant> details;
  12383. QList<QCPLayerable*> candidates = layerableListAt(mMousePressPos, false, &details);
  12384. for (int i=0; i<candidates.size(); ++i)
  12385. {
  12386. event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
  12387. candidates.at(i)->mouseDoubleClickEvent(event, details.at(i));
  12388. if (event->isAccepted())
  12389. {
  12390. mMouseEventLayerable = candidates.at(i);
  12391. mMouseEventLayerableDetails = details.at(i);
  12392. break;
  12393. }
  12394. }
  12395. // emit specialized object double click signals:
  12396. if (!candidates.isEmpty())
  12397. {
  12398. if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(candidates.first()))
  12399. {
  12400. int dataIndex = 0;
  12401. if (!details.first().value<QCPDataSelection>().isEmpty())
  12402. dataIndex = details.first().value<QCPDataSelection>().dataRange().begin();
  12403. emit plottableDoubleClick(ap, dataIndex, event);
  12404. } else if (QCPAxis *ax = qobject_cast<QCPAxis*>(candidates.first()))
  12405. emit axisDoubleClick(ax, details.first().value<QCPAxis::SelectablePart>(), event);
  12406. else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(candidates.first()))
  12407. emit itemDoubleClick(ai, event);
  12408. else if (QCPLegend *lg = qobject_cast<QCPLegend*>(candidates.first()))
  12409. emit legendDoubleClick(lg, 0, event);
  12410. else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(candidates.first()))
  12411. emit legendDoubleClick(li->parentLegend(), li, event);
  12412. }
  12413. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  12414. }
  12415. /*! \internal
  12416. Event handler for when a mouse button is pressed. Emits the mousePress signal.
  12417. If the current \ref setSelectionRectMode is not \ref QCP::srmNone, passes the event to the
  12418. selection rect. Otherwise determines the layerable under the cursor and forwards the event to it.
  12419. \see mouseMoveEvent, mouseReleaseEvent
  12420. */
  12421. void QCustomPlot::mousePressEvent(QMouseEvent *event)
  12422. {
  12423. emit mousePress(event);
  12424. // save some state to tell in releaseEvent whether it was a click:
  12425. mMouseHasMoved = false;
  12426. mMousePressPos = event->pos();
  12427. if (mSelectionRect && mSelectionRectMode != QCP::srmNone)
  12428. {
  12429. if (mSelectionRectMode != QCP::srmZoom || qobject_cast<QCPAxisRect*>(axisRectAt(mMousePressPos))) // in zoom mode only activate selection rect if on an axis rect
  12430. mSelectionRect->startSelection(event);
  12431. } else
  12432. {
  12433. // no selection rect interaction, prepare for click signal emission and forward event to layerable under the cursor:
  12434. QList<QVariant> details;
  12435. QList<QCPLayerable*> candidates = layerableListAt(mMousePressPos, false, &details);
  12436. if (!candidates.isEmpty())
  12437. {
  12438. mMouseSignalLayerable = candidates.first(); // candidate for signal emission is always topmost hit layerable (signal emitted in release event)
  12439. mMouseSignalLayerableDetails = details.first();
  12440. }
  12441. // forward event to topmost candidate which accepts the event:
  12442. for (int i=0; i<candidates.size(); ++i)
  12443. {
  12444. event->accept(); // default impl of QCPLayerable's mouse events call ignore() on the event, in that case propagate to next candidate in list
  12445. candidates.at(i)->mousePressEvent(event, details.at(i));
  12446. if (event->isAccepted())
  12447. {
  12448. mMouseEventLayerable = candidates.at(i);
  12449. mMouseEventLayerableDetails = details.at(i);
  12450. break;
  12451. }
  12452. }
  12453. }
  12454. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  12455. }
  12456. /*! \internal
  12457. Event handler for when the cursor is moved. Emits the \ref mouseMove signal.
  12458. If the selection rect (\ref setSelectionRect) is currently active, the event is forwarded to it
  12459. in order to update the rect geometry.
  12460. Otherwise, if a layout element has mouse capture focus (a mousePressEvent happened on top of the
  12461. layout element before), the mouseMoveEvent is forwarded to that element.
  12462. \see mousePressEvent, mouseReleaseEvent
  12463. */
  12464. void QCustomPlot::mouseMoveEvent(QMouseEvent *event)
  12465. {
  12466. emit mouseMove(event);
  12467. if (!mMouseHasMoved && (mMousePressPos-event->pos()).manhattanLength() > 3)
  12468. mMouseHasMoved = true; // moved too far from mouse press position, don't handle as click on mouse release
  12469. if (mSelectionRect && mSelectionRect->isActive())
  12470. mSelectionRect->moveSelection(event);
  12471. else if (mMouseEventLayerable) // call event of affected layerable:
  12472. mMouseEventLayerable->mouseMoveEvent(event, mMousePressPos);
  12473. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  12474. }
  12475. /*! \internal
  12476. Event handler for when a mouse button is released. Emits the \ref mouseRelease signal.
  12477. If the mouse was moved less than a certain threshold in any direction since the \ref
  12478. mousePressEvent, it is considered a click which causes the selection mechanism (if activated via
  12479. \ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse
  12480. click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.)
  12481. If a layerable is the mouse capturer (a \ref mousePressEvent happened on top of the layerable
  12482. before), the \ref mouseReleaseEvent is forwarded to that element.
  12483. \see mousePressEvent, mouseMoveEvent
  12484. */
  12485. void QCustomPlot::mouseReleaseEvent(QMouseEvent *event)
  12486. {
  12487. emit mouseRelease(event);
  12488. if (!mMouseHasMoved) // mouse hasn't moved (much) between press and release, so handle as click
  12489. {
  12490. if (mSelectionRect && mSelectionRect->isActive()) // a simple click shouldn't successfully finish a selection rect, so cancel it here
  12491. mSelectionRect->cancel();
  12492. if (event->button() == Qt::LeftButton)
  12493. processPointSelection(event);
  12494. // emit specialized click signals of QCustomPlot instance:
  12495. if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(mMouseSignalLayerable))
  12496. {
  12497. int dataIndex = 0;
  12498. if (!mMouseSignalLayerableDetails.value<QCPDataSelection>().isEmpty())
  12499. dataIndex = mMouseSignalLayerableDetails.value<QCPDataSelection>().dataRange().begin();
  12500. emit plottableClick(ap, dataIndex, event);
  12501. } else if (QCPAxis *ax = qobject_cast<QCPAxis*>(mMouseSignalLayerable))
  12502. emit axisClick(ax, mMouseSignalLayerableDetails.value<QCPAxis::SelectablePart>(), event);
  12503. else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(mMouseSignalLayerable))
  12504. emit itemClick(ai, event);
  12505. else if (QCPLegend *lg = qobject_cast<QCPLegend*>(mMouseSignalLayerable))
  12506. emit legendClick(lg, 0, event);
  12507. else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(mMouseSignalLayerable))
  12508. emit legendClick(li->parentLegend(), li, event);
  12509. mMouseSignalLayerable = 0;
  12510. }
  12511. if (mSelectionRect && mSelectionRect->isActive()) // Note: if a click was detected above, the selection rect is canceled there
  12512. {
  12513. // finish selection rect, the appropriate action will be taken via signal-slot connection:
  12514. mSelectionRect->endSelection(event);
  12515. } else
  12516. {
  12517. // call event of affected layerable:
  12518. if (mMouseEventLayerable)
  12519. {
  12520. mMouseEventLayerable->mouseReleaseEvent(event, mMousePressPos);
  12521. mMouseEventLayerable = 0;
  12522. }
  12523. }
  12524. if (noAntialiasingOnDrag())
  12525. replot(rpQueuedReplot);
  12526. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  12527. }
  12528. /*! \internal
  12529. Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then
  12530. determines the affected layerable and forwards the event to it.
  12531. */
  12532. void QCustomPlot::wheelEvent(QWheelEvent *event)
  12533. {
  12534. emit mouseWheel(event);
  12535. // forward event to layerable under cursor:
  12536. QList<QCPLayerable*> candidates = layerableListAt(event->pos(), false);
  12537. for (int i=0; i<candidates.size(); ++i)
  12538. {
  12539. event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
  12540. candidates.at(i)->wheelEvent(event);
  12541. if (event->isAccepted())
  12542. break;
  12543. }
  12544. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  12545. }
  12546. /*! \internal
  12547. This function draws the entire plot, including background pixmap, with the specified \a painter.
  12548. It does not make use of the paint buffers like \ref replot, so this is the function typically
  12549. used by saving/exporting methods such as \ref savePdf or \ref toPainter.
  12550. Note that it does not fill the background with the background brush (as the user may specify with
  12551. \ref setBackground(const QBrush &brush)), this is up to the respective functions calling this
  12552. method.
  12553. */
  12554. void QCustomPlot::draw(QCPPainter *painter)
  12555. {
  12556. updateLayout();
  12557. // draw viewport background pixmap:
  12558. drawBackground(painter);
  12559. // draw all layered objects (grid, axes, plottables, items, legend,...):
  12560. foreach (QCPLayer *layer, mLayers)
  12561. layer->draw(painter);
  12562. /* Debug code to draw all layout element rects
  12563. foreach (QCPLayoutElement* el, findChildren<QCPLayoutElement*>())
  12564. {
  12565. painter->setBrush(Qt::NoBrush);
  12566. painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine));
  12567. painter->drawRect(el->rect());
  12568. painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine));
  12569. painter->drawRect(el->outerRect());
  12570. }
  12571. */
  12572. }
  12573. /*! \internal
  12574. Performs the layout update steps defined by \ref QCPLayoutElement::UpdatePhase, by calling \ref
  12575. QCPLayoutElement::update on the main plot layout.
  12576. Here, the layout elements calculate their positions and margins, and prepare for the following
  12577. draw call.
  12578. */
  12579. void QCustomPlot::updateLayout()
  12580. {
  12581. // run through layout phases:
  12582. mPlotLayout->update(QCPLayoutElement::upPreparation);
  12583. mPlotLayout->update(QCPLayoutElement::upMargins);
  12584. mPlotLayout->update(QCPLayoutElement::upLayout);
  12585. }
  12586. /*! \internal
  12587. Draws the viewport background pixmap of the plot.
  12588. If a pixmap was provided via \ref setBackground, this function buffers the scaled version
  12589. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  12590. the viewport with the provided \a painter. The scaled version is buffered in
  12591. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  12592. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  12593. dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
  12594. set.
  12595. Note that this function does not draw a fill with the background brush
  12596. (\ref setBackground(const QBrush &brush)) beneath the pixmap.
  12597. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  12598. */
  12599. void QCustomPlot::drawBackground(QCPPainter *painter)
  12600. {
  12601. // Note: background color is handled in individual replot/save functions
  12602. // draw background pixmap (on top of fill, if brush specified):
  12603. if (!mBackgroundPixmap.isNull())
  12604. {
  12605. if (mBackgroundScaled)
  12606. {
  12607. // check whether mScaledBackground needs to be updated:
  12608. QSize scaledSize(mBackgroundPixmap.size());
  12609. scaledSize.scale(mViewport.size(), mBackgroundScaledMode);
  12610. if (mScaledBackgroundPixmap.size() != scaledSize)
  12611. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
  12612. painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect());
  12613. } else
  12614. {
  12615. painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()));
  12616. }
  12617. }
  12618. }
  12619. /*! \internal
  12620. Goes through the layers and makes sure this QCustomPlot instance holds the correct number of
  12621. paint buffers and that they have the correct configuration (size, pixel ratio, etc.).
  12622. Allocations, reallocations and deletions of paint buffers are performed as necessary. It also
  12623. associates the paint buffers with the layers, so they draw themselves into the right buffer when
  12624. \ref QCPLayer::drawToPaintBuffer is called. This means it associates adjacent \ref
  12625. QCPLayer::lmLogical layers to a mutual paint buffer and creates dedicated paint buffers for
  12626. layers in \ref QCPLayer::lmBuffered mode.
  12627. This method uses \ref createPaintBuffer to create new paint buffers.
  12628. After this method, the paint buffers are empty (filled with \c Qt::transparent) and invalidated
  12629. (so an attempt to replot only a single buffered layer causes a full replot).
  12630. This method is called in every \ref replot call, prior to actually drawing the layers (into their
  12631. associated paint buffer). If the paint buffers don't need changing/reallocating, this method
  12632. basically leaves them alone and thus finishes very fast.
  12633. */
  12634. void QCustomPlot::setupPaintBuffers()
  12635. {
  12636. int bufferIndex = 0;
  12637. if (mPaintBuffers.isEmpty())
  12638. mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
  12639. for (int layerIndex = 0; layerIndex < mLayers.size(); ++layerIndex)
  12640. {
  12641. QCPLayer *layer = mLayers.at(layerIndex);
  12642. if (layer->mode() == QCPLayer::lmLogical)
  12643. {
  12644. layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef();
  12645. } else if (layer->mode() == QCPLayer::lmBuffered)
  12646. {
  12647. ++bufferIndex;
  12648. if (bufferIndex >= mPaintBuffers.size())
  12649. mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
  12650. layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef();
  12651. 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
  12652. {
  12653. ++bufferIndex;
  12654. if (bufferIndex >= mPaintBuffers.size())
  12655. mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
  12656. }
  12657. }
  12658. }
  12659. // remove unneeded buffers:
  12660. while (mPaintBuffers.size()-1 > bufferIndex)
  12661. mPaintBuffers.removeLast();
  12662. // resize buffers to viewport size and clear contents:
  12663. for (int i=0; i<mPaintBuffers.size(); ++i)
  12664. {
  12665. mPaintBuffers.at(i)->setSize(viewport().size()); // won't do anything if already correct size
  12666. mPaintBuffers.at(i)->clear(Qt::transparent);
  12667. mPaintBuffers.at(i)->setInvalidated();
  12668. }
  12669. }
  12670. /*! \internal
  12671. This method is used by \ref setupPaintBuffers when it needs to create new paint buffers.
  12672. Depending on the current setting of \ref setOpenGl, and the current Qt version, different
  12673. backends (subclasses of \ref QCPAbstractPaintBuffer) are created, initialized with the proper
  12674. size and device pixel ratio, and returned.
  12675. */
  12676. QCPAbstractPaintBuffer *QCustomPlot::createPaintBuffer()
  12677. {
  12678. if (mOpenGl)
  12679. {
  12680. #if defined(QCP_OPENGL_FBO)
  12681. return new QCPPaintBufferGlFbo(viewport().size(), mBufferDevicePixelRatio, mGlContext, mGlPaintDevice);
  12682. #elif defined(QCP_OPENGL_PBUFFER)
  12683. return new QCPPaintBufferGlPbuffer(viewport().size(), mBufferDevicePixelRatio, mOpenGlMultisamples);
  12684. #else
  12685. 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.";
  12686. return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio);
  12687. #endif
  12688. } else
  12689. return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio);
  12690. }
  12691. /*!
  12692. This method returns whether any of the paint buffers held by this QCustomPlot instance are
  12693. invalidated.
  12694. If any buffer is invalidated, a partial replot (\ref QCPLayer::replot) is not allowed and always
  12695. causes a full replot (\ref QCustomPlot::replot) of all layers. This is the case when for example
  12696. the layer order has changed, new layers were added, layers were removed, or layer modes were
  12697. changed (\ref QCPLayer::setMode).
  12698. \see QCPAbstractPaintBuffer::setInvalidated
  12699. */
  12700. bool QCustomPlot::hasInvalidatedPaintBuffers()
  12701. {
  12702. for (int i=0; i<mPaintBuffers.size(); ++i)
  12703. {
  12704. if (mPaintBuffers.at(i)->invalidated())
  12705. return true;
  12706. }
  12707. return false;
  12708. }
  12709. /*! \internal
  12710. When \ref setOpenGl is set to true, this method is used to initialize OpenGL (create a context,
  12711. surface, paint device).
  12712. Returns true on success.
  12713. If this method is successful, all paint buffers should be deleted and then reallocated by calling
  12714. \ref setupPaintBuffers, so the OpenGL-based paint buffer subclasses (\ref
  12715. QCPPaintBufferGlPbuffer, \ref QCPPaintBufferGlFbo) are used for subsequent replots.
  12716. \see freeOpenGl
  12717. */
  12718. bool QCustomPlot::setupOpenGl()
  12719. {
  12720. #ifdef QCP_OPENGL_FBO
  12721. freeOpenGl();
  12722. QSurfaceFormat proposedSurfaceFormat;
  12723. proposedSurfaceFormat.setSamples(mOpenGlMultisamples);
  12724. #ifdef QCP_OPENGL_OFFSCREENSURFACE
  12725. QOffscreenSurface *surface = new QOffscreenSurface;
  12726. #else
  12727. QWindow *surface = new QWindow;
  12728. surface->setSurfaceType(QSurface::OpenGLSurface);
  12729. #endif
  12730. surface->setFormat(proposedSurfaceFormat);
  12731. surface->create();
  12732. mGlSurface = QSharedPointer<QSurface>(surface);
  12733. mGlContext = QSharedPointer<QOpenGLContext>(new QOpenGLContext);
  12734. mGlContext->setFormat(mGlSurface->format());
  12735. if (!mGlContext->create())
  12736. {
  12737. qDebug() << Q_FUNC_INFO << "Failed to create OpenGL context";
  12738. mGlContext.clear();
  12739. mGlSurface.clear();
  12740. return false;
  12741. }
  12742. if (!mGlContext->makeCurrent(mGlSurface.data())) // context needs to be current to create paint device
  12743. {
  12744. qDebug() << Q_FUNC_INFO << "Failed to make opengl context current";
  12745. mGlContext.clear();
  12746. mGlSurface.clear();
  12747. return false;
  12748. }
  12749. if (!QOpenGLFramebufferObject::hasOpenGLFramebufferObjects())
  12750. {
  12751. qDebug() << Q_FUNC_INFO << "OpenGL of this system doesn't support frame buffer objects";
  12752. mGlContext.clear();
  12753. mGlSurface.clear();
  12754. return false;
  12755. }
  12756. mGlPaintDevice = QSharedPointer<QOpenGLPaintDevice>(new QOpenGLPaintDevice);
  12757. return true;
  12758. #elif defined(QCP_OPENGL_PBUFFER)
  12759. return QGLFormat::hasOpenGL();
  12760. #else
  12761. return false;
  12762. #endif
  12763. }
  12764. /*! \internal
  12765. When \ref setOpenGl is set to false, this method is used to deinitialize OpenGL (releases the
  12766. context and frees resources).
  12767. After OpenGL is disabled, all paint buffers should be deleted and then reallocated by calling
  12768. \ref setupPaintBuffers, so the standard software rendering paint buffer subclass (\ref
  12769. QCPPaintBufferPixmap) is used for subsequent replots.
  12770. \see setupOpenGl
  12771. */
  12772. void QCustomPlot::freeOpenGl()
  12773. {
  12774. #ifdef QCP_OPENGL_FBO
  12775. mGlPaintDevice.clear();
  12776. mGlContext.clear();
  12777. mGlSurface.clear();
  12778. #endif
  12779. }
  12780. /*! \internal
  12781. This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot
  12782. so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly.
  12783. */
  12784. void QCustomPlot::axisRemoved(QCPAxis *axis)
  12785. {
  12786. if (xAxis == axis)
  12787. xAxis = 0;
  12788. if (xAxis2 == axis)
  12789. xAxis2 = 0;
  12790. if (yAxis == axis)
  12791. yAxis = 0;
  12792. if (yAxis2 == axis)
  12793. yAxis2 = 0;
  12794. // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers
  12795. }
  12796. /*! \internal
  12797. This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so
  12798. it may clear its QCustomPlot::legend member accordingly.
  12799. */
  12800. void QCustomPlot::legendRemoved(QCPLegend *legend)
  12801. {
  12802. if (this->legend == legend)
  12803. this->legend = 0;
  12804. }
  12805. /*! \internal
  12806. This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref
  12807. setSelectionRectMode is set to \ref QCP::srmSelect.
  12808. First, it determines which axis rect was the origin of the selection rect judging by the starting
  12809. point of the selection. Then it goes through the plottables (\ref QCPAbstractPlottable1D to be
  12810. precise) associated with that axis rect and finds the data points that are in \a rect. It does
  12811. this by querying their \ref QCPAbstractPlottable1D::selectTestRect method.
  12812. Then, the actual selection is done by calling the plottables' \ref
  12813. QCPAbstractPlottable::selectEvent, placing the found selected data points in the \a details
  12814. parameter as <tt>QVariant(\ref QCPDataSelection)</tt>. All plottables that weren't touched by \a
  12815. rect receive a \ref QCPAbstractPlottable::deselectEvent.
  12816. \see processRectZoom
  12817. */
  12818. void QCustomPlot::processRectSelection(QRect rect, QMouseEvent *event)
  12819. {
  12820. bool selectionStateChanged = false;
  12821. if (mInteractions.testFlag(QCP::iSelectPlottables))
  12822. {
  12823. QMap<int, QPair<QCPAbstractPlottable*, QCPDataSelection> > potentialSelections; // map key is number of selected data points, so we have selections sorted by size
  12824. QRectF rectF(rect.normalized());
  12825. if (QCPAxisRect *affectedAxisRect = axisRectAt(rectF.topLeft()))
  12826. {
  12827. // determine plottables that were hit by the rect and thus are candidates for selection:
  12828. foreach (QCPAbstractPlottable *plottable, affectedAxisRect->plottables())
  12829. {
  12830. if (QCPPlottableInterface1D *plottableInterface = plottable->interface1D())
  12831. {
  12832. QCPDataSelection dataSel = plottableInterface->selectTestRect(rectF, true);
  12833. if (!dataSel.isEmpty())
  12834. potentialSelections.insertMulti(dataSel.dataPointCount(), QPair<QCPAbstractPlottable*, QCPDataSelection>(plottable, dataSel));
  12835. }
  12836. }
  12837. if (!mInteractions.testFlag(QCP::iMultiSelect))
  12838. {
  12839. // only leave plottable with most selected points in map, since we will only select a single plottable:
  12840. if (!potentialSelections.isEmpty())
  12841. {
  12842. QMap<int, QPair<QCPAbstractPlottable*, QCPDataSelection> >::iterator it = potentialSelections.begin();
  12843. while (it != potentialSelections.end()-1) // erase all except last element
  12844. it = potentialSelections.erase(it);
  12845. }
  12846. }
  12847. bool additive = event->modifiers().testFlag(mMultiSelectModifier);
  12848. // deselect all other layerables if not additive selection:
  12849. if (!additive)
  12850. {
  12851. // emit deselection except to those plottables who will be selected afterwards:
  12852. foreach (QCPLayer *layer, mLayers)
  12853. {
  12854. foreach (QCPLayerable *layerable, layer->children())
  12855. {
  12856. if ((potentialSelections.isEmpty() || potentialSelections.constBegin()->first != layerable) && mInteractions.testFlag(layerable->selectionCategory()))
  12857. {
  12858. bool selChanged = false;
  12859. layerable->deselectEvent(&selChanged);
  12860. selectionStateChanged |= selChanged;
  12861. }
  12862. }
  12863. }
  12864. }
  12865. // go through selections in reverse (largest selection first) and emit select events:
  12866. QMap<int, QPair<QCPAbstractPlottable*, QCPDataSelection> >::const_iterator it = potentialSelections.constEnd();
  12867. while (it != potentialSelections.constBegin())
  12868. {
  12869. --it;
  12870. if (mInteractions.testFlag(it.value().first->selectionCategory()))
  12871. {
  12872. bool selChanged = false;
  12873. it.value().first->selectEvent(event, additive, QVariant::fromValue(it.value().second), &selChanged);
  12874. selectionStateChanged |= selChanged;
  12875. }
  12876. }
  12877. }
  12878. }
  12879. if (selectionStateChanged)
  12880. {
  12881. emit selectionChangedByUser();
  12882. replot(rpQueuedReplot);
  12883. } else if (mSelectionRect)
  12884. mSelectionRect->layer()->replot();
  12885. }
  12886. /*! \internal
  12887. This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref
  12888. setSelectionRectMode is set to \ref QCP::srmZoom.
  12889. It determines which axis rect was the origin of the selection rect judging by the starting point
  12890. of the selection, and then zooms the axes defined via \ref QCPAxisRect::setRangeZoomAxes to the
  12891. provided \a rect (see \ref QCPAxisRect::zoom).
  12892. \see processRectSelection
  12893. */
  12894. void QCustomPlot::processRectZoom(QRect rect, QMouseEvent *event)
  12895. {
  12896. Q_UNUSED(event)
  12897. if (QCPAxisRect *axisRect = axisRectAt(rect.topLeft()))
  12898. {
  12899. QList<QCPAxis*> affectedAxes = QList<QCPAxis*>() << axisRect->rangeZoomAxes(Qt::Horizontal) << axisRect->rangeZoomAxes(Qt::Vertical);
  12900. affectedAxes.removeAll(static_cast<QCPAxis*>(0));
  12901. axisRect->zoom(QRectF(rect), affectedAxes);
  12902. }
  12903. replot(rpQueuedReplot); // always replot to make selection rect disappear
  12904. }
  12905. /*! \internal
  12906. This method is called when a simple left mouse click was detected on the QCustomPlot surface.
  12907. It first determines the layerable that was hit by the click, and then calls its \ref
  12908. QCPLayerable::selectEvent. All other layerables receive a QCPLayerable::deselectEvent (unless the
  12909. multi-select modifier was pressed, see \ref setMultiSelectModifier).
  12910. In this method the hit layerable is determined a second time using \ref layerableAt (after the
  12911. one in \ref mousePressEvent), because we want \a onlySelectable set to true this time. This
  12912. implies that the mouse event grabber (mMouseEventLayerable) may be a different one from the
  12913. clicked layerable determined here. For example, if a non-selectable layerable is in front of a
  12914. selectable layerable at the click position, the front layerable will receive mouse events but the
  12915. selectable one in the back will receive the \ref QCPLayerable::selectEvent.
  12916. \see processRectSelection, QCPLayerable::selectTest
  12917. */
  12918. void QCustomPlot::processPointSelection(QMouseEvent *event)
  12919. {
  12920. QVariant details;
  12921. QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details);
  12922. bool selectionStateChanged = false;
  12923. bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier);
  12924. // deselect all other layerables if not additive selection:
  12925. if (!additive)
  12926. {
  12927. foreach (QCPLayer *layer, mLayers)
  12928. {
  12929. foreach (QCPLayerable *layerable, layer->children())
  12930. {
  12931. if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory()))
  12932. {
  12933. bool selChanged = false;
  12934. layerable->deselectEvent(&selChanged);
  12935. selectionStateChanged |= selChanged;
  12936. }
  12937. }
  12938. }
  12939. }
  12940. if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory()))
  12941. {
  12942. // a layerable was actually clicked, call its selectEvent:
  12943. bool selChanged = false;
  12944. clickedLayerable->selectEvent(event, additive, details, &selChanged);
  12945. selectionStateChanged |= selChanged;
  12946. }
  12947. if (selectionStateChanged)
  12948. {
  12949. emit selectionChangedByUser();
  12950. replot(rpQueuedReplot);
  12951. }
  12952. }
  12953. /*! \internal
  12954. Registers the specified plottable with this QCustomPlot and, if \ref setAutoAddPlottableToLegend
  12955. is enabled, adds it to the legend (QCustomPlot::legend). QCustomPlot takes ownership of the
  12956. plottable.
  12957. Returns true on success, i.e. when \a plottable isn't already in this plot and the parent plot of
  12958. \a plottable is this QCustomPlot.
  12959. This method is called automatically in the QCPAbstractPlottable base class constructor.
  12960. */
  12961. bool QCustomPlot::registerPlottable(QCPAbstractPlottable *plottable)
  12962. {
  12963. if (mPlottables.contains(plottable))
  12964. {
  12965. qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast<quintptr>(plottable);
  12966. return false;
  12967. }
  12968. if (plottable->parentPlot() != this)
  12969. {
  12970. qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(plottable);
  12971. return false;
  12972. }
  12973. mPlottables.append(plottable);
  12974. // possibly add plottable to legend:
  12975. if (mAutoAddPlottableToLegend)
  12976. plottable->addToLegend();
  12977. if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
  12978. plottable->setLayer(currentLayer());
  12979. return true;
  12980. }
  12981. /*! \internal
  12982. In order to maintain the simplified graph interface of QCustomPlot, this method is called by the
  12983. QCPGraph constructor to register itself with this QCustomPlot's internal graph list. Returns true
  12984. on success, i.e. if \a graph is valid and wasn't already registered with this QCustomPlot.
  12985. This graph specific registration happens in addition to the call to \ref registerPlottable by the
  12986. QCPAbstractPlottable base class.
  12987. */
  12988. bool QCustomPlot::registerGraph(QCPGraph *graph)
  12989. {
  12990. if (!graph)
  12991. {
  12992. qDebug() << Q_FUNC_INFO << "passed graph is zero";
  12993. return false;
  12994. }
  12995. if (mGraphs.contains(graph))
  12996. {
  12997. qDebug() << Q_FUNC_INFO << "graph already registered with this QCustomPlot";
  12998. return false;
  12999. }
  13000. mGraphs.append(graph);
  13001. return true;
  13002. }
  13003. /*! \internal
  13004. Registers the specified item with this QCustomPlot. QCustomPlot takes ownership of the item.
  13005. Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a
  13006. item is this QCustomPlot.
  13007. This method is called automatically in the QCPAbstractItem base class constructor.
  13008. */
  13009. bool QCustomPlot::registerItem(QCPAbstractItem *item)
  13010. {
  13011. if (mItems.contains(item))
  13012. {
  13013. qDebug() << Q_FUNC_INFO << "item already added to this QCustomPlot:" << reinterpret_cast<quintptr>(item);
  13014. return false;
  13015. }
  13016. if (item->parentPlot() != this)
  13017. {
  13018. qDebug() << Q_FUNC_INFO << "item not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(item);
  13019. return false;
  13020. }
  13021. mItems.append(item);
  13022. if (!item->layer()) // usually the layer is already set in the constructor of the item (via QCPLayerable constructor)
  13023. item->setLayer(currentLayer());
  13024. return true;
  13025. }
  13026. /*! \internal
  13027. Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called
  13028. after every operation that changes the layer indices, like layer removal, layer creation, layer
  13029. moving.
  13030. */
  13031. void QCustomPlot::updateLayerIndices() const
  13032. {
  13033. for (int i=0; i<mLayers.size(); ++i)
  13034. mLayers.at(i)->mIndex = i;
  13035. }
  13036. /*! \internal
  13037. Returns the top-most layerable at pixel position \a pos. If \a onlySelectable is set to true,
  13038. only those layerables that are selectable will be considered. (Layerable subclasses communicate
  13039. their selectability via the QCPLayerable::selectTest method, by returning -1.)
  13040. \a selectionDetails is an output parameter that contains selection specifics of the affected
  13041. layerable. This is useful if the respective layerable shall be given a subsequent
  13042. QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
  13043. information about which part of the layerable was hit, in multi-part layerables (e.g.
  13044. QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref
  13045. QCPDataSelection instance with the single data point which is closest to \a pos.
  13046. \see layerableListAt, layoutElementAt, axisRectAt
  13047. */
  13048. QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const
  13049. {
  13050. QList<QVariant> details;
  13051. QList<QCPLayerable*> candidates = layerableListAt(pos, onlySelectable, selectionDetails ? &details : 0);
  13052. if (selectionDetails && !details.isEmpty())
  13053. *selectionDetails = details.first();
  13054. if (!candidates.isEmpty())
  13055. return candidates.first();
  13056. else
  13057. return 0;
  13058. }
  13059. /*! \internal
  13060. Returns the layerables at pixel position \a pos. If \a onlySelectable is set to true, only those
  13061. layerables that are selectable will be considered. (Layerable subclasses communicate their
  13062. selectability via the QCPLayerable::selectTest method, by returning -1.)
  13063. The returned list is sorted by the layerable/drawing order. If you only need to know the top-most
  13064. layerable, rather use \ref layerableAt.
  13065. \a selectionDetails is an output parameter that contains selection specifics of the affected
  13066. layerable. This is useful if the respective layerable shall be given a subsequent
  13067. QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
  13068. information about which part of the layerable was hit, in multi-part layerables (e.g.
  13069. QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref
  13070. QCPDataSelection instance with the single data point which is closest to \a pos.
  13071. \see layerableAt, layoutElementAt, axisRectAt
  13072. */
  13073. QList<QCPLayerable*> QCustomPlot::layerableListAt(const QPointF &pos, bool onlySelectable, QList<QVariant> *selectionDetails) const
  13074. {
  13075. QList<QCPLayerable*> result;
  13076. for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex)
  13077. {
  13078. const QList<QCPLayerable*> layerables = mLayers.at(layerIndex)->children();
  13079. for (int i=layerables.size()-1; i>=0; --i)
  13080. {
  13081. if (!layerables.at(i)->realVisibility())
  13082. continue;
  13083. QVariant details;
  13084. double dist = layerables.at(i)->selectTest(pos, onlySelectable, selectionDetails ? &details : 0);
  13085. if (dist >= 0 && dist < selectionTolerance())
  13086. {
  13087. result.append(layerables.at(i));
  13088. if (selectionDetails)
  13089. selectionDetails->append(details);
  13090. }
  13091. }
  13092. }
  13093. return result;
  13094. }
  13095. /*!
  13096. Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is
  13097. sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead
  13098. to a full resolution file with width 200.) If the \a format supports compression, \a quality may
  13099. be between 0 and 100 to control it.
  13100. Returns true on success. If this function fails, most likely the given \a format isn't supported
  13101. by the system, see Qt docs about QImageWriter::supportedImageFormats().
  13102. The \a resolution will be written to the image file header (if the file format supports this) and
  13103. has no direct consequence for the quality or the pixel size. However, if opening the image with a
  13104. tool which respects the metadata, it will be able to scale the image to match either a given size
  13105. in real units of length (inch, centimeters, etc.), or the target display DPI. You can specify in
  13106. which units \a resolution is given, by setting \a resolutionUnit. The \a resolution is converted
  13107. to the format's expected resolution unit internally.
  13108. \see saveBmp, saveJpg, savePng, savePdf
  13109. */
  13110. bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
  13111. {
  13112. QImage buffer = toPixmap(width, height, scale).toImage();
  13113. int dotsPerMeter = 0;
  13114. switch (resolutionUnit)
  13115. {
  13116. case QCP::ruDotsPerMeter: dotsPerMeter = resolution; break;
  13117. case QCP::ruDotsPerCentimeter: dotsPerMeter = resolution*100; break;
  13118. case QCP::ruDotsPerInch: dotsPerMeter = resolution/0.0254; break;
  13119. }
  13120. buffer.setDotsPerMeterX(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools
  13121. buffer.setDotsPerMeterY(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools
  13122. if (!buffer.isNull())
  13123. return buffer.save(fileName, format, quality);
  13124. else
  13125. return false;
  13126. }
  13127. /*!
  13128. Renders the plot to a pixmap and returns it.
  13129. The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and
  13130. scale 2.0 lead to a full resolution pixmap with width 200.)
  13131. \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf
  13132. */
  13133. QPixmap QCustomPlot::toPixmap(int width, int height, double scale)
  13134. {
  13135. // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too.
  13136. int newWidth, newHeight;
  13137. if (width == 0 || height == 0)
  13138. {
  13139. newWidth = this->width();
  13140. newHeight = this->height();
  13141. } else
  13142. {
  13143. newWidth = width;
  13144. newHeight = height;
  13145. }
  13146. int scaledWidth = qRound(scale*newWidth);
  13147. int scaledHeight = qRound(scale*newHeight);
  13148. QPixmap result(scaledWidth, scaledHeight);
  13149. result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later
  13150. QCPPainter painter;
  13151. painter.begin(&result);
  13152. if (painter.isActive())
  13153. {
  13154. QRect oldViewport = viewport();
  13155. setViewport(QRect(0, 0, newWidth, newHeight));
  13156. painter.setMode(QCPPainter::pmNoCaching);
  13157. if (!qFuzzyCompare(scale, 1.0))
  13158. {
  13159. if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales
  13160. painter.setMode(QCPPainter::pmNonCosmetic);
  13161. painter.scale(scale, scale);
  13162. }
  13163. if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) // solid fills were done a few lines above with QPixmap::fill
  13164. painter.fillRect(mViewport, mBackgroundBrush);
  13165. draw(&painter);
  13166. setViewport(oldViewport);
  13167. painter.end();
  13168. } else // might happen if pixmap has width or height zero
  13169. {
  13170. qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap";
  13171. return QPixmap();
  13172. }
  13173. return result;
  13174. }
  13175. /*!
  13176. Renders the plot using the passed \a painter.
  13177. 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
  13178. appear scaled accordingly.
  13179. \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter
  13180. on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with
  13181. the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter.
  13182. \see toPixmap
  13183. */
  13184. void QCustomPlot::toPainter(QCPPainter *painter, int width, int height)
  13185. {
  13186. // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too.
  13187. int newWidth, newHeight;
  13188. if (width == 0 || height == 0)
  13189. {
  13190. newWidth = this->width();
  13191. newHeight = this->height();
  13192. } else
  13193. {
  13194. newWidth = width;
  13195. newHeight = height;
  13196. }
  13197. if (painter->isActive())
  13198. {
  13199. QRect oldViewport = viewport();
  13200. setViewport(QRect(0, 0, newWidth, newHeight));
  13201. painter->setMode(QCPPainter::pmNoCaching);
  13202. 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
  13203. painter->fillRect(mViewport, mBackgroundBrush);
  13204. draw(painter);
  13205. setViewport(oldViewport);
  13206. } else
  13207. qDebug() << Q_FUNC_INFO << "Passed painter is not active";
  13208. }
  13209. /* end of 'src/core.cpp' */
  13210. //amalgamation: add plottable1d.cpp
  13211. /* including file 'src/colorgradient.cpp', size 24646 */
  13212. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  13213. ////////////////////////////////////////////////////////////////////////////////////////////////////
  13214. //////////////////// QCPColorGradient
  13215. ////////////////////////////////////////////////////////////////////////////////////////////////////
  13216. /*! \class QCPColorGradient
  13217. \brief Defines a color gradient for use with e.g. \ref QCPColorMap
  13218. This class describes a color gradient which can be used to encode data with color. For example,
  13219. QCPColorMap and QCPColorScale have \ref QCPColorMap::setGradient "setGradient" methods which
  13220. take an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color)
  13221. with a \a position from 0 to 1. In between these defined color positions, the
  13222. color will be interpolated linearly either in RGB or HSV space, see \ref setColorInterpolation.
  13223. Alternatively, load one of the preset color gradients shown in the image below, with \ref
  13224. loadPreset, or by directly specifying the preset in the constructor.
  13225. Apart from red, green and blue components, the gradient also interpolates the alpha values of the
  13226. configured color stops. This allows to display some portions of the data range as transparent in
  13227. the plot.
  13228. \image html QCPColorGradient.png
  13229. The \ref QCPColorGradient(GradientPreset preset) constructor allows directly converting a \ref
  13230. GradientPreset to a QCPColorGradient. This means that you can directly pass \ref GradientPreset
  13231. to all the \a setGradient methods, e.g.:
  13232. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorgradient-setgradient
  13233. The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the
  13234. color gradient shall be applied periodically (wrapping around) to data values that lie outside
  13235. the data range specified on the plottable instance can be controlled with \ref setPeriodic.
  13236. */
  13237. /*!
  13238. Constructs a new, empty QCPColorGradient with no predefined color stops. You can add own color
  13239. stops with \ref setColorStopAt.
  13240. The color level count is initialized to 350.
  13241. */
  13242. QCPColorGradient::QCPColorGradient() :
  13243. mLevelCount(350),
  13244. mColorInterpolation(ciRGB),
  13245. mPeriodic(false),
  13246. mColorBufferInvalidated(true)
  13247. {
  13248. mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
  13249. }
  13250. /*!
  13251. Constructs a new QCPColorGradient initialized with the colors and color interpolation according
  13252. to \a preset.
  13253. The color level count is initialized to 350.
  13254. */
  13255. QCPColorGradient::QCPColorGradient(GradientPreset preset) :
  13256. mLevelCount(350),
  13257. mColorInterpolation(ciRGB),
  13258. mPeriodic(false),
  13259. mColorBufferInvalidated(true)
  13260. {
  13261. mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
  13262. loadPreset(preset);
  13263. }
  13264. /* undocumented operator */
  13265. bool QCPColorGradient::operator==(const QCPColorGradient &other) const
  13266. {
  13267. return ((other.mLevelCount == this->mLevelCount) &&
  13268. (other.mColorInterpolation == this->mColorInterpolation) &&
  13269. (other.mPeriodic == this->mPeriodic) &&
  13270. (other.mColorStops == this->mColorStops));
  13271. }
  13272. /*!
  13273. Sets the number of discretization levels of the color gradient to \a n. The default is 350 which
  13274. is typically enough to create a smooth appearance. The minimum number of levels is 2.
  13275. \image html QCPColorGradient-levelcount.png
  13276. */
  13277. void QCPColorGradient::setLevelCount(int n)
  13278. {
  13279. if (n < 2)
  13280. {
  13281. qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n;
  13282. n = 2;
  13283. }
  13284. if (n != mLevelCount)
  13285. {
  13286. mLevelCount = n;
  13287. mColorBufferInvalidated = true;
  13288. }
  13289. }
  13290. /*!
  13291. Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the
  13292. colors are the values of the passed QMap \a colorStops. In between these color stops, the color
  13293. is interpolated according to \ref setColorInterpolation.
  13294. A more convenient way to create a custom gradient may be to clear all color stops with \ref
  13295. clearColorStops (or creating a new, empty QCPColorGradient) and then adding them one by one with
  13296. \ref setColorStopAt.
  13297. \see clearColorStops
  13298. */
  13299. void QCPColorGradient::setColorStops(const QMap<double, QColor> &colorStops)
  13300. {
  13301. mColorStops = colorStops;
  13302. mColorBufferInvalidated = true;
  13303. }
  13304. /*!
  13305. Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between
  13306. these color stops, the color is interpolated according to \ref setColorInterpolation.
  13307. \see setColorStops, clearColorStops
  13308. */
  13309. void QCPColorGradient::setColorStopAt(double position, const QColor &color)
  13310. {
  13311. mColorStops.insert(position, color);
  13312. mColorBufferInvalidated = true;
  13313. }
  13314. /*!
  13315. Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be
  13316. interpolated linearly in RGB or in HSV color space.
  13317. For example, a sweep in RGB space from red to green will have a muddy brown intermediate color,
  13318. whereas in HSV space the intermediate color is yellow.
  13319. */
  13320. void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation)
  13321. {
  13322. if (interpolation != mColorInterpolation)
  13323. {
  13324. mColorInterpolation = interpolation;
  13325. mColorBufferInvalidated = true;
  13326. }
  13327. }
  13328. /*!
  13329. Sets whether data points that are outside the configured data range (e.g. \ref
  13330. QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether
  13331. they all have the same color, corresponding to the respective gradient boundary color.
  13332. \image html QCPColorGradient-periodic.png
  13333. As shown in the image above, gradients that have the same start and end color are especially
  13334. suitable for a periodic gradient mapping, since they produce smooth color transitions throughout
  13335. the color map. A preset that has this property is \ref gpHues.
  13336. In practice, using periodic color gradients makes sense when the data corresponds to a periodic
  13337. dimension, such as an angle or a phase. If this is not the case, the color encoding might become
  13338. ambiguous, because multiple different data values are shown as the same color.
  13339. */
  13340. void QCPColorGradient::setPeriodic(bool enabled)
  13341. {
  13342. mPeriodic = enabled;
  13343. }
  13344. /*! \overload
  13345. This method is used to quickly convert a \a data array to colors. The colors will be output in
  13346. the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this
  13347. function. The data range that shall be used for mapping the data value to the gradient is passed
  13348. in \a range. \a logarithmic indicates whether the data values shall be mapped to colors
  13349. logarithmically.
  13350. if \a data actually contains 2D-data linearized via <tt>[row*columnCount + column]</tt>, you can
  13351. set \a dataIndexFactor to <tt>columnCount</tt> to convert a column instead of a row of the data
  13352. array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data
  13353. is addressed <tt>data[i*dataIndexFactor]</tt>.
  13354. Use the overloaded method to additionally provide alpha map data.
  13355. The QRgb values that are placed in \a scanLine have their r, g and b components premultiplied
  13356. with alpha (see QImage::Format_ARGB32_Premultiplied).
  13357. */
  13358. void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
  13359. {
  13360. // If you change something here, make sure to also adapt color() and the other colorize() overload
  13361. if (!data)
  13362. {
  13363. qDebug() << Q_FUNC_INFO << "null pointer given as data";
  13364. return;
  13365. }
  13366. if (!scanLine)
  13367. {
  13368. qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
  13369. return;
  13370. }
  13371. if (mColorBufferInvalidated)
  13372. updateColorBuffer();
  13373. if (!logarithmic)
  13374. {
  13375. const double posToIndexFactor = (mLevelCount-1)/range.size();
  13376. if (mPeriodic)
  13377. {
  13378. for (int i=0; i<n; ++i)
  13379. {
  13380. int index = (int)((data[dataIndexFactor*i]-range.lower)*posToIndexFactor) % mLevelCount;
  13381. if (index < 0)
  13382. index += mLevelCount;
  13383. scanLine[i] = mColorBuffer.at(index);
  13384. }
  13385. } else
  13386. {
  13387. for (int i=0; i<n; ++i)
  13388. {
  13389. int index = (data[dataIndexFactor*i]-range.lower)*posToIndexFactor;
  13390. if (index < 0)
  13391. index = 0;
  13392. else if (index >= mLevelCount)
  13393. index = mLevelCount-1;
  13394. scanLine[i] = mColorBuffer.at(index);
  13395. }
  13396. }
  13397. } else // logarithmic == true
  13398. {
  13399. if (mPeriodic)
  13400. {
  13401. for (int i=0; i<n; ++i)
  13402. {
  13403. int index = (int)(qLn(data[dataIndexFactor*i]/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1)) % mLevelCount;
  13404. if (index < 0)
  13405. index += mLevelCount;
  13406. scanLine[i] = mColorBuffer.at(index);
  13407. }
  13408. } else
  13409. {
  13410. for (int i=0; i<n; ++i)
  13411. {
  13412. int index = qLn(data[dataIndexFactor*i]/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1);
  13413. if (index < 0)
  13414. index = 0;
  13415. else if (index >= mLevelCount)
  13416. index = mLevelCount-1;
  13417. scanLine[i] = mColorBuffer.at(index);
  13418. }
  13419. }
  13420. }
  13421. }
  13422. /*! \overload
  13423. Additionally to the other overload of \ref colorize, this method takes the array \a alpha, which
  13424. has the same size and structure as \a data and encodes the alpha information per data point.
  13425. The QRgb values that are placed in \a scanLine have their r, g and b components premultiplied
  13426. with alpha (see QImage::Format_ARGB32_Premultiplied).
  13427. */
  13428. void QCPColorGradient::colorize(const double *data, const unsigned char *alpha, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
  13429. {
  13430. // If you change something here, make sure to also adapt color() and the other colorize() overload
  13431. if (!data)
  13432. {
  13433. qDebug() << Q_FUNC_INFO << "null pointer given as data";
  13434. return;
  13435. }
  13436. if (!alpha)
  13437. {
  13438. qDebug() << Q_FUNC_INFO << "null pointer given as alpha";
  13439. return;
  13440. }
  13441. if (!scanLine)
  13442. {
  13443. qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
  13444. return;
  13445. }
  13446. if (mColorBufferInvalidated)
  13447. updateColorBuffer();
  13448. if (!logarithmic)
  13449. {
  13450. const double posToIndexFactor = (mLevelCount-1)/range.size();
  13451. if (mPeriodic)
  13452. {
  13453. for (int i=0; i<n; ++i)
  13454. {
  13455. int index = (int)((data[dataIndexFactor*i]-range.lower)*posToIndexFactor) % mLevelCount;
  13456. if (index < 0)
  13457. index += mLevelCount;
  13458. if (alpha[dataIndexFactor*i] == 255)
  13459. {
  13460. scanLine[i] = mColorBuffer.at(index);
  13461. } else
  13462. {
  13463. const QRgb rgb = mColorBuffer.at(index);
  13464. const float alphaF = alpha[dataIndexFactor*i]/255.0f;
  13465. scanLine[i] = qRgba(qRed(rgb)*alphaF, qGreen(rgb)*alphaF, qBlue(rgb)*alphaF, qAlpha(rgb)*alphaF);
  13466. }
  13467. }
  13468. } else
  13469. {
  13470. for (int i=0; i<n; ++i)
  13471. {
  13472. int index = (data[dataIndexFactor*i]-range.lower)*posToIndexFactor;
  13473. if (index < 0)
  13474. index = 0;
  13475. else if (index >= mLevelCount)
  13476. index = mLevelCount-1;
  13477. if (alpha[dataIndexFactor*i] == 255)
  13478. {
  13479. scanLine[i] = mColorBuffer.at(index);
  13480. } else
  13481. {
  13482. const QRgb rgb = mColorBuffer.at(index);
  13483. const float alphaF = alpha[dataIndexFactor*i]/255.0f;
  13484. scanLine[i] = qRgba(qRed(rgb)*alphaF, qGreen(rgb)*alphaF, qBlue(rgb)*alphaF, qAlpha(rgb)*alphaF);
  13485. }
  13486. }
  13487. }
  13488. } else // logarithmic == true
  13489. {
  13490. if (mPeriodic)
  13491. {
  13492. for (int i=0; i<n; ++i)
  13493. {
  13494. int index = (int)(qLn(data[dataIndexFactor*i]/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1)) % mLevelCount;
  13495. if (index < 0)
  13496. index += mLevelCount;
  13497. if (alpha[dataIndexFactor*i] == 255)
  13498. {
  13499. scanLine[i] = mColorBuffer.at(index);
  13500. } else
  13501. {
  13502. const QRgb rgb = mColorBuffer.at(index);
  13503. const float alphaF = alpha[dataIndexFactor*i]/255.0f;
  13504. scanLine[i] = qRgba(qRed(rgb)*alphaF, qGreen(rgb)*alphaF, qBlue(rgb)*alphaF, qAlpha(rgb)*alphaF);
  13505. }
  13506. }
  13507. } else
  13508. {
  13509. for (int i=0; i<n; ++i)
  13510. {
  13511. int index = qLn(data[dataIndexFactor*i]/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1);
  13512. if (index < 0)
  13513. index = 0;
  13514. else if (index >= mLevelCount)
  13515. index = mLevelCount-1;
  13516. if (alpha[dataIndexFactor*i] == 255)
  13517. {
  13518. scanLine[i] = mColorBuffer.at(index);
  13519. } else
  13520. {
  13521. const QRgb rgb = mColorBuffer.at(index);
  13522. const float alphaF = alpha[dataIndexFactor*i]/255.0f;
  13523. scanLine[i] = qRgba(qRed(rgb)*alphaF, qGreen(rgb)*alphaF, qBlue(rgb)*alphaF, qAlpha(rgb)*alphaF);
  13524. }
  13525. }
  13526. }
  13527. }
  13528. }
  13529. /*! \internal
  13530. This method is used to colorize a single data value given in \a position, to colors. The data
  13531. range that shall be used for mapping the data value to the gradient is passed in \a range. \a
  13532. logarithmic indicates whether the data value shall be mapped to a color logarithmically.
  13533. If an entire array of data values shall be converted, rather use \ref colorize, for better
  13534. performance.
  13535. The returned QRgb has its r, g and b components premultiplied with alpha (see
  13536. QImage::Format_ARGB32_Premultiplied).
  13537. */
  13538. QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic)
  13539. {
  13540. // If you change something here, make sure to also adapt ::colorize()
  13541. if (mColorBufferInvalidated)
  13542. updateColorBuffer();
  13543. int index = 0;
  13544. if (!logarithmic)
  13545. index = (position-range.lower)*(mLevelCount-1)/range.size();
  13546. else
  13547. index = qLn(position/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1);
  13548. if (mPeriodic)
  13549. {
  13550. index = index % mLevelCount;
  13551. if (index < 0)
  13552. index += mLevelCount;
  13553. } else
  13554. {
  13555. if (index < 0)
  13556. index = 0;
  13557. else if (index >= mLevelCount)
  13558. index = mLevelCount-1;
  13559. }
  13560. return mColorBuffer.at(index);
  13561. }
  13562. /*!
  13563. Clears the current color stops and loads the specified \a preset. A preset consists of predefined
  13564. color stops and the corresponding color interpolation method.
  13565. The available presets are:
  13566. \image html QCPColorGradient.png
  13567. */
  13568. void QCPColorGradient::loadPreset(GradientPreset preset)
  13569. {
  13570. clearColorStops();
  13571. switch (preset)
  13572. {
  13573. case gpGrayscale:
  13574. setColorInterpolation(ciRGB);
  13575. setColorStopAt(0, Qt::black);
  13576. setColorStopAt(1, Qt::white);
  13577. break;
  13578. case gpHot:
  13579. setColorInterpolation(ciRGB);
  13580. setColorStopAt(0, QColor(50, 0, 0));
  13581. setColorStopAt(0.2, QColor(180, 10, 0));
  13582. setColorStopAt(0.4, QColor(245, 50, 0));
  13583. setColorStopAt(0.6, QColor(255, 150, 10));
  13584. setColorStopAt(0.8, QColor(255, 255, 50));
  13585. setColorStopAt(1, QColor(255, 255, 255));
  13586. break;
  13587. case gpCold:
  13588. setColorInterpolation(ciRGB);
  13589. setColorStopAt(0, QColor(0, 0, 50));
  13590. setColorStopAt(0.2, QColor(0, 10, 180));
  13591. setColorStopAt(0.4, QColor(0, 50, 245));
  13592. setColorStopAt(0.6, QColor(10, 150, 255));
  13593. setColorStopAt(0.8, QColor(50, 255, 255));
  13594. setColorStopAt(1, QColor(255, 255, 255));
  13595. break;
  13596. case gpNight:
  13597. setColorInterpolation(ciHSV);
  13598. setColorStopAt(0, QColor(10, 20, 30));
  13599. setColorStopAt(1, QColor(250, 255, 250));
  13600. break;
  13601. case gpCandy:
  13602. setColorInterpolation(ciHSV);
  13603. setColorStopAt(0, QColor(0, 0, 255));
  13604. setColorStopAt(1, QColor(255, 250, 250));
  13605. break;
  13606. case gpGeography:
  13607. setColorInterpolation(ciRGB);
  13608. setColorStopAt(0, QColor(70, 170, 210));
  13609. setColorStopAt(0.20, QColor(90, 160, 180));
  13610. setColorStopAt(0.25, QColor(45, 130, 175));
  13611. setColorStopAt(0.30, QColor(100, 140, 125));
  13612. setColorStopAt(0.5, QColor(100, 140, 100));
  13613. setColorStopAt(0.6, QColor(130, 145, 120));
  13614. setColorStopAt(0.7, QColor(140, 130, 120));
  13615. setColorStopAt(0.9, QColor(180, 190, 190));
  13616. setColorStopAt(1, QColor(210, 210, 230));
  13617. break;
  13618. case gpIon:
  13619. setColorInterpolation(ciHSV);
  13620. setColorStopAt(0, QColor(50, 10, 10));
  13621. setColorStopAt(0.45, QColor(0, 0, 255));
  13622. setColorStopAt(0.8, QColor(0, 255, 255));
  13623. setColorStopAt(1, QColor(0, 255, 0));
  13624. break;
  13625. case gpThermal:
  13626. setColorInterpolation(ciRGB);
  13627. setColorStopAt(0, QColor(0, 0, 50));
  13628. setColorStopAt(0.15, QColor(20, 0, 120));
  13629. setColorStopAt(0.33, QColor(200, 30, 140));
  13630. setColorStopAt(0.6, QColor(255, 100, 0));
  13631. setColorStopAt(0.85, QColor(255, 255, 40));
  13632. setColorStopAt(1, QColor(255, 255, 255));
  13633. break;
  13634. case gpPolar:
  13635. setColorInterpolation(ciRGB);
  13636. setColorStopAt(0, QColor(50, 255, 255));
  13637. setColorStopAt(0.18, QColor(10, 70, 255));
  13638. setColorStopAt(0.28, QColor(10, 10, 190));
  13639. setColorStopAt(0.5, QColor(0, 0, 0));
  13640. setColorStopAt(0.72, QColor(190, 10, 10));
  13641. setColorStopAt(0.82, QColor(255, 70, 10));
  13642. setColorStopAt(1, QColor(255, 255, 50));
  13643. break;
  13644. case gpSpectrum:
  13645. setColorInterpolation(ciHSV);
  13646. setColorStopAt(0, QColor(50, 0, 50));
  13647. setColorStopAt(0.15, QColor(0, 0, 255));
  13648. setColorStopAt(0.35, QColor(0, 255, 255));
  13649. setColorStopAt(0.6, QColor(255, 255, 0));
  13650. setColorStopAt(0.75, QColor(255, 30, 0));
  13651. setColorStopAt(1, QColor(50, 0, 0));
  13652. break;
  13653. case gpJet:
  13654. setColorInterpolation(ciRGB);
  13655. setColorStopAt(0, QColor(0, 0, 100));
  13656. setColorStopAt(0.15, QColor(0, 50, 255));
  13657. setColorStopAt(0.35, QColor(0, 255, 255));
  13658. setColorStopAt(0.65, QColor(255, 255, 0));
  13659. setColorStopAt(0.85, QColor(255, 30, 0));
  13660. setColorStopAt(1, QColor(100, 0, 0));
  13661. break;
  13662. case gpHues:
  13663. setColorInterpolation(ciHSV);
  13664. setColorStopAt(0, QColor(255, 0, 0));
  13665. setColorStopAt(1.0/3.0, QColor(0, 0, 255));
  13666. setColorStopAt(2.0/3.0, QColor(0, 255, 0));
  13667. setColorStopAt(1, QColor(255, 0, 0));
  13668. break;
  13669. }
  13670. }
  13671. /*!
  13672. Clears all color stops.
  13673. \see setColorStops, setColorStopAt
  13674. */
  13675. void QCPColorGradient::clearColorStops()
  13676. {
  13677. mColorStops.clear();
  13678. mColorBufferInvalidated = true;
  13679. }
  13680. /*!
  13681. Returns an inverted gradient. The inverted gradient has all properties as this \ref
  13682. QCPColorGradient, but the order of the color stops is inverted.
  13683. \see setColorStops, setColorStopAt
  13684. */
  13685. QCPColorGradient QCPColorGradient::inverted() const
  13686. {
  13687. QCPColorGradient result(*this);
  13688. result.clearColorStops();
  13689. for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
  13690. result.setColorStopAt(1.0-it.key(), it.value());
  13691. return result;
  13692. }
  13693. /*! \internal
  13694. Returns true if the color gradient uses transparency, i.e. if any of the configured color stops
  13695. has an alpha value below 255.
  13696. */
  13697. bool QCPColorGradient::stopsUseAlpha() const
  13698. {
  13699. for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
  13700. {
  13701. if (it.value().alpha() < 255)
  13702. return true;
  13703. }
  13704. return false;
  13705. }
  13706. /*! \internal
  13707. Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly
  13708. convert positions to colors. This is where the interpolation between color stops is calculated.
  13709. */
  13710. void QCPColorGradient::updateColorBuffer()
  13711. {
  13712. if (mColorBuffer.size() != mLevelCount)
  13713. mColorBuffer.resize(mLevelCount);
  13714. if (mColorStops.size() > 1)
  13715. {
  13716. double indexToPosFactor = 1.0/(double)(mLevelCount-1);
  13717. const bool useAlpha = stopsUseAlpha();
  13718. for (int i=0; i<mLevelCount; ++i)
  13719. {
  13720. double position = i*indexToPosFactor;
  13721. QMap<double, QColor>::const_iterator it = mColorStops.lowerBound(position);
  13722. if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop
  13723. {
  13724. mColorBuffer[i] = (it-1).value().rgba();
  13725. } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop
  13726. {
  13727. mColorBuffer[i] = it.value().rgba();
  13728. } else // position is in between stops (or on an intermediate stop), interpolate color
  13729. {
  13730. QMap<double, QColor>::const_iterator high = it;
  13731. QMap<double, QColor>::const_iterator low = it-1;
  13732. double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1
  13733. switch (mColorInterpolation)
  13734. {
  13735. case ciRGB:
  13736. {
  13737. if (useAlpha)
  13738. {
  13739. const int alpha = (1-t)*low.value().alpha() + t*high.value().alpha();
  13740. const float alphaPremultiplier = alpha/255.0f; // since we use QImage::Format_ARGB32_Premultiplied
  13741. mColorBuffer[i] = qRgba(((1-t)*low.value().red() + t*high.value().red())*alphaPremultiplier,
  13742. ((1-t)*low.value().green() + t*high.value().green())*alphaPremultiplier,
  13743. ((1-t)*low.value().blue() + t*high.value().blue())*alphaPremultiplier,
  13744. alpha);
  13745. } else
  13746. {
  13747. mColorBuffer[i] = qRgb(((1-t)*low.value().red() + t*high.value().red()),
  13748. ((1-t)*low.value().green() + t*high.value().green()),
  13749. ((1-t)*low.value().blue() + t*high.value().blue()));
  13750. }
  13751. break;
  13752. }
  13753. case ciHSV:
  13754. {
  13755. QColor lowHsv = low.value().toHsv();
  13756. QColor highHsv = high.value().toHsv();
  13757. double hue = 0;
  13758. double hueDiff = highHsv.hueF()-lowHsv.hueF();
  13759. if (hueDiff > 0.5)
  13760. hue = lowHsv.hueF() - t*(1.0-hueDiff);
  13761. else if (hueDiff < -0.5)
  13762. hue = lowHsv.hueF() + t*(1.0+hueDiff);
  13763. else
  13764. hue = lowHsv.hueF() + t*hueDiff;
  13765. if (hue < 0) hue += 1.0;
  13766. else if (hue >= 1.0) hue -= 1.0;
  13767. if (useAlpha)
  13768. {
  13769. const QRgb rgb = QColor::fromHsvF(hue,
  13770. (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(),
  13771. (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
  13772. const float alpha = (1-t)*lowHsv.alphaF() + t*highHsv.alphaF();
  13773. mColorBuffer[i] = qRgba(qRed(rgb)*alpha, qGreen(rgb)*alpha, qBlue(rgb)*alpha, 255*alpha);
  13774. }
  13775. else
  13776. {
  13777. mColorBuffer[i] = QColor::fromHsvF(hue,
  13778. (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(),
  13779. (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
  13780. }
  13781. break;
  13782. }
  13783. }
  13784. }
  13785. }
  13786. } else if (mColorStops.size() == 1)
  13787. {
  13788. const QRgb rgb = mColorStops.constBegin().value().rgb();
  13789. const float alpha = mColorStops.constBegin().value().alphaF();
  13790. mColorBuffer.fill(qRgba(qRed(rgb)*alpha, qGreen(rgb)*alpha, qBlue(rgb)*alpha, 255*alpha));
  13791. } else // mColorStops is empty, fill color buffer with black
  13792. {
  13793. mColorBuffer.fill(qRgb(0, 0, 0));
  13794. }
  13795. mColorBufferInvalidated = false;
  13796. }
  13797. /* end of 'src/colorgradient.cpp' */
  13798. /* including file 'src/selectiondecorator-bracket.cpp', size 12313 */
  13799. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  13800. ////////////////////////////////////////////////////////////////////////////////////////////////////
  13801. //////////////////// QCPSelectionDecoratorBracket
  13802. ////////////////////////////////////////////////////////////////////////////////////////////////////
  13803. /*! \class QCPSelectionDecoratorBracket
  13804. \brief A selection decorator which draws brackets around each selected data segment
  13805. Additionally to the regular highlighting of selected segments via color, fill and scatter style,
  13806. this \ref QCPSelectionDecorator subclass draws markers at the begin and end of each selected data
  13807. segment of the plottable.
  13808. The shape of the markers can be controlled with \ref setBracketStyle, \ref setBracketWidth and
  13809. \ref setBracketHeight. The color/fill can be controlled with \ref setBracketPen and \ref
  13810. setBracketBrush.
  13811. To introduce custom bracket styles, it is only necessary to sublcass \ref
  13812. QCPSelectionDecoratorBracket and reimplement \ref drawBracket. The rest will be managed by the
  13813. base class.
  13814. */
  13815. /*!
  13816. Creates a new QCPSelectionDecoratorBracket instance with default values.
  13817. */
  13818. QCPSelectionDecoratorBracket::QCPSelectionDecoratorBracket() :
  13819. mBracketPen(QPen(Qt::black)),
  13820. mBracketBrush(Qt::NoBrush),
  13821. mBracketWidth(5),
  13822. mBracketHeight(50),
  13823. mBracketStyle(bsSquareBracket),
  13824. mTangentToData(false),
  13825. mTangentAverage(2)
  13826. {
  13827. }
  13828. QCPSelectionDecoratorBracket::~QCPSelectionDecoratorBracket()
  13829. {
  13830. }
  13831. /*!
  13832. Sets the pen that will be used to draw the brackets at the beginning and end of each selected
  13833. data segment.
  13834. */
  13835. void QCPSelectionDecoratorBracket::setBracketPen(const QPen &pen)
  13836. {
  13837. mBracketPen = pen;
  13838. }
  13839. /*!
  13840. Sets the brush that will be used to draw the brackets at the beginning and end of each selected
  13841. data segment.
  13842. */
  13843. void QCPSelectionDecoratorBracket::setBracketBrush(const QBrush &brush)
  13844. {
  13845. mBracketBrush = brush;
  13846. }
  13847. /*!
  13848. Sets the width of the drawn bracket. The width dimension is always parallel to the key axis of
  13849. the data, or the tangent direction of the current data slope, if \ref setTangentToData is
  13850. enabled.
  13851. */
  13852. void QCPSelectionDecoratorBracket::setBracketWidth(int width)
  13853. {
  13854. mBracketWidth = width;
  13855. }
  13856. /*!
  13857. Sets the height of the drawn bracket. The height dimension is always perpendicular to the key axis
  13858. of the data, or the tangent direction of the current data slope, if \ref setTangentToData is
  13859. enabled.
  13860. */
  13861. void QCPSelectionDecoratorBracket::setBracketHeight(int height)
  13862. {
  13863. mBracketHeight = height;
  13864. }
  13865. /*!
  13866. Sets the shape that the bracket/marker will have.
  13867. \see setBracketWidth, setBracketHeight
  13868. */
  13869. void QCPSelectionDecoratorBracket::setBracketStyle(QCPSelectionDecoratorBracket::BracketStyle style)
  13870. {
  13871. mBracketStyle = style;
  13872. }
  13873. /*!
  13874. Sets whether the brackets will be rotated such that they align with the slope of the data at the
  13875. position that they appear in.
  13876. For noisy data, it might be more visually appealing to average the slope over multiple data
  13877. points. This can be configured via \ref setTangentAverage.
  13878. */
  13879. void QCPSelectionDecoratorBracket::setTangentToData(bool enabled)
  13880. {
  13881. mTangentToData = enabled;
  13882. }
  13883. /*!
  13884. Controls over how many data points the slope shall be averaged, when brackets shall be aligned
  13885. with the data (if \ref setTangentToData is true).
  13886. From the position of the bracket, \a pointCount points towards the selected data range will be
  13887. taken into account. The smallest value of \a pointCount is 1, which is effectively equivalent to
  13888. disabling \ref setTangentToData.
  13889. */
  13890. void QCPSelectionDecoratorBracket::setTangentAverage(int pointCount)
  13891. {
  13892. mTangentAverage = pointCount;
  13893. if (mTangentAverage < 1)
  13894. mTangentAverage = 1;
  13895. }
  13896. /*!
  13897. Draws the bracket shape with \a painter. The parameter \a direction is either -1 or 1 and
  13898. indicates whether the bracket shall point to the left or the right (i.e. is a closing or opening
  13899. bracket, respectively).
  13900. The passed \a painter already contains all transformations that are necessary to position and
  13901. rotate the bracket appropriately. Painting operations can be performed as if drawing upright
  13902. brackets on flat data with horizontal key axis, with (0, 0) being the center of the bracket.
  13903. If you wish to sublcass \ref QCPSelectionDecoratorBracket in order to provide custom bracket
  13904. shapes (see \ref QCPSelectionDecoratorBracket::bsUserStyle), this is the method you should
  13905. reimplement.
  13906. */
  13907. void QCPSelectionDecoratorBracket::drawBracket(QCPPainter *painter, int direction) const
  13908. {
  13909. switch (mBracketStyle)
  13910. {
  13911. case bsSquareBracket:
  13912. {
  13913. painter->drawLine(QLineF(mBracketWidth*direction, -mBracketHeight*0.5, 0, -mBracketHeight*0.5));
  13914. painter->drawLine(QLineF(mBracketWidth*direction, mBracketHeight*0.5, 0, mBracketHeight*0.5));
  13915. painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5));
  13916. break;
  13917. }
  13918. case bsHalfEllipse:
  13919. {
  13920. painter->drawArc(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight, -90*16, -180*16*direction);
  13921. break;
  13922. }
  13923. case bsEllipse:
  13924. {
  13925. painter->drawEllipse(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight);
  13926. break;
  13927. }
  13928. case bsPlus:
  13929. {
  13930. painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5));
  13931. painter->drawLine(QLineF(-mBracketWidth*0.5, 0, mBracketWidth*0.5, 0));
  13932. break;
  13933. }
  13934. default:
  13935. {
  13936. qDebug() << Q_FUNC_INFO << "unknown/custom bracket style can't be handeld by default implementation:" << static_cast<int>(mBracketStyle);
  13937. break;
  13938. }
  13939. }
  13940. }
  13941. /*!
  13942. Draws the bracket decoration on the data points at the begin and end of each selected data
  13943. segment given in \a seletion.
  13944. It uses the method \ref drawBracket to actually draw the shapes.
  13945. \seebaseclassmethod
  13946. */
  13947. void QCPSelectionDecoratorBracket::drawDecoration(QCPPainter *painter, QCPDataSelection selection)
  13948. {
  13949. if (!mPlottable || selection.isEmpty()) return;
  13950. if (QCPPlottableInterface1D *interface1d = mPlottable->interface1D())
  13951. {
  13952. foreach (const QCPDataRange &dataRange, selection.dataRanges())
  13953. {
  13954. // determine position and (if tangent mode is enabled) angle of brackets:
  13955. int openBracketDir = (mPlottable->keyAxis() && !mPlottable->keyAxis()->rangeReversed()) ? 1 : -1;
  13956. int closeBracketDir = -openBracketDir;
  13957. QPointF openBracketPos = getPixelCoordinates(interface1d, dataRange.begin());
  13958. QPointF closeBracketPos = getPixelCoordinates(interface1d, dataRange.end()-1);
  13959. double openBracketAngle = 0;
  13960. double closeBracketAngle = 0;
  13961. if (mTangentToData)
  13962. {
  13963. openBracketAngle = getTangentAngle(interface1d, dataRange.begin(), openBracketDir);
  13964. closeBracketAngle = getTangentAngle(interface1d, dataRange.end()-1, closeBracketDir);
  13965. }
  13966. // draw opening bracket:
  13967. QTransform oldTransform = painter->transform();
  13968. painter->setPen(mBracketPen);
  13969. painter->setBrush(mBracketBrush);
  13970. painter->translate(openBracketPos);
  13971. painter->rotate(openBracketAngle/M_PI*180.0);
  13972. drawBracket(painter, openBracketDir);
  13973. painter->setTransform(oldTransform);
  13974. // draw closing bracket:
  13975. painter->setPen(mBracketPen);
  13976. painter->setBrush(mBracketBrush);
  13977. painter->translate(closeBracketPos);
  13978. painter->rotate(closeBracketAngle/M_PI*180.0);
  13979. drawBracket(painter, closeBracketDir);
  13980. painter->setTransform(oldTransform);
  13981. }
  13982. }
  13983. }
  13984. /*! \internal
  13985. If \ref setTangentToData is enabled, brackets need to be rotated according to the data slope.
  13986. This method returns the angle in radians by which a bracket at the given \a dataIndex must be
  13987. rotated.
  13988. The parameter \a direction must be set to either -1 or 1, representing whether it is an opening
  13989. or closing bracket. Since for slope calculation multiple data points are required, this defines
  13990. the direction in which the algorithm walks, starting at \a dataIndex, to average those data
  13991. points. (see \ref setTangentToData and \ref setTangentAverage)
  13992. \a interface1d is the interface to the plottable's data which is used to query data coordinates.
  13993. */
  13994. double QCPSelectionDecoratorBracket::getTangentAngle(const QCPPlottableInterface1D *interface1d, int dataIndex, int direction) const
  13995. {
  13996. if (!interface1d || dataIndex < 0 || dataIndex >= interface1d->dataCount())
  13997. return 0;
  13998. direction = direction < 0 ? -1 : 1; // enforce direction is either -1 or 1
  13999. // how many steps we can actually go from index in the given direction without exceeding data bounds:
  14000. int averageCount;
  14001. if (direction < 0)
  14002. averageCount = qMin(mTangentAverage, dataIndex);
  14003. else
  14004. averageCount = qMin(mTangentAverage, interface1d->dataCount()-1-dataIndex);
  14005. qDebug() << averageCount;
  14006. // calculate point average of averageCount points:
  14007. QVector<QPointF> points(averageCount);
  14008. QPointF pointsAverage;
  14009. int currentIndex = dataIndex;
  14010. for (int i=0; i<averageCount; ++i)
  14011. {
  14012. points[i] = getPixelCoordinates(interface1d, currentIndex);
  14013. pointsAverage += points[i];
  14014. currentIndex += direction;
  14015. }
  14016. pointsAverage /= (double)averageCount;
  14017. // calculate slope of linear regression through points:
  14018. double numSum = 0;
  14019. double denomSum = 0;
  14020. for (int i=0; i<averageCount; ++i)
  14021. {
  14022. const double dx = points.at(i).x()-pointsAverage.x();
  14023. const double dy = points.at(i).y()-pointsAverage.y();
  14024. numSum += dx*dy;
  14025. denomSum += dx*dx;
  14026. }
  14027. if (!qFuzzyIsNull(denomSum) && !qFuzzyIsNull(numSum))
  14028. {
  14029. return qAtan2(numSum, denomSum);
  14030. } else // undetermined angle, probably mTangentAverage == 1, so using only one data point
  14031. return 0;
  14032. }
  14033. /*! \internal
  14034. Returns the pixel coordinates of the data point at \a dataIndex, using \a interface1d to access
  14035. the data points.
  14036. */
  14037. QPointF QCPSelectionDecoratorBracket::getPixelCoordinates(const QCPPlottableInterface1D *interface1d, int dataIndex) const
  14038. {
  14039. QCPAxis *keyAxis = mPlottable->keyAxis();
  14040. QCPAxis *valueAxis = mPlottable->valueAxis();
  14041. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(0, 0); }
  14042. if (keyAxis->orientation() == Qt::Horizontal)
  14043. return QPointF(keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex)), valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex)));
  14044. else
  14045. return QPointF(valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex)), keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex)));
  14046. }
  14047. /* end of 'src/selectiondecorator-bracket.cpp' */
  14048. /* including file 'src/layoutelements/layoutelement-axisrect.cpp', size 47584 */
  14049. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  14050. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14051. //////////////////// QCPAxisRect
  14052. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14053. /*! \class QCPAxisRect
  14054. \brief Holds multiple axes and arranges them in a rectangular shape.
  14055. This class represents an axis rect, a rectangular area that is bounded on all sides with an
  14056. arbitrary number of axes.
  14057. Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the
  14058. layout system allows to have multiple axis rects, e.g. arranged in a grid layout
  14059. (QCustomPlot::plotLayout).
  14060. By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be
  14061. accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index.
  14062. If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be
  14063. invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref
  14064. addAxes. To remove an axis, use \ref removeAxis.
  14065. The axis rect layerable itself only draws a background pixmap or color, if specified (\ref
  14066. setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an
  14067. explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be
  14068. placed on other layers, independently of the axis rect.
  14069. Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref
  14070. insetLayout and can be used to have other layout elements (or even other layouts with multiple
  14071. elements) hovering inside the axis rect.
  14072. If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The
  14073. behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel
  14074. is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable
  14075. via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are
  14076. only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref
  14077. QCP::iRangeZoom.
  14078. \image html AxisRectSpacingOverview.png
  14079. <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed
  14080. line on the far left indicates the viewport/widget border.</center>
  14081. */
  14082. /* start documentation of inline functions */
  14083. /*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const
  14084. Returns the inset layout of this axis rect. It can be used to place other layout elements (or
  14085. even layouts with multiple other elements) inside/on top of an axis rect.
  14086. \see QCPLayoutInset
  14087. */
  14088. /*! \fn int QCPAxisRect::left() const
  14089. Returns the pixel position of the left border of this axis rect. Margins are not taken into
  14090. account here, so the returned value is with respect to the inner \ref rect.
  14091. */
  14092. /*! \fn int QCPAxisRect::right() const
  14093. Returns the pixel position of the right border of this axis rect. Margins are not taken into
  14094. account here, so the returned value is with respect to the inner \ref rect.
  14095. */
  14096. /*! \fn int QCPAxisRect::top() const
  14097. Returns the pixel position of the top border of this axis rect. Margins are not taken into
  14098. account here, so the returned value is with respect to the inner \ref rect.
  14099. */
  14100. /*! \fn int QCPAxisRect::bottom() const
  14101. Returns the pixel position of the bottom border of this axis rect. Margins are not taken into
  14102. account here, so the returned value is with respect to the inner \ref rect.
  14103. */
  14104. /*! \fn int QCPAxisRect::width() const
  14105. Returns the pixel width of this axis rect. Margins are not taken into account here, so the
  14106. returned value is with respect to the inner \ref rect.
  14107. */
  14108. /*! \fn int QCPAxisRect::height() const
  14109. Returns the pixel height of this axis rect. Margins are not taken into account here, so the
  14110. returned value is with respect to the inner \ref rect.
  14111. */
  14112. /*! \fn QSize QCPAxisRect::size() const
  14113. Returns the pixel size of this axis rect. Margins are not taken into account here, so the
  14114. returned value is with respect to the inner \ref rect.
  14115. */
  14116. /*! \fn QPoint QCPAxisRect::topLeft() const
  14117. Returns the top left corner of this axis rect in pixels. Margins are not taken into account here,
  14118. so the returned value is with respect to the inner \ref rect.
  14119. */
  14120. /*! \fn QPoint QCPAxisRect::topRight() const
  14121. Returns the top right corner of this axis rect in pixels. Margins are not taken into account
  14122. here, so the returned value is with respect to the inner \ref rect.
  14123. */
  14124. /*! \fn QPoint QCPAxisRect::bottomLeft() const
  14125. Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account
  14126. here, so the returned value is with respect to the inner \ref rect.
  14127. */
  14128. /*! \fn QPoint QCPAxisRect::bottomRight() const
  14129. Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account
  14130. here, so the returned value is with respect to the inner \ref rect.
  14131. */
  14132. /*! \fn QPoint QCPAxisRect::center() const
  14133. Returns the center of this axis rect in pixels. Margins are not taken into account here, so the
  14134. returned value is with respect to the inner \ref rect.
  14135. */
  14136. /* end documentation of inline functions */
  14137. /*!
  14138. Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four
  14139. sides, the top and right axes are set invisible initially.
  14140. */
  14141. QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) :
  14142. QCPLayoutElement(parentPlot),
  14143. mBackgroundBrush(Qt::NoBrush),
  14144. mBackgroundScaled(true),
  14145. mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
  14146. mInsetLayout(new QCPLayoutInset),
  14147. mRangeDrag(Qt::Horizontal|Qt::Vertical),
  14148. mRangeZoom(Qt::Horizontal|Qt::Vertical),
  14149. mRangeZoomFactorHorz(0.85),
  14150. mRangeZoomFactorVert(0.85),
  14151. mDragging(false)
  14152. {
  14153. mInsetLayout->initializeParentPlot(mParentPlot);
  14154. mInsetLayout->setParentLayerable(this);
  14155. mInsetLayout->setParent(this);
  14156. setMinimumSize(50, 50);
  14157. setMinimumMargins(QMargins(15, 15, 15, 15));
  14158. mAxes.insert(QCPAxis::atLeft, QList<QCPAxis*>());
  14159. mAxes.insert(QCPAxis::atRight, QList<QCPAxis*>());
  14160. mAxes.insert(QCPAxis::atTop, QList<QCPAxis*>());
  14161. mAxes.insert(QCPAxis::atBottom, QList<QCPAxis*>());
  14162. if (setupDefaultAxes)
  14163. {
  14164. QCPAxis *xAxis = addAxis(QCPAxis::atBottom);
  14165. QCPAxis *yAxis = addAxis(QCPAxis::atLeft);
  14166. QCPAxis *xAxis2 = addAxis(QCPAxis::atTop);
  14167. QCPAxis *yAxis2 = addAxis(QCPAxis::atRight);
  14168. setRangeDragAxes(xAxis, yAxis);
  14169. setRangeZoomAxes(xAxis, yAxis);
  14170. xAxis2->setVisible(false);
  14171. yAxis2->setVisible(false);
  14172. xAxis->grid()->setVisible(true);
  14173. yAxis->grid()->setVisible(true);
  14174. xAxis2->grid()->setVisible(false);
  14175. yAxis2->grid()->setVisible(false);
  14176. xAxis2->grid()->setZeroLinePen(Qt::NoPen);
  14177. yAxis2->grid()->setZeroLinePen(Qt::NoPen);
  14178. xAxis2->grid()->setVisible(false);
  14179. yAxis2->grid()->setVisible(false);
  14180. }
  14181. }
  14182. QCPAxisRect::~QCPAxisRect()
  14183. {
  14184. delete mInsetLayout;
  14185. mInsetLayout = 0;
  14186. QList<QCPAxis*> axesList = axes();
  14187. for (int i=0; i<axesList.size(); ++i)
  14188. removeAxis(axesList.at(i));
  14189. }
  14190. /*!
  14191. Returns the number of axes on the axis rect side specified with \a type.
  14192. \see axis
  14193. */
  14194. int QCPAxisRect::axisCount(QCPAxis::AxisType type) const
  14195. {
  14196. return mAxes.value(type).size();
  14197. }
  14198. /*!
  14199. Returns the axis with the given \a index on the axis rect side specified with \a type.
  14200. \see axisCount, axes
  14201. */
  14202. QCPAxis *QCPAxisRect::axis(QCPAxis::AxisType type, int index) const
  14203. {
  14204. QList<QCPAxis*> ax(mAxes.value(type));
  14205. if (index >= 0 && index < ax.size())
  14206. {
  14207. return ax.at(index);
  14208. } else
  14209. {
  14210. qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index;
  14211. return 0;
  14212. }
  14213. }
  14214. /*!
  14215. Returns all axes on the axis rect sides specified with \a types.
  14216. \a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of
  14217. multiple sides.
  14218. \see axis
  14219. */
  14220. QList<QCPAxis*> QCPAxisRect::axes(QCPAxis::AxisTypes types) const
  14221. {
  14222. QList<QCPAxis*> result;
  14223. if (types.testFlag(QCPAxis::atLeft))
  14224. result << mAxes.value(QCPAxis::atLeft);
  14225. if (types.testFlag(QCPAxis::atRight))
  14226. result << mAxes.value(QCPAxis::atRight);
  14227. if (types.testFlag(QCPAxis::atTop))
  14228. result << mAxes.value(QCPAxis::atTop);
  14229. if (types.testFlag(QCPAxis::atBottom))
  14230. result << mAxes.value(QCPAxis::atBottom);
  14231. return result;
  14232. }
  14233. /*! \overload
  14234. Returns all axes of this axis rect.
  14235. */
  14236. QList<QCPAxis*> QCPAxisRect::axes() const
  14237. {
  14238. QList<QCPAxis*> result;
  14239. QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
  14240. while (it.hasNext())
  14241. {
  14242. it.next();
  14243. result << it.value();
  14244. }
  14245. return result;
  14246. }
  14247. /*!
  14248. Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a
  14249. new QCPAxis instance is created internally. QCustomPlot owns the returned axis, so if you want to
  14250. remove an axis, use \ref removeAxis instead of deleting it manually.
  14251. You may inject QCPAxis instances (or subclasses of QCPAxis) by setting \a axis to an axis that was
  14252. previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership
  14253. of the axis, so you may not delete it afterwards. Further, the \a axis must have been created
  14254. with this axis rect as parent and with the same axis type as specified in \a type. If this is not
  14255. the case, a debug output is generated, the axis is not added, and the method returns 0.
  14256. This method can not be used to move \a axis between axis rects. The same \a axis instance must
  14257. not be added multiple times to the same or different axis rects.
  14258. If an axis rect side already contains one or more axes, the lower and upper endings of the new
  14259. axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref
  14260. QCPLineEnding::esHalfBar.
  14261. \see addAxes, setupFullAxesBox
  14262. */
  14263. QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type, QCPAxis *axis)
  14264. {
  14265. QCPAxis *newAxis = axis;
  14266. if (!newAxis)
  14267. {
  14268. newAxis = new QCPAxis(this, type);
  14269. } else // user provided existing axis instance, do some sanity checks
  14270. {
  14271. if (newAxis->axisType() != type)
  14272. {
  14273. qDebug() << Q_FUNC_INFO << "passed axis has different axis type than specified in type parameter";
  14274. return 0;
  14275. }
  14276. if (newAxis->axisRect() != this)
  14277. {
  14278. qDebug() << Q_FUNC_INFO << "passed axis doesn't have this axis rect as parent axis rect";
  14279. return 0;
  14280. }
  14281. if (axes().contains(newAxis))
  14282. {
  14283. qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect";
  14284. return 0;
  14285. }
  14286. }
  14287. if (mAxes[type].size() > 0) // multiple axes on one side, add half-bar axis ending to additional axes with offset
  14288. {
  14289. bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom);
  14290. newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert));
  14291. newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert));
  14292. }
  14293. mAxes[type].append(newAxis);
  14294. // reset convenience axis pointers on parent QCustomPlot if they are unset:
  14295. if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this)
  14296. {
  14297. switch (type)
  14298. {
  14299. case QCPAxis::atBottom: { if (!mParentPlot->xAxis) mParentPlot->xAxis = newAxis; break; }
  14300. case QCPAxis::atLeft: { if (!mParentPlot->yAxis) mParentPlot->yAxis = newAxis; break; }
  14301. case QCPAxis::atTop: { if (!mParentPlot->xAxis2) mParentPlot->xAxis2 = newAxis; break; }
  14302. case QCPAxis::atRight: { if (!mParentPlot->yAxis2) mParentPlot->yAxis2 = newAxis; break; }
  14303. }
  14304. }
  14305. return newAxis;
  14306. }
  14307. /*!
  14308. Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an
  14309. <tt>or</tt>-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once.
  14310. Returns a list of the added axes.
  14311. \see addAxis, setupFullAxesBox
  14312. */
  14313. QList<QCPAxis*> QCPAxisRect::addAxes(QCPAxis::AxisTypes types)
  14314. {
  14315. QList<QCPAxis*> result;
  14316. if (types.testFlag(QCPAxis::atLeft))
  14317. result << addAxis(QCPAxis::atLeft);
  14318. if (types.testFlag(QCPAxis::atRight))
  14319. result << addAxis(QCPAxis::atRight);
  14320. if (types.testFlag(QCPAxis::atTop))
  14321. result << addAxis(QCPAxis::atTop);
  14322. if (types.testFlag(QCPAxis::atBottom))
  14323. result << addAxis(QCPAxis::atBottom);
  14324. return result;
  14325. }
  14326. /*!
  14327. Removes the specified \a axis from the axis rect and deletes it.
  14328. Returns true on success, i.e. if \a axis was a valid axis in this axis rect.
  14329. \see addAxis
  14330. */
  14331. bool QCPAxisRect::removeAxis(QCPAxis *axis)
  14332. {
  14333. // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers:
  14334. QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
  14335. while (it.hasNext())
  14336. {
  14337. it.next();
  14338. if (it.value().contains(axis))
  14339. {
  14340. 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)
  14341. it.value()[1]->setOffset(axis->offset());
  14342. mAxes[it.key()].removeOne(axis);
  14343. 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)
  14344. parentPlot()->axisRemoved(axis);
  14345. delete axis;
  14346. return true;
  14347. }
  14348. }
  14349. qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast<quintptr>(axis);
  14350. return false;
  14351. }
  14352. /*!
  14353. Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates.
  14354. All axes of this axis rect will have their range zoomed accordingly. If you only wish to zoom
  14355. specific axes, use the overloaded version of this method.
  14356. \see QCustomPlot::setSelectionRectMode
  14357. */
  14358. void QCPAxisRect::zoom(const QRectF &pixelRect)
  14359. {
  14360. zoom(pixelRect, axes());
  14361. }
  14362. /*! \overload
  14363. Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates.
  14364. Only the axes passed in \a affectedAxes will have their ranges zoomed accordingly.
  14365. \see QCustomPlot::setSelectionRectMode
  14366. */
  14367. void QCPAxisRect::zoom(const QRectF &pixelRect, const QList<QCPAxis*> &affectedAxes)
  14368. {
  14369. foreach (QCPAxis *axis, affectedAxes)
  14370. {
  14371. if (!axis)
  14372. {
  14373. qDebug() << Q_FUNC_INFO << "a passed axis was zero";
  14374. continue;
  14375. }
  14376. QCPRange pixelRange;
  14377. if (axis->orientation() == Qt::Horizontal)
  14378. pixelRange = QCPRange(pixelRect.left(), pixelRect.right());
  14379. else
  14380. pixelRange = QCPRange(pixelRect.top(), pixelRect.bottom());
  14381. axis->setRange(axis->pixelToCoord(pixelRange.lower), axis->pixelToCoord(pixelRange.upper));
  14382. }
  14383. }
  14384. /*!
  14385. Convenience function to create an axis on each side that doesn't have any axes yet and set their
  14386. visibility to true. Further, the top/right axes are assigned the following properties of the
  14387. bottom/left axes:
  14388. \li range (\ref QCPAxis::setRange)
  14389. \li range reversed (\ref QCPAxis::setRangeReversed)
  14390. \li scale type (\ref QCPAxis::setScaleType)
  14391. \li tick visibility (\ref QCPAxis::setTicks)
  14392. \li number format (\ref QCPAxis::setNumberFormat)
  14393. \li number precision (\ref QCPAxis::setNumberPrecision)
  14394. \li tick count of ticker (\ref QCPAxisTicker::setTickCount)
  14395. \li tick origin of ticker (\ref QCPAxisTicker::setTickOrigin)
  14396. Tick label visibility (\ref QCPAxis::setTickLabels) of the right and top axes are set to false.
  14397. If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom
  14398. and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes.
  14399. */
  14400. void QCPAxisRect::setupFullAxesBox(bool connectRanges)
  14401. {
  14402. QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2;
  14403. if (axisCount(QCPAxis::atBottom) == 0)
  14404. xAxis = addAxis(QCPAxis::atBottom);
  14405. else
  14406. xAxis = axis(QCPAxis::atBottom);
  14407. if (axisCount(QCPAxis::atLeft) == 0)
  14408. yAxis = addAxis(QCPAxis::atLeft);
  14409. else
  14410. yAxis = axis(QCPAxis::atLeft);
  14411. if (axisCount(QCPAxis::atTop) == 0)
  14412. xAxis2 = addAxis(QCPAxis::atTop);
  14413. else
  14414. xAxis2 = axis(QCPAxis::atTop);
  14415. if (axisCount(QCPAxis::atRight) == 0)
  14416. yAxis2 = addAxis(QCPAxis::atRight);
  14417. else
  14418. yAxis2 = axis(QCPAxis::atRight);
  14419. xAxis->setVisible(true);
  14420. yAxis->setVisible(true);
  14421. xAxis2->setVisible(true);
  14422. yAxis2->setVisible(true);
  14423. xAxis2->setTickLabels(false);
  14424. yAxis2->setTickLabels(false);
  14425. xAxis2->setRange(xAxis->range());
  14426. xAxis2->setRangeReversed(xAxis->rangeReversed());
  14427. xAxis2->setScaleType(xAxis->scaleType());
  14428. xAxis2->setTicks(xAxis->ticks());
  14429. xAxis2->setNumberFormat(xAxis->numberFormat());
  14430. xAxis2->setNumberPrecision(xAxis->numberPrecision());
  14431. xAxis2->ticker()->setTickCount(xAxis->ticker()->tickCount());
  14432. xAxis2->ticker()->setTickOrigin(xAxis->ticker()->tickOrigin());
  14433. yAxis2->setRange(yAxis->range());
  14434. yAxis2->setRangeReversed(yAxis->rangeReversed());
  14435. yAxis2->setScaleType(yAxis->scaleType());
  14436. yAxis2->setTicks(yAxis->ticks());
  14437. yAxis2->setNumberFormat(yAxis->numberFormat());
  14438. yAxis2->setNumberPrecision(yAxis->numberPrecision());
  14439. yAxis2->ticker()->setTickCount(yAxis->ticker()->tickCount());
  14440. yAxis2->ticker()->setTickOrigin(yAxis->ticker()->tickOrigin());
  14441. if (connectRanges)
  14442. {
  14443. connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange)));
  14444. connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange)));
  14445. }
  14446. }
  14447. /*!
  14448. Returns a list of all the plottables that are associated with this axis rect.
  14449. A plottable is considered associated with an axis rect if its key or value axis (or both) is in
  14450. this axis rect.
  14451. \see graphs, items
  14452. */
  14453. QList<QCPAbstractPlottable*> QCPAxisRect::plottables() const
  14454. {
  14455. // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries
  14456. QList<QCPAbstractPlottable*> result;
  14457. for (int i=0; i<mParentPlot->mPlottables.size(); ++i)
  14458. {
  14459. if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this || mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this)
  14460. result.append(mParentPlot->mPlottables.at(i));
  14461. }
  14462. return result;
  14463. }
  14464. /*!
  14465. Returns a list of all the graphs that are associated with this axis rect.
  14466. A graph is considered associated with an axis rect if its key or value axis (or both) is in
  14467. this axis rect.
  14468. \see plottables, items
  14469. */
  14470. QList<QCPGraph*> QCPAxisRect::graphs() const
  14471. {
  14472. // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries
  14473. QList<QCPGraph*> result;
  14474. for (int i=0; i<mParentPlot->mGraphs.size(); ++i)
  14475. {
  14476. if (mParentPlot->mGraphs.at(i)->keyAxis()->axisRect() == this || mParentPlot->mGraphs.at(i)->valueAxis()->axisRect() == this)
  14477. result.append(mParentPlot->mGraphs.at(i));
  14478. }
  14479. return result;
  14480. }
  14481. /*!
  14482. Returns a list of all the items that are associated with this axis rect.
  14483. An item is considered associated with an axis rect if any of its positions has key or value axis
  14484. set to an axis that is in this axis rect, or if any of its positions has \ref
  14485. QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref
  14486. QCPAbstractItem::setClipAxisRect) is set to this axis rect.
  14487. \see plottables, graphs
  14488. */
  14489. QList<QCPAbstractItem *> QCPAxisRect::items() const
  14490. {
  14491. // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries
  14492. // and miss those items that have this axis rect as clipAxisRect.
  14493. QList<QCPAbstractItem*> result;
  14494. for (int itemId=0; itemId<mParentPlot->mItems.size(); ++itemId)
  14495. {
  14496. if (mParentPlot->mItems.at(itemId)->clipAxisRect() == this)
  14497. {
  14498. result.append(mParentPlot->mItems.at(itemId));
  14499. continue;
  14500. }
  14501. QList<QCPItemPosition*> positions = mParentPlot->mItems.at(itemId)->positions();
  14502. for (int posId=0; posId<positions.size(); ++posId)
  14503. {
  14504. if (positions.at(posId)->axisRect() == this ||
  14505. positions.at(posId)->keyAxis()->axisRect() == this ||
  14506. positions.at(posId)->valueAxis()->axisRect() == this)
  14507. {
  14508. result.append(mParentPlot->mItems.at(itemId));
  14509. break;
  14510. }
  14511. }
  14512. }
  14513. return result;
  14514. }
  14515. /*!
  14516. This method is called automatically upon replot and doesn't need to be called by users of
  14517. QCPAxisRect.
  14518. Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
  14519. and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
  14520. QCPInsetLayout::update function.
  14521. \seebaseclassmethod
  14522. */
  14523. void QCPAxisRect::update(UpdatePhase phase)
  14524. {
  14525. QCPLayoutElement::update(phase);
  14526. switch (phase)
  14527. {
  14528. case upPreparation:
  14529. {
  14530. QList<QCPAxis*> allAxes = axes();
  14531. for (int i=0; i<allAxes.size(); ++i)
  14532. allAxes.at(i)->setupTickVectors();
  14533. break;
  14534. }
  14535. case upLayout:
  14536. {
  14537. mInsetLayout->setOuterRect(rect());
  14538. break;
  14539. }
  14540. default: break;
  14541. }
  14542. // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout):
  14543. mInsetLayout->update(phase);
  14544. }
  14545. /* inherits documentation from base class */
  14546. QList<QCPLayoutElement*> QCPAxisRect::elements(bool recursive) const
  14547. {
  14548. QList<QCPLayoutElement*> result;
  14549. if (mInsetLayout)
  14550. {
  14551. result << mInsetLayout;
  14552. if (recursive)
  14553. result << mInsetLayout->elements(recursive);
  14554. }
  14555. return result;
  14556. }
  14557. /* inherits documentation from base class */
  14558. void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const
  14559. {
  14560. painter->setAntialiasing(false);
  14561. }
  14562. /* inherits documentation from base class */
  14563. void QCPAxisRect::draw(QCPPainter *painter)
  14564. {
  14565. drawBackground(painter);
  14566. }
  14567. /*!
  14568. Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the
  14569. axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect
  14570. backgrounds are usually drawn below everything else.
  14571. For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be
  14572. enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio
  14573. is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  14574. consider using the overloaded version of this function.
  14575. Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref
  14576. setBackground(const QBrush &brush).
  14577. \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush)
  14578. */
  14579. void QCPAxisRect::setBackground(const QPixmap &pm)
  14580. {
  14581. mBackgroundPixmap = pm;
  14582. mScaledBackgroundPixmap = QPixmap();
  14583. }
  14584. /*! \overload
  14585. Sets \a brush as the background brush. The axis rect background will be filled with this brush.
  14586. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds
  14587. are usually drawn below everything else.
  14588. The brush will be drawn before (under) any background pixmap, which may be specified with \ref
  14589. setBackground(const QPixmap &pm).
  14590. To disable drawing of a background brush, set \a brush to Qt::NoBrush.
  14591. \see setBackground(const QPixmap &pm)
  14592. */
  14593. void QCPAxisRect::setBackground(const QBrush &brush)
  14594. {
  14595. mBackgroundBrush = brush;
  14596. }
  14597. /*! \overload
  14598. Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it
  14599. shall be scaled in one call.
  14600. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  14601. */
  14602. void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
  14603. {
  14604. mBackgroundPixmap = pm;
  14605. mScaledBackgroundPixmap = QPixmap();
  14606. mBackgroundScaled = scaled;
  14607. mBackgroundScaledMode = mode;
  14608. }
  14609. /*!
  14610. Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled
  14611. is set to true, you may control whether and how the aspect ratio of the original pixmap is
  14612. preserved with \ref setBackgroundScaledMode.
  14613. Note that the scaled version of the original pixmap is buffered, so there is no performance
  14614. penalty on replots. (Except when the axis rect dimensions are changed continuously.)
  14615. \see setBackground, setBackgroundScaledMode
  14616. */
  14617. void QCPAxisRect::setBackgroundScaled(bool scaled)
  14618. {
  14619. mBackgroundScaled = scaled;
  14620. }
  14621. /*!
  14622. If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to
  14623. define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved.
  14624. \see setBackground, setBackgroundScaled
  14625. */
  14626. void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  14627. {
  14628. mBackgroundScaledMode = mode;
  14629. }
  14630. /*!
  14631. Returns the range drag axis of the \a orientation provided. If multiple axes were set, returns
  14632. the first one (use \ref rangeDragAxes to retrieve a list with all set axes).
  14633. \see setRangeDragAxes
  14634. */
  14635. QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation)
  14636. {
  14637. if (orientation == Qt::Horizontal)
  14638. return mRangeDragHorzAxis.isEmpty() ? 0 : mRangeDragHorzAxis.first().data();
  14639. else
  14640. return mRangeDragVertAxis.isEmpty() ? 0 : mRangeDragVertAxis.first().data();
  14641. }
  14642. /*!
  14643. Returns the range zoom axis of the \a orientation provided. If multiple axes were set, returns
  14644. the first one (use \ref rangeZoomAxes to retrieve a list with all set axes).
  14645. \see setRangeZoomAxes
  14646. */
  14647. QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation)
  14648. {
  14649. if (orientation == Qt::Horizontal)
  14650. return mRangeZoomHorzAxis.isEmpty() ? 0 : mRangeZoomHorzAxis.first().data();
  14651. else
  14652. return mRangeZoomVertAxis.isEmpty() ? 0 : mRangeZoomVertAxis.first().data();
  14653. }
  14654. /*!
  14655. Returns all range drag axes of the \a orientation provided.
  14656. \see rangeZoomAxis, setRangeZoomAxes
  14657. */
  14658. QList<QCPAxis*> QCPAxisRect::rangeDragAxes(Qt::Orientation orientation)
  14659. {
  14660. QList<QCPAxis*> result;
  14661. if (orientation == Qt::Horizontal)
  14662. {
  14663. for (int i=0; i<mRangeDragHorzAxis.size(); ++i)
  14664. {
  14665. if (!mRangeDragHorzAxis.at(i).isNull())
  14666. result.append(mRangeDragHorzAxis.at(i).data());
  14667. }
  14668. } else
  14669. {
  14670. for (int i=0; i<mRangeDragVertAxis.size(); ++i)
  14671. {
  14672. if (!mRangeDragVertAxis.at(i).isNull())
  14673. result.append(mRangeDragVertAxis.at(i).data());
  14674. }
  14675. }
  14676. return result;
  14677. }
  14678. /*!
  14679. Returns all range zoom axes of the \a orientation provided.
  14680. \see rangeDragAxis, setRangeDragAxes
  14681. */
  14682. QList<QCPAxis*> QCPAxisRect::rangeZoomAxes(Qt::Orientation orientation)
  14683. {
  14684. QList<QCPAxis*> result;
  14685. if (orientation == Qt::Horizontal)
  14686. {
  14687. for (int i=0; i<mRangeZoomHorzAxis.size(); ++i)
  14688. {
  14689. if (!mRangeZoomHorzAxis.at(i).isNull())
  14690. result.append(mRangeZoomHorzAxis.at(i).data());
  14691. }
  14692. } else
  14693. {
  14694. for (int i=0; i<mRangeZoomVertAxis.size(); ++i)
  14695. {
  14696. if (!mRangeZoomVertAxis.at(i).isNull())
  14697. result.append(mRangeZoomVertAxis.at(i).data());
  14698. }
  14699. }
  14700. return result;
  14701. }
  14702. /*!
  14703. Returns the range zoom factor of the \a orientation provided.
  14704. \see setRangeZoomFactor
  14705. */
  14706. double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation)
  14707. {
  14708. return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert);
  14709. }
  14710. /*!
  14711. Sets which axis orientation may be range dragged by the user with mouse interaction.
  14712. What orientation corresponds to which specific axis can be set with
  14713. \ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By
  14714. default, the horizontal axis is the bottom axis (xAxis) and the vertical axis
  14715. is the left axis (yAxis).
  14716. To disable range dragging entirely, pass 0 as \a orientations or remove \ref QCP::iRangeDrag from \ref
  14717. QCustomPlot::setInteractions. To enable range dragging for both directions, pass <tt>Qt::Horizontal |
  14718. Qt::Vertical</tt> as \a orientations.
  14719. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
  14720. contains \ref QCP::iRangeDrag to enable the range dragging interaction.
  14721. \see setRangeZoom, setRangeDragAxes, QCustomPlot::setNoAntialiasingOnDrag
  14722. */
  14723. void QCPAxisRect::setRangeDrag(Qt::Orientations orientations)
  14724. {
  14725. mRangeDrag = orientations;
  14726. }
  14727. /*!
  14728. Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation
  14729. corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal,
  14730. QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical
  14731. axis is the left axis (yAxis).
  14732. To disable range zooming entirely, pass 0 as \a orientations or remove \ref QCP::iRangeZoom from \ref
  14733. QCustomPlot::setInteractions. To enable range zooming for both directions, pass <tt>Qt::Horizontal |
  14734. Qt::Vertical</tt> as \a orientations.
  14735. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
  14736. contains \ref QCP::iRangeZoom to enable the range zooming interaction.
  14737. \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag
  14738. */
  14739. void QCPAxisRect::setRangeZoom(Qt::Orientations orientations)
  14740. {
  14741. mRangeZoom = orientations;
  14742. }
  14743. /*! \overload
  14744. Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging on
  14745. the QCustomPlot widget. Pass 0 if no axis shall be dragged in the respective orientation.
  14746. Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall
  14747. react to dragging interactions.
  14748. \see setRangeZoomAxes
  14749. */
  14750. void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical)
  14751. {
  14752. QList<QCPAxis*> horz, vert;
  14753. if (horizontal)
  14754. horz.append(horizontal);
  14755. if (vertical)
  14756. vert.append(vertical);
  14757. setRangeDragAxes(horz, vert);
  14758. }
  14759. /*! \overload
  14760. This method allows to set up multiple axes to react to horizontal and vertical dragging. The drag
  14761. orientation that the respective axis will react to is deduced from its orientation (\ref
  14762. QCPAxis::orientation).
  14763. In the unusual case that you wish to e.g. drag a vertically oriented axis with a horizontal drag
  14764. motion, use the overload taking two separate lists for horizontal and vertical dragging.
  14765. */
  14766. void QCPAxisRect::setRangeDragAxes(QList<QCPAxis*> axes)
  14767. {
  14768. QList<QCPAxis*> horz, vert;
  14769. foreach (QCPAxis *ax, axes)
  14770. {
  14771. if (ax->orientation() == Qt::Horizontal)
  14772. horz.append(ax);
  14773. else
  14774. vert.append(ax);
  14775. }
  14776. setRangeDragAxes(horz, vert);
  14777. }
  14778. /*! \overload
  14779. This method allows to set multiple axes up to react to horizontal and vertical dragging, and
  14780. define specifically which axis reacts to which drag orientation (irrespective of the axis
  14781. orientation).
  14782. */
  14783. void QCPAxisRect::setRangeDragAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical)
  14784. {
  14785. mRangeDragHorzAxis.clear();
  14786. foreach (QCPAxis *ax, horizontal)
  14787. {
  14788. QPointer<QCPAxis> axPointer(ax);
  14789. if (!axPointer.isNull())
  14790. mRangeDragHorzAxis.append(axPointer);
  14791. else
  14792. qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast<quintptr>(ax);
  14793. }
  14794. mRangeDragVertAxis.clear();
  14795. foreach (QCPAxis *ax, vertical)
  14796. {
  14797. QPointer<QCPAxis> axPointer(ax);
  14798. if (!axPointer.isNull())
  14799. mRangeDragVertAxis.append(axPointer);
  14800. else
  14801. qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast<quintptr>(ax);
  14802. }
  14803. }
  14804. /*!
  14805. Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on
  14806. the QCustomPlot widget. Pass 0 if no axis shall be zoomed in the respective orientation.
  14807. The two axes can be zoomed with different strengths, when different factors are passed to \ref
  14808. setRangeZoomFactor(double horizontalFactor, double verticalFactor).
  14809. Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall
  14810. react to zooming interactions.
  14811. \see setRangeDragAxes
  14812. */
  14813. void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical)
  14814. {
  14815. QList<QCPAxis*> horz, vert;
  14816. if (horizontal)
  14817. horz.append(horizontal);
  14818. if (vertical)
  14819. vert.append(vertical);
  14820. setRangeZoomAxes(horz, vert);
  14821. }
  14822. /*! \overload
  14823. This method allows to set up multiple axes to react to horizontal and vertical range zooming. The
  14824. zoom orientation that the respective axis will react to is deduced from its orientation (\ref
  14825. QCPAxis::orientation).
  14826. In the unusual case that you wish to e.g. zoom a vertically oriented axis with a horizontal zoom
  14827. interaction, use the overload taking two separate lists for horizontal and vertical zooming.
  14828. */
  14829. void QCPAxisRect::setRangeZoomAxes(QList<QCPAxis*> axes)
  14830. {
  14831. QList<QCPAxis*> horz, vert;
  14832. foreach (QCPAxis *ax, axes)
  14833. {
  14834. if (ax->orientation() == Qt::Horizontal)
  14835. horz.append(ax);
  14836. else
  14837. vert.append(ax);
  14838. }
  14839. setRangeZoomAxes(horz, vert);
  14840. }
  14841. /*! \overload
  14842. This method allows to set multiple axes up to react to horizontal and vertical zooming, and
  14843. define specifically which axis reacts to which zoom orientation (irrespective of the axis
  14844. orientation).
  14845. */
  14846. void QCPAxisRect::setRangeZoomAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical)
  14847. {
  14848. mRangeZoomHorzAxis.clear();
  14849. foreach (QCPAxis *ax, horizontal)
  14850. {
  14851. QPointer<QCPAxis> axPointer(ax);
  14852. if (!axPointer.isNull())
  14853. mRangeZoomHorzAxis.append(axPointer);
  14854. else
  14855. qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast<quintptr>(ax);
  14856. }
  14857. mRangeZoomVertAxis.clear();
  14858. foreach (QCPAxis *ax, vertical)
  14859. {
  14860. QPointer<QCPAxis> axPointer(ax);
  14861. if (!axPointer.isNull())
  14862. mRangeZoomVertAxis.append(axPointer);
  14863. else
  14864. qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast<quintptr>(ax);
  14865. }
  14866. }
  14867. /*!
  14868. Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with
  14869. \ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to
  14870. let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal
  14871. and which is vertical, can be set with \ref setRangeZoomAxes.
  14872. When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user)
  14873. will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the
  14874. same scrolling direction will zoom out.
  14875. */
  14876. void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor)
  14877. {
  14878. mRangeZoomFactorHorz = horizontalFactor;
  14879. mRangeZoomFactorVert = verticalFactor;
  14880. }
  14881. /*! \overload
  14882. Sets both the horizontal and vertical zoom \a factor.
  14883. */
  14884. void QCPAxisRect::setRangeZoomFactor(double factor)
  14885. {
  14886. mRangeZoomFactorHorz = factor;
  14887. mRangeZoomFactorVert = factor;
  14888. }
  14889. /*! \internal
  14890. Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a
  14891. pixmap.
  14892. If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an
  14893. according filling inside the axis rect with the provided \a painter.
  14894. Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version
  14895. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  14896. the axis rect with the provided \a painter. The scaled version is buffered in
  14897. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  14898. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  14899. dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
  14900. set.
  14901. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  14902. */
  14903. void QCPAxisRect::drawBackground(QCPPainter *painter)
  14904. {
  14905. // draw background fill:
  14906. if (mBackgroundBrush != Qt::NoBrush)
  14907. painter->fillRect(mRect, mBackgroundBrush);
  14908. // draw background pixmap (on top of fill, if brush specified):
  14909. if (!mBackgroundPixmap.isNull())
  14910. {
  14911. if (mBackgroundScaled)
  14912. {
  14913. // check whether mScaledBackground needs to be updated:
  14914. QSize scaledSize(mBackgroundPixmap.size());
  14915. scaledSize.scale(mRect.size(), mBackgroundScaledMode);
  14916. if (mScaledBackgroundPixmap.size() != scaledSize)
  14917. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
  14918. painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect());
  14919. } else
  14920. {
  14921. painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()));
  14922. }
  14923. }
  14924. }
  14925. /*! \internal
  14926. This function makes sure multiple axes on the side specified with \a type don't collide, but are
  14927. distributed according to their respective space requirement (QCPAxis::calculateMargin).
  14928. It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the
  14929. one with index zero.
  14930. This function is called by \ref calculateAutoMargin.
  14931. */
  14932. void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type)
  14933. {
  14934. const QList<QCPAxis*> axesList = mAxes.value(type);
  14935. if (axesList.isEmpty())
  14936. return;
  14937. 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
  14938. for (int i=1; i<axesList.size(); ++i)
  14939. {
  14940. int offset = axesList.at(i-1)->offset() + axesList.at(i-1)->calculateMargin();
  14941. 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)
  14942. {
  14943. if (!isFirstVisible)
  14944. offset += axesList.at(i)->tickLengthIn();
  14945. isFirstVisible = false;
  14946. }
  14947. axesList.at(i)->setOffset(offset);
  14948. }
  14949. }
  14950. /* inherits documentation from base class */
  14951. int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side)
  14952. {
  14953. if (!mAutoMargins.testFlag(side))
  14954. qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin";
  14955. updateAxesOffset(QCPAxis::marginSideToAxisType(side));
  14956. // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call
  14957. const QList<QCPAxis*> axesList = mAxes.value(QCPAxis::marginSideToAxisType(side));
  14958. if (axesList.size() > 0)
  14959. return axesList.last()->offset() + axesList.last()->calculateMargin();
  14960. else
  14961. return 0;
  14962. }
  14963. /*! \internal
  14964. Reacts to a change in layout to potentially set the convenience axis pointers \ref
  14965. QCustomPlot::xAxis, \ref QCustomPlot::yAxis, etc. of the parent QCustomPlot to the respective
  14966. axes of this axis rect. This is only done if the respective convenience pointer is currently zero
  14967. and if there is no QCPAxisRect at position (0, 0) of the plot layout.
  14968. This automation makes it simpler to replace the main axis rect with a newly created one, without
  14969. the need to manually reset the convenience pointers.
  14970. */
  14971. void QCPAxisRect::layoutChanged()
  14972. {
  14973. if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this)
  14974. {
  14975. if (axisCount(QCPAxis::atBottom) > 0 && !mParentPlot->xAxis)
  14976. mParentPlot->xAxis = axis(QCPAxis::atBottom);
  14977. if (axisCount(QCPAxis::atLeft) > 0 && !mParentPlot->yAxis)
  14978. mParentPlot->yAxis = axis(QCPAxis::atLeft);
  14979. if (axisCount(QCPAxis::atTop) > 0 && !mParentPlot->xAxis2)
  14980. mParentPlot->xAxis2 = axis(QCPAxis::atTop);
  14981. if (axisCount(QCPAxis::atRight) > 0 && !mParentPlot->yAxis2)
  14982. mParentPlot->yAxis2 = axis(QCPAxis::atRight);
  14983. }
  14984. }
  14985. /*! \internal
  14986. Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
  14987. pressed, the range dragging interaction is initialized (the actual range manipulation happens in
  14988. the \ref mouseMoveEvent).
  14989. The mDragging flag is set to true and some anchor points are set that are needed to determine the
  14990. distance the mouse was dragged in the mouse move/release events later.
  14991. \see mouseMoveEvent, mouseReleaseEvent
  14992. */
  14993. void QCPAxisRect::mousePressEvent(QMouseEvent *event, const QVariant &details)
  14994. {
  14995. Q_UNUSED(details)
  14996. if (event->buttons() & Qt::LeftButton)
  14997. {
  14998. mDragging = true;
  14999. // initialize antialiasing backup in case we start dragging:
  15000. if (mParentPlot->noAntialiasingOnDrag())
  15001. {
  15002. mAADragBackup = mParentPlot->antialiasedElements();
  15003. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  15004. }
  15005. // Mouse range dragging interaction:
  15006. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  15007. {
  15008. mDragStartHorzRange.clear();
  15009. for (int i=0; i<mRangeDragHorzAxis.size(); ++i)
  15010. mDragStartHorzRange.append(mRangeDragHorzAxis.at(i).isNull() ? QCPRange() : mRangeDragHorzAxis.at(i)->range());
  15011. mDragStartVertRange.clear();
  15012. for (int i=0; i<mRangeDragVertAxis.size(); ++i)
  15013. mDragStartVertRange.append(mRangeDragVertAxis.at(i).isNull() ? QCPRange() : mRangeDragVertAxis.at(i)->range());
  15014. }
  15015. }
  15016. }
  15017. /*! \internal
  15018. Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a
  15019. preceding \ref mousePressEvent, the range is moved accordingly.
  15020. \see mousePressEvent, mouseReleaseEvent
  15021. */
  15022. void QCPAxisRect::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  15023. {
  15024. Q_UNUSED(startPos)
  15025. // Mouse range dragging interaction:
  15026. if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  15027. {
  15028. if (mRangeDrag.testFlag(Qt::Horizontal))
  15029. {
  15030. for (int i=0; i<mRangeDragHorzAxis.size(); ++i)
  15031. {
  15032. QCPAxis *ax = mRangeDragHorzAxis.at(i).data();
  15033. if (!ax)
  15034. continue;
  15035. if (i >= mDragStartHorzRange.size())
  15036. break;
  15037. if (ax->mScaleType == QCPAxis::stLinear)
  15038. {
  15039. double diff = ax->pixelToCoord(startPos.x()) - ax->pixelToCoord(event->pos().x());
  15040. ax->setRange(mDragStartHorzRange.at(i).lower+diff, mDragStartHorzRange.at(i).upper+diff);
  15041. } else if (ax->mScaleType == QCPAxis::stLogarithmic)
  15042. {
  15043. double diff = ax->pixelToCoord(startPos.x()) / ax->pixelToCoord(event->pos().x());
  15044. ax->setRange(mDragStartHorzRange.at(i).lower*diff, mDragStartHorzRange.at(i).upper*diff);
  15045. }
  15046. }
  15047. }
  15048. if (mRangeDrag.testFlag(Qt::Vertical))
  15049. {
  15050. for (int i=0; i<mRangeDragVertAxis.size(); ++i)
  15051. {
  15052. QCPAxis *ax = mRangeDragVertAxis.at(i).data();
  15053. if (!ax)
  15054. continue;
  15055. if (i >= mDragStartVertRange.size())
  15056. break;
  15057. if (ax->mScaleType == QCPAxis::stLinear)
  15058. {
  15059. double diff = ax->pixelToCoord(startPos.y()) - ax->pixelToCoord(event->pos().y());
  15060. ax->setRange(mDragStartVertRange.at(i).lower+diff, mDragStartVertRange.at(i).upper+diff);
  15061. } else if (ax->mScaleType == QCPAxis::stLogarithmic)
  15062. {
  15063. double diff = ax->pixelToCoord(startPos.y()) / ax->pixelToCoord(event->pos().y());
  15064. ax->setRange(mDragStartVertRange.at(i).lower*diff, mDragStartVertRange.at(i).upper*diff);
  15065. }
  15066. }
  15067. }
  15068. if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot
  15069. {
  15070. if (mParentPlot->noAntialiasingOnDrag())
  15071. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  15072. mParentPlot->replot(QCustomPlot::rpQueuedReplot);
  15073. }
  15074. }
  15075. }
  15076. /* inherits documentation from base class */
  15077. void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  15078. {
  15079. Q_UNUSED(event)
  15080. Q_UNUSED(startPos)
  15081. mDragging = false;
  15082. if (mParentPlot->noAntialiasingOnDrag())
  15083. {
  15084. mParentPlot->setAntialiasedElements(mAADragBackup);
  15085. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  15086. }
  15087. }
  15088. /*! \internal
  15089. Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
  15090. ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
  15091. the scaling operation is the current cursor position inside the axis rect. The scaling factor is
  15092. dependent on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
  15093. zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
  15094. Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse
  15095. wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be
  15096. multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as
  15097. exponent of the range zoom factor. This takes care of the wheel direction automatically, by
  15098. inverting the factor, when the wheel step is negative (f^-1 = 1/f).
  15099. */
  15100. void QCPAxisRect::wheelEvent(QWheelEvent *event)
  15101. {
  15102. // Mouse range zooming interaction:
  15103. if (mParentPlot->interactions().testFlag(QCP::iRangeZoom))
  15104. {
  15105. if (mRangeZoom != 0)
  15106. {
  15107. double factor;
  15108. double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually
  15109. if (mRangeZoom.testFlag(Qt::Horizontal))
  15110. {
  15111. factor = qPow(mRangeZoomFactorHorz, wheelSteps);
  15112. for (int i=0; i<mRangeZoomHorzAxis.size(); ++i)
  15113. {
  15114. if (!mRangeZoomHorzAxis.at(i).isNull())
  15115. mRangeZoomHorzAxis.at(i)->scaleRange(factor, mRangeZoomHorzAxis.at(i)->pixelToCoord(event->pos().x()));
  15116. }
  15117. }
  15118. if (mRangeZoom.testFlag(Qt::Vertical))
  15119. {
  15120. factor = qPow(mRangeZoomFactorVert, wheelSteps);
  15121. for (int i=0; i<mRangeZoomVertAxis.size(); ++i)
  15122. {
  15123. if (!mRangeZoomVertAxis.at(i).isNull())
  15124. mRangeZoomVertAxis.at(i)->scaleRange(factor, mRangeZoomVertAxis.at(i)->pixelToCoord(event->pos().y()));
  15125. }
  15126. }
  15127. mParentPlot->replot();
  15128. }
  15129. }
  15130. }
  15131. /* end of 'src/layoutelements/layoutelement-axisrect.cpp' */
  15132. /* including file 'src/layoutelements/layoutelement-legend.cpp', size 31097 */
  15133. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  15134. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15135. //////////////////// QCPAbstractLegendItem
  15136. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15137. /*! \class QCPAbstractLegendItem
  15138. \brief The abstract base class for all entries in a QCPLegend.
  15139. It defines a very basic interface for entries in a QCPLegend. For representing plottables in the
  15140. legend, the subclass \ref QCPPlottableLegendItem is more suitable.
  15141. Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry
  15142. that's not even associated with a plottable).
  15143. You must implement the following pure virtual functions:
  15144. \li \ref draw (from QCPLayerable)
  15145. You inherit the following members you may use:
  15146. <table>
  15147. <tr>
  15148. <td>QCPLegend *\b mParentLegend</td>
  15149. <td>A pointer to the parent QCPLegend.</td>
  15150. </tr><tr>
  15151. <td>QFont \b mFont</td>
  15152. <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>
  15153. </tr>
  15154. </table>
  15155. */
  15156. /* start of documentation of signals */
  15157. /*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected)
  15158. This signal is emitted when the selection state of this legend item has changed, either by user
  15159. interaction or by a direct call to \ref setSelected.
  15160. */
  15161. /* end of documentation of signals */
  15162. /*!
  15163. Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not
  15164. cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately.
  15165. */
  15166. QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) :
  15167. QCPLayoutElement(parent->parentPlot()),
  15168. mParentLegend(parent),
  15169. mFont(parent->font()),
  15170. mTextColor(parent->textColor()),
  15171. mSelectedFont(parent->selectedFont()),
  15172. mSelectedTextColor(parent->selectedTextColor()),
  15173. mSelectable(true),
  15174. mSelected(false)
  15175. {
  15176. setLayer(QLatin1String("legend"));
  15177. setMargins(QMargins(0, 0, 0, 0));
  15178. }
  15179. /*!
  15180. Sets the default font of this specific legend item to \a font.
  15181. \see setTextColor, QCPLegend::setFont
  15182. */
  15183. void QCPAbstractLegendItem::setFont(const QFont &font)
  15184. {
  15185. mFont = font;
  15186. }
  15187. /*!
  15188. Sets the default text color of this specific legend item to \a color.
  15189. \see setFont, QCPLegend::setTextColor
  15190. */
  15191. void QCPAbstractLegendItem::setTextColor(const QColor &color)
  15192. {
  15193. mTextColor = color;
  15194. }
  15195. /*!
  15196. When this legend item is selected, \a font is used to draw generic text, instead of the normal
  15197. font set with \ref setFont.
  15198. \see setFont, QCPLegend::setSelectedFont
  15199. */
  15200. void QCPAbstractLegendItem::setSelectedFont(const QFont &font)
  15201. {
  15202. mSelectedFont = font;
  15203. }
  15204. /*!
  15205. When this legend item is selected, \a color is used to draw generic text, instead of the normal
  15206. color set with \ref setTextColor.
  15207. \see setTextColor, QCPLegend::setSelectedTextColor
  15208. */
  15209. void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color)
  15210. {
  15211. mSelectedTextColor = color;
  15212. }
  15213. /*!
  15214. Sets whether this specific legend item is selectable.
  15215. \see setSelectedParts, QCustomPlot::setInteractions
  15216. */
  15217. void QCPAbstractLegendItem::setSelectable(bool selectable)
  15218. {
  15219. if (mSelectable != selectable)
  15220. {
  15221. mSelectable = selectable;
  15222. emit selectableChanged(mSelectable);
  15223. }
  15224. }
  15225. /*!
  15226. Sets whether this specific legend item is selected.
  15227. It is possible to set the selection state of this item by calling this function directly, even if
  15228. setSelectable is set to false.
  15229. \see setSelectableParts, QCustomPlot::setInteractions
  15230. */
  15231. void QCPAbstractLegendItem::setSelected(bool selected)
  15232. {
  15233. if (mSelected != selected)
  15234. {
  15235. mSelected = selected;
  15236. emit selectionChanged(mSelected);
  15237. }
  15238. }
  15239. /* inherits documentation from base class */
  15240. double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  15241. {
  15242. Q_UNUSED(details)
  15243. if (!mParentPlot) return -1;
  15244. if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems)))
  15245. return -1;
  15246. if (mRect.contains(pos.toPoint()))
  15247. return mParentPlot->selectionTolerance()*0.99;
  15248. else
  15249. return -1;
  15250. }
  15251. /* inherits documentation from base class */
  15252. void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
  15253. {
  15254. applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems);
  15255. }
  15256. /* inherits documentation from base class */
  15257. QRect QCPAbstractLegendItem::clipRect() const
  15258. {
  15259. return mOuterRect;
  15260. }
  15261. /* inherits documentation from base class */
  15262. void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  15263. {
  15264. Q_UNUSED(event)
  15265. Q_UNUSED(details)
  15266. if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
  15267. {
  15268. bool selBefore = mSelected;
  15269. setSelected(additive ? !mSelected : true);
  15270. if (selectionStateChanged)
  15271. *selectionStateChanged = mSelected != selBefore;
  15272. }
  15273. }
  15274. /* inherits documentation from base class */
  15275. void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged)
  15276. {
  15277. if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
  15278. {
  15279. bool selBefore = mSelected;
  15280. setSelected(false);
  15281. if (selectionStateChanged)
  15282. *selectionStateChanged = mSelected != selBefore;
  15283. }
  15284. }
  15285. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15286. //////////////////// QCPPlottableLegendItem
  15287. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15288. /*! \class QCPPlottableLegendItem
  15289. \brief A legend item representing a plottable with an icon and the plottable name.
  15290. This is the standard legend item for plottables. It displays an icon of the plottable next to the
  15291. plottable name. The icon is drawn by the respective plottable itself (\ref
  15292. QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable.
  15293. For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the
  15294. middle.
  15295. Legend items of this type are always associated with one plottable (retrievable via the
  15296. plottable() function and settable with the constructor). You may change the font of the plottable
  15297. name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref
  15298. QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding.
  15299. The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend
  15300. creates/removes legend items of this type.
  15301. Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of
  15302. QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout
  15303. interface, QCPLegend has specialized functions for handling legend items conveniently, see the
  15304. documentation of \ref QCPLegend.
  15305. */
  15306. /*!
  15307. Creates a new legend item associated with \a plottable.
  15308. Once it's created, it can be added to the legend via \ref QCPLegend::addItem.
  15309. A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref
  15310. QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend.
  15311. */
  15312. QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) :
  15313. QCPAbstractLegendItem(parent),
  15314. mPlottable(plottable)
  15315. {
  15316. setAntialiased(false);
  15317. }
  15318. /*! \internal
  15319. Returns the pen that shall be used to draw the icon border, taking into account the selection
  15320. state of this item.
  15321. */
  15322. QPen QCPPlottableLegendItem::getIconBorderPen() const
  15323. {
  15324. return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen();
  15325. }
  15326. /*! \internal
  15327. Returns the text color that shall be used to draw text, taking into account the selection state
  15328. of this item.
  15329. */
  15330. QColor QCPPlottableLegendItem::getTextColor() const
  15331. {
  15332. return mSelected ? mSelectedTextColor : mTextColor;
  15333. }
  15334. /*! \internal
  15335. Returns the font that shall be used to draw text, taking into account the selection state of this
  15336. item.
  15337. */
  15338. QFont QCPPlottableLegendItem::getFont() const
  15339. {
  15340. return mSelected ? mSelectedFont : mFont;
  15341. }
  15342. /*! \internal
  15343. Draws the item with \a painter. The size and position of the drawn legend item is defined by the
  15344. parent layout (typically a \ref QCPLegend) and the \ref minimumOuterSizeHint and \ref
  15345. maximumOuterSizeHint of this legend item.
  15346. */
  15347. void QCPPlottableLegendItem::draw(QCPPainter *painter)
  15348. {
  15349. if (!mPlottable) return;
  15350. painter->setFont(getFont());
  15351. painter->setPen(QPen(getTextColor()));
  15352. QSizeF iconSize = mParentLegend->iconSize();
  15353. QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
  15354. QRectF iconRect(mRect.topLeft(), iconSize);
  15355. int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops
  15356. painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name());
  15357. // draw icon:
  15358. painter->save();
  15359. painter->setClipRect(iconRect, Qt::IntersectClip);
  15360. mPlottable->drawLegendIcon(painter, iconRect);
  15361. painter->restore();
  15362. // draw icon border:
  15363. if (getIconBorderPen().style() != Qt::NoPen)
  15364. {
  15365. painter->setPen(getIconBorderPen());
  15366. painter->setBrush(Qt::NoBrush);
  15367. int halfPen = qCeil(painter->pen().widthF()*0.5)+1;
  15368. painter->setClipRect(mOuterRect.adjusted(-halfPen, -halfPen, halfPen, halfPen)); // extend default clip rect so thicker pens (especially during selection) are not clipped
  15369. painter->drawRect(iconRect);
  15370. }
  15371. }
  15372. /*! \internal
  15373. Calculates and returns the size of this item. This includes the icon, the text and the padding in
  15374. between.
  15375. \seebaseclassmethod
  15376. */
  15377. QSize QCPPlottableLegendItem::minimumOuterSizeHint() const
  15378. {
  15379. if (!mPlottable) return QSize();
  15380. QSize result(0, 0);
  15381. QRect textRect;
  15382. QFontMetrics fontMetrics(getFont());
  15383. QSize iconSize = mParentLegend->iconSize();
  15384. textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
  15385. result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width());
  15386. result.setHeight(qMax(textRect.height(), iconSize.height()));
  15387. result.rwidth() += mMargins.left()+mMargins.right();
  15388. result.rheight() += mMargins.top()+mMargins.bottom();
  15389. return result;
  15390. }
  15391. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15392. //////////////////// QCPLegend
  15393. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15394. /*! \class QCPLegend
  15395. \brief Manages a legend inside a QCustomPlot.
  15396. A legend is a small box somewhere in the plot which lists plottables with their name and icon.
  15397. A legend is populated with legend items by calling \ref QCPAbstractPlottable::addToLegend on the
  15398. plottable, for which a legend item shall be created. In the case of the main legend (\ref
  15399. QCustomPlot::legend), simply adding plottables to the plot while \ref
  15400. QCustomPlot::setAutoAddPlottableToLegend is set to true (the default) creates corresponding
  15401. legend items. The legend item associated with a certain plottable can be removed with \ref
  15402. QCPAbstractPlottable::removeFromLegend. However, QCPLegend also offers an interface to add and
  15403. manipulate legend items directly: \ref item, \ref itemWithPlottable, \ref itemCount, \ref
  15404. addItem, \ref removeItem, etc.
  15405. Since \ref QCPLegend derives from \ref QCPLayoutGrid, it can be placed in any position a \ref
  15406. QCPLayoutElement may be positioned. The legend items are themselves \ref QCPLayoutElement
  15407. "QCPLayoutElements" which are placed in the grid layout of the legend. \ref QCPLegend only adds
  15408. an interface specialized for handling child elements of type \ref QCPAbstractLegendItem, as
  15409. mentioned above. In principle, any other layout elements may also be added to a legend via the
  15410. normal \ref QCPLayoutGrid interface. See the special page about \link thelayoutsystem The Layout
  15411. System\endlink for examples on how to add other elements to the legend and move it outside the axis
  15412. rect.
  15413. Use the methods \ref setFillOrder and \ref setWrap inherited from \ref QCPLayoutGrid to control
  15414. in which order (column first or row first) the legend is filled up when calling \ref addItem, and
  15415. at which column or row wrapping occurs.
  15416. By default, every QCustomPlot has one legend (\ref QCustomPlot::legend) which is placed in the
  15417. inset layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another
  15418. position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend
  15419. outside of the axis rect, place it anywhere else with the \ref QCPLayout/\ref QCPLayoutElement
  15420. interface.
  15421. */
  15422. /* start of documentation of signals */
  15423. /*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection);
  15424. This signal is emitted when the selection state of this legend has changed.
  15425. \see setSelectedParts, setSelectableParts
  15426. */
  15427. /* end of documentation of signals */
  15428. /*!
  15429. Constructs a new QCPLegend instance with default values.
  15430. Note that by default, QCustomPlot already contains a legend ready to be used as \ref
  15431. QCustomPlot::legend
  15432. */
  15433. QCPLegend::QCPLegend()
  15434. {
  15435. setFillOrder(QCPLayoutGrid::foRowsFirst);
  15436. setWrap(0);
  15437. setRowSpacing(3);
  15438. setColumnSpacing(8);
  15439. setMargins(QMargins(7, 5, 7, 4));
  15440. setAntialiased(false);
  15441. setIconSize(32, 18);
  15442. setIconTextPadding(7);
  15443. setSelectableParts(spLegendBox | spItems);
  15444. setSelectedParts(spNone);
  15445. setBorderPen(QPen(Qt::black, 0));
  15446. setSelectedBorderPen(QPen(Qt::blue, 2));
  15447. setIconBorderPen(Qt::NoPen);
  15448. setSelectedIconBorderPen(QPen(Qt::blue, 2));
  15449. setBrush(Qt::white);
  15450. setSelectedBrush(Qt::white);
  15451. setTextColor(Qt::black);
  15452. setSelectedTextColor(Qt::blue);
  15453. }
  15454. QCPLegend::~QCPLegend()
  15455. {
  15456. clearItems();
  15457. 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)
  15458. mParentPlot->legendRemoved(this);
  15459. }
  15460. /* no doc for getter, see setSelectedParts */
  15461. QCPLegend::SelectableParts QCPLegend::selectedParts() const
  15462. {
  15463. // check whether any legend elements selected, if yes, add spItems to return value
  15464. bool hasSelectedItems = false;
  15465. for (int i=0; i<itemCount(); ++i)
  15466. {
  15467. if (item(i) && item(i)->selected())
  15468. {
  15469. hasSelectedItems = true;
  15470. break;
  15471. }
  15472. }
  15473. if (hasSelectedItems)
  15474. return mSelectedParts | spItems;
  15475. else
  15476. return mSelectedParts & ~spItems;
  15477. }
  15478. /*!
  15479. Sets the pen, the border of the entire legend is drawn with.
  15480. */
  15481. void QCPLegend::setBorderPen(const QPen &pen)
  15482. {
  15483. mBorderPen = pen;
  15484. }
  15485. /*!
  15486. Sets the brush of the legend background.
  15487. */
  15488. void QCPLegend::setBrush(const QBrush &brush)
  15489. {
  15490. mBrush = brush;
  15491. }
  15492. /*!
  15493. Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will
  15494. use this font by default. However, a different font can be specified on a per-item-basis by
  15495. accessing the specific legend item.
  15496. This function will also set \a font on all already existing legend items.
  15497. \see QCPAbstractLegendItem::setFont
  15498. */
  15499. void QCPLegend::setFont(const QFont &font)
  15500. {
  15501. mFont = font;
  15502. for (int i=0; i<itemCount(); ++i)
  15503. {
  15504. if (item(i))
  15505. item(i)->setFont(mFont);
  15506. }
  15507. }
  15508. /*!
  15509. Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph)
  15510. will use this color by default. However, a different colors can be specified on a per-item-basis
  15511. by accessing the specific legend item.
  15512. This function will also set \a color on all already existing legend items.
  15513. \see QCPAbstractLegendItem::setTextColor
  15514. */
  15515. void QCPLegend::setTextColor(const QColor &color)
  15516. {
  15517. mTextColor = color;
  15518. for (int i=0; i<itemCount(); ++i)
  15519. {
  15520. if (item(i))
  15521. item(i)->setTextColor(color);
  15522. }
  15523. }
  15524. /*!
  15525. Sets the size of legend icons. Legend items that draw an icon (e.g. a visual
  15526. representation of the graph) will use this size by default.
  15527. */
  15528. void QCPLegend::setIconSize(const QSize &size)
  15529. {
  15530. mIconSize = size;
  15531. }
  15532. /*! \overload
  15533. */
  15534. void QCPLegend::setIconSize(int width, int height)
  15535. {
  15536. mIconSize.setWidth(width);
  15537. mIconSize.setHeight(height);
  15538. }
  15539. /*!
  15540. Sets the horizontal space in pixels between the legend icon and the text next to it.
  15541. Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the
  15542. name of the graph) will use this space by default.
  15543. */
  15544. void QCPLegend::setIconTextPadding(int padding)
  15545. {
  15546. mIconTextPadding = padding;
  15547. }
  15548. /*!
  15549. Sets the pen used to draw a border around each legend icon. Legend items that draw an
  15550. icon (e.g. a visual representation of the graph) will use this pen by default.
  15551. If no border is wanted, set this to \a Qt::NoPen.
  15552. */
  15553. void QCPLegend::setIconBorderPen(const QPen &pen)
  15554. {
  15555. mIconBorderPen = pen;
  15556. }
  15557. /*!
  15558. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  15559. (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.)
  15560. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  15561. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  15562. directly.
  15563. \see SelectablePart, setSelectedParts
  15564. */
  15565. void QCPLegend::setSelectableParts(const SelectableParts &selectable)
  15566. {
  15567. if (mSelectableParts != selectable)
  15568. {
  15569. mSelectableParts = selectable;
  15570. emit selectableChanged(mSelectableParts);
  15571. }
  15572. }
  15573. /*!
  15574. Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part
  15575. is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected
  15576. doesn't contain \ref spItems, those items become deselected.
  15577. The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions
  15578. contains iSelectLegend. You only need to call this function when you wish to change the selection
  15579. state manually.
  15580. This function can change the selection state of a part even when \ref setSelectableParts was set to a
  15581. value that actually excludes the part.
  15582. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  15583. Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set
  15584. before, because there's no way to specify which exact items to newly select. Do this by calling
  15585. \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select.
  15586. \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush,
  15587. setSelectedFont
  15588. */
  15589. void QCPLegend::setSelectedParts(const SelectableParts &selected)
  15590. {
  15591. SelectableParts newSelected = selected;
  15592. mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed
  15593. if (mSelectedParts != newSelected)
  15594. {
  15595. if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that)
  15596. {
  15597. qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function";
  15598. newSelected &= ~spItems;
  15599. }
  15600. if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection
  15601. {
  15602. for (int i=0; i<itemCount(); ++i)
  15603. {
  15604. if (item(i))
  15605. item(i)->setSelected(false);
  15606. }
  15607. }
  15608. mSelectedParts = newSelected;
  15609. emit selectionChanged(mSelectedParts);
  15610. }
  15611. }
  15612. /*!
  15613. When the legend box is selected, this pen is used to draw the border instead of the normal pen
  15614. set via \ref setBorderPen.
  15615. \see setSelectedParts, setSelectableParts, setSelectedBrush
  15616. */
  15617. void QCPLegend::setSelectedBorderPen(const QPen &pen)
  15618. {
  15619. mSelectedBorderPen = pen;
  15620. }
  15621. /*!
  15622. Sets the pen legend items will use to draw their icon borders, when they are selected.
  15623. \see setSelectedParts, setSelectableParts, setSelectedFont
  15624. */
  15625. void QCPLegend::setSelectedIconBorderPen(const QPen &pen)
  15626. {
  15627. mSelectedIconBorderPen = pen;
  15628. }
  15629. /*!
  15630. When the legend box is selected, this brush is used to draw the legend background instead of the normal brush
  15631. set via \ref setBrush.
  15632. \see setSelectedParts, setSelectableParts, setSelectedBorderPen
  15633. */
  15634. void QCPLegend::setSelectedBrush(const QBrush &brush)
  15635. {
  15636. mSelectedBrush = brush;
  15637. }
  15638. /*!
  15639. Sets the default font that is used by legend items when they are selected.
  15640. This function will also set \a font on all already existing legend items.
  15641. \see setFont, QCPAbstractLegendItem::setSelectedFont
  15642. */
  15643. void QCPLegend::setSelectedFont(const QFont &font)
  15644. {
  15645. mSelectedFont = font;
  15646. for (int i=0; i<itemCount(); ++i)
  15647. {
  15648. if (item(i))
  15649. item(i)->setSelectedFont(font);
  15650. }
  15651. }
  15652. /*!
  15653. Sets the default text color that is used by legend items when they are selected.
  15654. This function will also set \a color on all already existing legend items.
  15655. \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor
  15656. */
  15657. void QCPLegend::setSelectedTextColor(const QColor &color)
  15658. {
  15659. mSelectedTextColor = color;
  15660. for (int i=0; i<itemCount(); ++i)
  15661. {
  15662. if (item(i))
  15663. item(i)->setSelectedTextColor(color);
  15664. }
  15665. }
  15666. /*!
  15667. Returns the item with index \a i.
  15668. Note that the linear index depends on the current fill order (\ref setFillOrder).
  15669. \see itemCount, addItem, itemWithPlottable
  15670. */
  15671. QCPAbstractLegendItem *QCPLegend::item(int index) const
  15672. {
  15673. return qobject_cast<QCPAbstractLegendItem*>(elementAt(index));
  15674. }
  15675. /*!
  15676. Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
  15677. If such an item isn't in the legend, returns 0.
  15678. \see hasItemWithPlottable
  15679. */
  15680. QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const
  15681. {
  15682. for (int i=0; i<itemCount(); ++i)
  15683. {
  15684. if (QCPPlottableLegendItem *pli = qobject_cast<QCPPlottableLegendItem*>(item(i)))
  15685. {
  15686. if (pli->plottable() == plottable)
  15687. return pli;
  15688. }
  15689. }
  15690. return 0;
  15691. }
  15692. /*!
  15693. Returns the number of items currently in the legend.
  15694. Note that if empty cells are in the legend (e.g. by calling methods of the \ref QCPLayoutGrid
  15695. base class which allows creating empty cells), they are included in the returned count.
  15696. \see item
  15697. */
  15698. int QCPLegend::itemCount() const
  15699. {
  15700. return elementCount();
  15701. }
  15702. /*!
  15703. Returns whether the legend contains \a item.
  15704. \see hasItemWithPlottable
  15705. */
  15706. bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const
  15707. {
  15708. for (int i=0; i<itemCount(); ++i)
  15709. {
  15710. if (item == this->item(i))
  15711. return true;
  15712. }
  15713. return false;
  15714. }
  15715. /*!
  15716. Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
  15717. If such an item isn't in the legend, returns false.
  15718. \see itemWithPlottable
  15719. */
  15720. bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const
  15721. {
  15722. return itemWithPlottable(plottable);
  15723. }
  15724. /*!
  15725. Adds \a item to the legend, if it's not present already. The element is arranged according to the
  15726. current fill order (\ref setFillOrder) and wrapping (\ref setWrap).
  15727. Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added.
  15728. The legend takes ownership of the item.
  15729. \see removeItem, item, hasItem
  15730. */
  15731. bool QCPLegend::addItem(QCPAbstractLegendItem *item)
  15732. {
  15733. return addElement(item);
  15734. }
  15735. /*! \overload
  15736. Removes the item with the specified \a index from the legend and deletes it.
  15737. After successful removal, the legend is reordered according to the current fill order (\ref
  15738. setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item
  15739. was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid.
  15740. Returns true, if successful. Unlike \ref QCPLayoutGrid::removeAt, this method only removes
  15741. elements derived from \ref QCPAbstractLegendItem.
  15742. \see itemCount, clearItems
  15743. */
  15744. bool QCPLegend::removeItem(int index)
  15745. {
  15746. if (QCPAbstractLegendItem *ali = item(index))
  15747. {
  15748. bool success = remove(ali);
  15749. if (success)
  15750. setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering
  15751. return success;
  15752. } else
  15753. return false;
  15754. }
  15755. /*! \overload
  15756. Removes \a item from the legend and deletes it.
  15757. After successful removal, the legend is reordered according to the current fill order (\ref
  15758. setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item
  15759. was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid.
  15760. Returns true, if successful.
  15761. \see clearItems
  15762. */
  15763. bool QCPLegend::removeItem(QCPAbstractLegendItem *item)
  15764. {
  15765. bool success = remove(item);
  15766. if (success)
  15767. setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering
  15768. return success;
  15769. }
  15770. /*!
  15771. Removes all items from the legend.
  15772. */
  15773. void QCPLegend::clearItems()
  15774. {
  15775. for (int i=itemCount()-1; i>=0; --i)
  15776. removeItem(i);
  15777. }
  15778. /*!
  15779. Returns the legend items that are currently selected. If no items are selected,
  15780. the list is empty.
  15781. \see QCPAbstractLegendItem::setSelected, setSelectable
  15782. */
  15783. QList<QCPAbstractLegendItem *> QCPLegend::selectedItems() const
  15784. {
  15785. QList<QCPAbstractLegendItem*> result;
  15786. for (int i=0; i<itemCount(); ++i)
  15787. {
  15788. if (QCPAbstractLegendItem *ali = item(i))
  15789. {
  15790. if (ali->selected())
  15791. result.append(ali);
  15792. }
  15793. }
  15794. return result;
  15795. }
  15796. /*! \internal
  15797. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  15798. before drawing main legend elements.
  15799. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  15800. This function takes into account the local setting of the antialiasing flag as well as the
  15801. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  15802. QCustomPlot::setNotAntialiasedElements.
  15803. \seebaseclassmethod
  15804. \see setAntialiased
  15805. */
  15806. void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const
  15807. {
  15808. applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend);
  15809. }
  15810. /*! \internal
  15811. Returns the pen used to paint the border of the legend, taking into account the selection state
  15812. of the legend box.
  15813. */
  15814. QPen QCPLegend::getBorderPen() const
  15815. {
  15816. return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen;
  15817. }
  15818. /*! \internal
  15819. Returns the brush used to paint the background of the legend, taking into account the selection
  15820. state of the legend box.
  15821. */
  15822. QBrush QCPLegend::getBrush() const
  15823. {
  15824. return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush;
  15825. }
  15826. /*! \internal
  15827. Draws the legend box with the provided \a painter. The individual legend items are layerables
  15828. themselves, thus are drawn independently.
  15829. */
  15830. void QCPLegend::draw(QCPPainter *painter)
  15831. {
  15832. // draw background rect:
  15833. painter->setBrush(getBrush());
  15834. painter->setPen(getBorderPen());
  15835. painter->drawRect(mOuterRect);
  15836. }
  15837. /* inherits documentation from base class */
  15838. double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  15839. {
  15840. if (!mParentPlot) return -1;
  15841. if (onlySelectable && !mSelectableParts.testFlag(spLegendBox))
  15842. return -1;
  15843. if (mOuterRect.contains(pos.toPoint()))
  15844. {
  15845. if (details) details->setValue(spLegendBox);
  15846. return mParentPlot->selectionTolerance()*0.99;
  15847. }
  15848. return -1;
  15849. }
  15850. /* inherits documentation from base class */
  15851. void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  15852. {
  15853. Q_UNUSED(event)
  15854. mSelectedParts = selectedParts(); // in case item selection has changed
  15855. if (details.value<SelectablePart>() == spLegendBox && mSelectableParts.testFlag(spLegendBox))
  15856. {
  15857. SelectableParts selBefore = mSelectedParts;
  15858. 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)
  15859. if (selectionStateChanged)
  15860. *selectionStateChanged = mSelectedParts != selBefore;
  15861. }
  15862. }
  15863. /* inherits documentation from base class */
  15864. void QCPLegend::deselectEvent(bool *selectionStateChanged)
  15865. {
  15866. mSelectedParts = selectedParts(); // in case item selection has changed
  15867. if (mSelectableParts.testFlag(spLegendBox))
  15868. {
  15869. SelectableParts selBefore = mSelectedParts;
  15870. setSelectedParts(selectedParts() & ~spLegendBox);
  15871. if (selectionStateChanged)
  15872. *selectionStateChanged = mSelectedParts != selBefore;
  15873. }
  15874. }
  15875. /* inherits documentation from base class */
  15876. QCP::Interaction QCPLegend::selectionCategory() const
  15877. {
  15878. return QCP::iSelectLegend;
  15879. }
  15880. /* inherits documentation from base class */
  15881. QCP::Interaction QCPAbstractLegendItem::selectionCategory() const
  15882. {
  15883. return QCP::iSelectLegend;
  15884. }
  15885. /* inherits documentation from base class */
  15886. void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot)
  15887. {
  15888. if (parentPlot && !parentPlot->legend)
  15889. parentPlot->legend = this;
  15890. }
  15891. /* end of 'src/layoutelements/layoutelement-legend.cpp' */
  15892. /* including file 'src/layoutelements/layoutelement-textelement.cpp', size 12761 */
  15893. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  15894. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15895. //////////////////// QCPTextElement
  15896. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15897. /*! \class QCPTextElement
  15898. \brief A layout element displaying a text
  15899. The text may be specified with \ref setText, the formatting can be controlled with \ref setFont,
  15900. \ref setTextColor, and \ref setTextFlags.
  15901. A text element can be added as follows:
  15902. \snippet documentation/doc-code-snippets/mainwindow.cpp qcptextelement-creation
  15903. */
  15904. /* start documentation of signals */
  15905. /*! \fn void QCPTextElement::selectionChanged(bool selected)
  15906. This signal is emitted when the selection state has changed to \a selected, either by user
  15907. interaction or by a direct call to \ref setSelected.
  15908. \see setSelected, setSelectable
  15909. */
  15910. /*! \fn void QCPTextElement::clicked(QMouseEvent *event)
  15911. This signal is emitted when the text element is clicked.
  15912. \see doubleClicked, selectTest
  15913. */
  15914. /*! \fn void QCPTextElement::doubleClicked(QMouseEvent *event)
  15915. This signal is emitted when the text element is double clicked.
  15916. \see clicked, selectTest
  15917. */
  15918. /* end documentation of signals */
  15919. /*! \overload
  15920. Creates a new QCPTextElement instance and sets default values. The initial text is empty (\ref
  15921. setText).
  15922. */
  15923. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot) :
  15924. QCPLayoutElement(parentPlot),
  15925. mText(),
  15926. mTextFlags(Qt::AlignCenter|Qt::TextWordWrap),
  15927. mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  15928. mTextColor(Qt::black),
  15929. mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  15930. mSelectedTextColor(Qt::blue),
  15931. mSelectable(false),
  15932. mSelected(false)
  15933. {
  15934. if (parentPlot)
  15935. {
  15936. mFont = parentPlot->font();
  15937. mSelectedFont = parentPlot->font();
  15938. }
  15939. setMargins(QMargins(2, 2, 2, 2));
  15940. }
  15941. /*! \overload
  15942. Creates a new QCPTextElement instance and sets default values.
  15943. The initial text is set to \a text.
  15944. */
  15945. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text) :
  15946. QCPLayoutElement(parentPlot),
  15947. mText(text),
  15948. mTextFlags(Qt::AlignCenter|Qt::TextWordWrap),
  15949. mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  15950. mTextColor(Qt::black),
  15951. mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  15952. mSelectedTextColor(Qt::blue),
  15953. mSelectable(false),
  15954. mSelected(false)
  15955. {
  15956. if (parentPlot)
  15957. {
  15958. mFont = parentPlot->font();
  15959. mSelectedFont = parentPlot->font();
  15960. }
  15961. setMargins(QMargins(2, 2, 2, 2));
  15962. }
  15963. /*! \overload
  15964. Creates a new QCPTextElement instance and sets default values.
  15965. The initial text is set to \a text with \a pointSize.
  15966. */
  15967. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, double pointSize) :
  15968. QCPLayoutElement(parentPlot),
  15969. mText(text),
  15970. mTextFlags(Qt::AlignCenter|Qt::TextWordWrap),
  15971. mFont(QFont(QLatin1String("sans serif"), pointSize)), // will be taken from parentPlot if available, see below
  15972. mTextColor(Qt::black),
  15973. mSelectedFont(QFont(QLatin1String("sans serif"), pointSize)), // will be taken from parentPlot if available, see below
  15974. mSelectedTextColor(Qt::blue),
  15975. mSelectable(false),
  15976. mSelected(false)
  15977. {
  15978. if (parentPlot)
  15979. {
  15980. mFont = parentPlot->font();
  15981. mFont.setPointSizeF(pointSize);
  15982. mSelectedFont = parentPlot->font();
  15983. mSelectedFont.setPointSizeF(pointSize);
  15984. }
  15985. setMargins(QMargins(2, 2, 2, 2));
  15986. }
  15987. /*! \overload
  15988. Creates a new QCPTextElement instance and sets default values.
  15989. The initial text is set to \a text with \a pointSize and the specified \a fontFamily.
  15990. */
  15991. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QString &fontFamily, double pointSize) :
  15992. QCPLayoutElement(parentPlot),
  15993. mText(text),
  15994. mTextFlags(Qt::AlignCenter|Qt::TextWordWrap),
  15995. mFont(QFont(fontFamily, pointSize)),
  15996. mTextColor(Qt::black),
  15997. mSelectedFont(QFont(fontFamily, pointSize)),
  15998. mSelectedTextColor(Qt::blue),
  15999. mSelectable(false),
  16000. mSelected(false)
  16001. {
  16002. setMargins(QMargins(2, 2, 2, 2));
  16003. }
  16004. /*! \overload
  16005. Creates a new QCPTextElement instance and sets default values.
  16006. The initial text is set to \a text with the specified \a font.
  16007. */
  16008. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QFont &font) :
  16009. QCPLayoutElement(parentPlot),
  16010. mText(text),
  16011. mTextFlags(Qt::AlignCenter|Qt::TextWordWrap),
  16012. mFont(font),
  16013. mTextColor(Qt::black),
  16014. mSelectedFont(font),
  16015. mSelectedTextColor(Qt::blue),
  16016. mSelectable(false),
  16017. mSelected(false)
  16018. {
  16019. setMargins(QMargins(2, 2, 2, 2));
  16020. }
  16021. /*!
  16022. Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n".
  16023. \see setFont, setTextColor, setTextFlags
  16024. */
  16025. void QCPTextElement::setText(const QString &text)
  16026. {
  16027. mText = text;
  16028. }
  16029. /*!
  16030. Sets options for text alignment and wrapping behaviour. \a flags is a bitwise OR-combination of
  16031. \c Qt::AlignmentFlag and \c Qt::TextFlag enums.
  16032. Possible enums are:
  16033. - Qt::AlignLeft
  16034. - Qt::AlignRight
  16035. - Qt::AlignHCenter
  16036. - Qt::AlignJustify
  16037. - Qt::AlignTop
  16038. - Qt::AlignBottom
  16039. - Qt::AlignVCenter
  16040. - Qt::AlignCenter
  16041. - Qt::TextDontClip
  16042. - Qt::TextSingleLine
  16043. - Qt::TextExpandTabs
  16044. - Qt::TextShowMnemonic
  16045. - Qt::TextWordWrap
  16046. - Qt::TextIncludeTrailingSpaces
  16047. */
  16048. void QCPTextElement::setTextFlags(int flags)
  16049. {
  16050. mTextFlags = flags;
  16051. }
  16052. /*!
  16053. Sets the \a font of the text.
  16054. \see setTextColor, setSelectedFont
  16055. */
  16056. void QCPTextElement::setFont(const QFont &font)
  16057. {
  16058. mFont = font;
  16059. }
  16060. /*!
  16061. Sets the \a color of the text.
  16062. \see setFont, setSelectedTextColor
  16063. */
  16064. void QCPTextElement::setTextColor(const QColor &color)
  16065. {
  16066. mTextColor = color;
  16067. }
  16068. /*!
  16069. Sets the \a font of the text that will be used if the text element is selected (\ref setSelected).
  16070. \see setFont
  16071. */
  16072. void QCPTextElement::setSelectedFont(const QFont &font)
  16073. {
  16074. mSelectedFont = font;
  16075. }
  16076. /*!
  16077. Sets the \a color of the text that will be used if the text element is selected (\ref setSelected).
  16078. \see setTextColor
  16079. */
  16080. void QCPTextElement::setSelectedTextColor(const QColor &color)
  16081. {
  16082. mSelectedTextColor = color;
  16083. }
  16084. /*!
  16085. Sets whether the user may select this text element.
  16086. Note that even when \a selectable is set to <tt>false</tt>, the selection state may be changed
  16087. programmatically via \ref setSelected.
  16088. */
  16089. void QCPTextElement::setSelectable(bool selectable)
  16090. {
  16091. if (mSelectable != selectable)
  16092. {
  16093. mSelectable = selectable;
  16094. emit selectableChanged(mSelectable);
  16095. }
  16096. }
  16097. /*!
  16098. Sets the selection state of this text element to \a selected. If the selection has changed, \ref
  16099. selectionChanged is emitted.
  16100. Note that this function can change the selection state independently of the current \ref
  16101. setSelectable state.
  16102. */
  16103. void QCPTextElement::setSelected(bool selected)
  16104. {
  16105. if (mSelected != selected)
  16106. {
  16107. mSelected = selected;
  16108. emit selectionChanged(mSelected);
  16109. }
  16110. }
  16111. /* inherits documentation from base class */
  16112. void QCPTextElement::applyDefaultAntialiasingHint(QCPPainter *painter) const
  16113. {
  16114. applyAntialiasingHint(painter, mAntialiased, QCP::aeOther);
  16115. }
  16116. /* inherits documentation from base class */
  16117. void QCPTextElement::draw(QCPPainter *painter)
  16118. {
  16119. painter->setFont(mainFont());
  16120. painter->setPen(QPen(mainTextColor()));
  16121. painter->drawText(mRect, Qt::AlignCenter, mText, &mTextBoundingRect);
  16122. }
  16123. /* inherits documentation from base class */
  16124. QSize QCPTextElement::minimumOuterSizeHint() const
  16125. {
  16126. QFontMetrics metrics(mFont);
  16127. QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size());
  16128. result.rwidth() += mMargins.left()+mMargins.right();
  16129. result.rheight() += mMargins.top()+mMargins.bottom();
  16130. return result;
  16131. }
  16132. /* inherits documentation from base class */
  16133. QSize QCPTextElement::maximumOuterSizeHint() const
  16134. {
  16135. QFontMetrics metrics(mFont);
  16136. QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size());
  16137. result.setWidth(QWIDGETSIZE_MAX);
  16138. result.rheight() += mMargins.top()+mMargins.bottom();
  16139. return result;
  16140. }
  16141. /* inherits documentation from base class */
  16142. void QCPTextElement::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  16143. {
  16144. Q_UNUSED(event)
  16145. Q_UNUSED(details)
  16146. if (mSelectable)
  16147. {
  16148. bool selBefore = mSelected;
  16149. setSelected(additive ? !mSelected : true);
  16150. if (selectionStateChanged)
  16151. *selectionStateChanged = mSelected != selBefore;
  16152. }
  16153. }
  16154. /* inherits documentation from base class */
  16155. void QCPTextElement::deselectEvent(bool *selectionStateChanged)
  16156. {
  16157. if (mSelectable)
  16158. {
  16159. bool selBefore = mSelected;
  16160. setSelected(false);
  16161. if (selectionStateChanged)
  16162. *selectionStateChanged = mSelected != selBefore;
  16163. }
  16164. }
  16165. /*!
  16166. Returns 0.99*selectionTolerance (see \ref QCustomPlot::setSelectionTolerance) when \a pos is
  16167. within the bounding box of the text element's text. Note that this bounding box is updated in the
  16168. draw call.
  16169. If \a pos is outside the text's bounding box or if \a onlySelectable is true and this text
  16170. element is not selectable (\ref setSelectable), returns -1.
  16171. \seebaseclassmethod
  16172. */
  16173. double QCPTextElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  16174. {
  16175. Q_UNUSED(details)
  16176. if (onlySelectable && !mSelectable)
  16177. return -1;
  16178. if (mTextBoundingRect.contains(pos.toPoint()))
  16179. return mParentPlot->selectionTolerance()*0.99;
  16180. else
  16181. return -1;
  16182. }
  16183. /*!
  16184. Accepts the mouse event in order to emit the according click signal in the \ref
  16185. mouseReleaseEvent.
  16186. \seebaseclassmethod
  16187. */
  16188. void QCPTextElement::mousePressEvent(QMouseEvent *event, const QVariant &details)
  16189. {
  16190. Q_UNUSED(details)
  16191. event->accept();
  16192. }
  16193. /*!
  16194. Emits the \ref clicked signal if the cursor hasn't moved by more than a few pixels since the \ref
  16195. mousePressEvent.
  16196. \seebaseclassmethod
  16197. */
  16198. void QCPTextElement::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  16199. {
  16200. if ((QPointF(event->pos())-startPos).manhattanLength() <= 3)
  16201. emit clicked(event);
  16202. }
  16203. /*!
  16204. Emits the \ref doubleClicked signal.
  16205. \seebaseclassmethod
  16206. */
  16207. void QCPTextElement::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details)
  16208. {
  16209. Q_UNUSED(details)
  16210. emit doubleClicked(event);
  16211. }
  16212. /*! \internal
  16213. Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to
  16214. <tt>true</tt>, else mFont is returned.
  16215. */
  16216. QFont QCPTextElement::mainFont() const
  16217. {
  16218. return mSelected ? mSelectedFont : mFont;
  16219. }
  16220. /*! \internal
  16221. Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to
  16222. <tt>true</tt>, else mTextColor is returned.
  16223. */
  16224. QColor QCPTextElement::mainTextColor() const
  16225. {
  16226. return mSelected ? mSelectedTextColor : mTextColor;
  16227. }
  16228. /* end of 'src/layoutelements/layoutelement-textelement.cpp' */
  16229. /* including file 'src/layoutelements/layoutelement-colorscale.cpp', size 25770 */
  16230. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  16231. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16232. //////////////////// QCPColorScale
  16233. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16234. /*! \class QCPColorScale
  16235. \brief A color scale for use with color coding data such as QCPColorMap
  16236. This layout element can be placed on the plot to correlate a color gradient with data values. It
  16237. is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps".
  16238. \image html QCPColorScale.png
  16239. The color scale can be either horizontal or vertical, as shown in the image above. The
  16240. orientation and the side where the numbers appear is controlled with \ref setType.
  16241. Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are
  16242. connected, they share their gradient, data range and data scale type (\ref setGradient, \ref
  16243. setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color
  16244. scale, to make them all synchronize these properties.
  16245. To have finer control over the number display and axis behaviour, you can directly access the
  16246. \ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if
  16247. you want to change the number of automatically generated ticks, call
  16248. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-tickcount
  16249. Placing a color scale next to the main axis rect works like with any other layout element:
  16250. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-creation
  16251. In this case we have placed it to the right of the default axis rect, so it wasn't necessary to
  16252. call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color
  16253. scale can be set with \ref setLabel.
  16254. For optimum appearance (like in the image above), it may be desirable to line up the axis rect and
  16255. the borders of the color scale. Use a \ref QCPMarginGroup to achieve this:
  16256. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-margingroup
  16257. Color scales are initialized with a non-zero minimum top and bottom margin (\ref
  16258. setMinimumMargins), because vertical color scales are most common and the minimum top/bottom
  16259. margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a
  16260. horizontal color scale by setting \ref setType to \ref QCPAxis::atBottom or \ref QCPAxis::atTop, you
  16261. might want to also change the minimum margins accordingly, e.g. <tt>setMinimumMargins(QMargins(6, 0, 6, 0))</tt>.
  16262. */
  16263. /* start documentation of inline functions */
  16264. /*! \fn QCPAxis *QCPColorScale::axis() const
  16265. Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the
  16266. appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its
  16267. interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref
  16268. setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref
  16269. QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on
  16270. the QCPColorScale or on its QCPAxis.
  16271. If the type of the color scale is changed with \ref setType, the axis returned by this method
  16272. will change, too, to either the left, right, bottom or top axis, depending on which type was set.
  16273. */
  16274. /* end documentation of signals */
  16275. /* start documentation of signals */
  16276. /*! \fn void QCPColorScale::dataRangeChanged(const QCPRange &newRange);
  16277. This signal is emitted when the data range changes.
  16278. \see setDataRange
  16279. */
  16280. /*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
  16281. This signal is emitted when the data scale type changes.
  16282. \see setDataScaleType
  16283. */
  16284. /*! \fn void QCPColorScale::gradientChanged(const QCPColorGradient &newGradient);
  16285. This signal is emitted when the gradient changes.
  16286. \see setGradient
  16287. */
  16288. /* end documentation of signals */
  16289. /*!
  16290. Constructs a new QCPColorScale.
  16291. */
  16292. QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) :
  16293. QCPLayoutElement(parentPlot),
  16294. mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight
  16295. mDataScaleType(QCPAxis::stLinear),
  16296. mBarWidth(20),
  16297. mAxisRect(new QCPColorScaleAxisRectPrivate(this))
  16298. {
  16299. 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)
  16300. setType(QCPAxis::atRight);
  16301. setDataRange(QCPRange(0, 6));
  16302. }
  16303. QCPColorScale::~QCPColorScale()
  16304. {
  16305. delete mAxisRect;
  16306. }
  16307. /* undocumented getter */
  16308. QString QCPColorScale::label() const
  16309. {
  16310. if (!mColorAxis)
  16311. {
  16312. qDebug() << Q_FUNC_INFO << "internal color axis undefined";
  16313. return QString();
  16314. }
  16315. return mColorAxis.data()->label();
  16316. }
  16317. /* undocumented getter */
  16318. bool QCPColorScale::rangeDrag() const
  16319. {
  16320. if (!mAxisRect)
  16321. {
  16322. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  16323. return false;
  16324. }
  16325. return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) &&
  16326. mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) &&
  16327. mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
  16328. }
  16329. /* undocumented getter */
  16330. bool QCPColorScale::rangeZoom() const
  16331. {
  16332. if (!mAxisRect)
  16333. {
  16334. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  16335. return false;
  16336. }
  16337. return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) &&
  16338. mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) &&
  16339. mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
  16340. }
  16341. /*!
  16342. Sets at which side of the color scale the axis is placed, and thus also its orientation.
  16343. Note that after setting \a type to a different value, the axis returned by \ref axis() will
  16344. be a different one. The new axis will adopt the following properties from the previous axis: The
  16345. range, scale type, label and ticker (the latter will be shared and not copied).
  16346. */
  16347. void QCPColorScale::setType(QCPAxis::AxisType type)
  16348. {
  16349. if (!mAxisRect)
  16350. {
  16351. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  16352. return;
  16353. }
  16354. if (mType != type)
  16355. {
  16356. mType = type;
  16357. QCPRange rangeTransfer(0, 6);
  16358. QString labelTransfer;
  16359. QSharedPointer<QCPAxisTicker> tickerTransfer;
  16360. // transfer/revert some settings on old axis if it exists:
  16361. bool doTransfer = (bool)mColorAxis;
  16362. if (doTransfer)
  16363. {
  16364. rangeTransfer = mColorAxis.data()->range();
  16365. labelTransfer = mColorAxis.data()->label();
  16366. tickerTransfer = mColorAxis.data()->ticker();
  16367. mColorAxis.data()->setLabel(QString());
  16368. disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  16369. disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  16370. }
  16371. QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop;
  16372. foreach (QCPAxis::AxisType atype, allAxisTypes)
  16373. {
  16374. mAxisRect.data()->axis(atype)->setTicks(atype == mType);
  16375. mAxisRect.data()->axis(atype)->setTickLabels(atype== mType);
  16376. }
  16377. // set new mColorAxis pointer:
  16378. mColorAxis = mAxisRect.data()->axis(mType);
  16379. // transfer settings to new axis:
  16380. if (doTransfer)
  16381. {
  16382. 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)
  16383. mColorAxis.data()->setLabel(labelTransfer);
  16384. mColorAxis.data()->setTicker(tickerTransfer);
  16385. }
  16386. connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  16387. connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  16388. mAxisRect.data()->setRangeDragAxes(QList<QCPAxis*>() << mColorAxis.data());
  16389. }
  16390. }
  16391. /*!
  16392. Sets the range spanned by the color gradient and that is shown by the axis in the color scale.
  16393. It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is
  16394. also equivalent to directly accessing the \ref axis and setting its range with \ref
  16395. QCPAxis::setRange.
  16396. \see setDataScaleType, setGradient, rescaleDataRange
  16397. */
  16398. void QCPColorScale::setDataRange(const QCPRange &dataRange)
  16399. {
  16400. if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
  16401. {
  16402. mDataRange = dataRange;
  16403. if (mColorAxis)
  16404. mColorAxis.data()->setRange(mDataRange);
  16405. emit dataRangeChanged(mDataRange);
  16406. }
  16407. }
  16408. /*!
  16409. Sets the scale type of the color scale, i.e. whether values are linearly associated with colors
  16410. or logarithmically.
  16411. It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is
  16412. also equivalent to directly accessing the \ref axis and setting its scale type with \ref
  16413. QCPAxis::setScaleType.
  16414. \see setDataRange, setGradient
  16415. */
  16416. void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType)
  16417. {
  16418. if (mDataScaleType != scaleType)
  16419. {
  16420. mDataScaleType = scaleType;
  16421. if (mColorAxis)
  16422. mColorAxis.data()->setScaleType(mDataScaleType);
  16423. if (mDataScaleType == QCPAxis::stLogarithmic)
  16424. setDataRange(mDataRange.sanitizedForLogScale());
  16425. emit dataScaleTypeChanged(mDataScaleType);
  16426. }
  16427. }
  16428. /*!
  16429. Sets the color gradient that will be used to represent data values.
  16430. It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps.
  16431. \see setDataRange, setDataScaleType
  16432. */
  16433. void QCPColorScale::setGradient(const QCPColorGradient &gradient)
  16434. {
  16435. if (mGradient != gradient)
  16436. {
  16437. mGradient = gradient;
  16438. if (mAxisRect)
  16439. mAxisRect.data()->mGradientImageInvalidated = true;
  16440. emit gradientChanged(mGradient);
  16441. }
  16442. }
  16443. /*!
  16444. Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on
  16445. the internal \ref axis.
  16446. */
  16447. void QCPColorScale::setLabel(const QString &str)
  16448. {
  16449. if (!mColorAxis)
  16450. {
  16451. qDebug() << Q_FUNC_INFO << "internal color axis undefined";
  16452. return;
  16453. }
  16454. mColorAxis.data()->setLabel(str);
  16455. }
  16456. /*!
  16457. Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed
  16458. will have.
  16459. */
  16460. void QCPColorScale::setBarWidth(int width)
  16461. {
  16462. mBarWidth = width;
  16463. }
  16464. /*!
  16465. Sets whether the user can drag the data range (\ref setDataRange).
  16466. Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref
  16467. QCustomPlot::setInteractions) to allow range dragging.
  16468. */
  16469. void QCPColorScale::setRangeDrag(bool enabled)
  16470. {
  16471. if (!mAxisRect)
  16472. {
  16473. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  16474. return;
  16475. }
  16476. if (enabled)
  16477. mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType));
  16478. else
  16479. mAxisRect.data()->setRangeDrag(0);
  16480. }
  16481. /*!
  16482. Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel.
  16483. Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref
  16484. QCustomPlot::setInteractions) to allow range dragging.
  16485. */
  16486. void QCPColorScale::setRangeZoom(bool enabled)
  16487. {
  16488. if (!mAxisRect)
  16489. {
  16490. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  16491. return;
  16492. }
  16493. if (enabled)
  16494. mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType));
  16495. else
  16496. mAxisRect.data()->setRangeZoom(0);
  16497. }
  16498. /*!
  16499. Returns a list of all the color maps associated with this color scale.
  16500. */
  16501. QList<QCPColorMap*> QCPColorScale::colorMaps() const
  16502. {
  16503. QList<QCPColorMap*> result;
  16504. for (int i=0; i<mParentPlot->plottableCount(); ++i)
  16505. {
  16506. if (QCPColorMap *cm = qobject_cast<QCPColorMap*>(mParentPlot->plottable(i)))
  16507. if (cm->colorScale() == this)
  16508. result.append(cm);
  16509. }
  16510. return result;
  16511. }
  16512. /*!
  16513. Changes the data range such that all color maps associated with this color scale are fully mapped
  16514. to the gradient in the data dimension.
  16515. \see setDataRange
  16516. */
  16517. void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps)
  16518. {
  16519. QList<QCPColorMap*> maps = colorMaps();
  16520. QCPRange newRange;
  16521. bool haveRange = false;
  16522. QCP::SignDomain sign = QCP::sdBoth;
  16523. if (mDataScaleType == QCPAxis::stLogarithmic)
  16524. sign = (mDataRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  16525. for (int i=0; i<maps.size(); ++i)
  16526. {
  16527. if (!maps.at(i)->realVisibility() && onlyVisibleMaps)
  16528. continue;
  16529. QCPRange mapRange;
  16530. if (maps.at(i)->colorScale() == this)
  16531. {
  16532. bool currentFoundRange = true;
  16533. mapRange = maps.at(i)->data()->dataBounds();
  16534. if (sign == QCP::sdPositive)
  16535. {
  16536. if (mapRange.lower <= 0 && mapRange.upper > 0)
  16537. mapRange.lower = mapRange.upper*1e-3;
  16538. else if (mapRange.lower <= 0 && mapRange.upper <= 0)
  16539. currentFoundRange = false;
  16540. } else if (sign == QCP::sdNegative)
  16541. {
  16542. if (mapRange.upper >= 0 && mapRange.lower < 0)
  16543. mapRange.upper = mapRange.lower*1e-3;
  16544. else if (mapRange.upper >= 0 && mapRange.lower >= 0)
  16545. currentFoundRange = false;
  16546. }
  16547. if (currentFoundRange)
  16548. {
  16549. if (!haveRange)
  16550. newRange = mapRange;
  16551. else
  16552. newRange.expand(mapRange);
  16553. haveRange = true;
  16554. }
  16555. }
  16556. }
  16557. if (haveRange)
  16558. {
  16559. 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
  16560. {
  16561. 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
  16562. if (mDataScaleType == QCPAxis::stLinear)
  16563. {
  16564. newRange.lower = center-mDataRange.size()/2.0;
  16565. newRange.upper = center+mDataRange.size()/2.0;
  16566. } else // mScaleType == stLogarithmic
  16567. {
  16568. newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower);
  16569. newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower);
  16570. }
  16571. }
  16572. setDataRange(newRange);
  16573. }
  16574. }
  16575. /* inherits documentation from base class */
  16576. void QCPColorScale::update(UpdatePhase phase)
  16577. {
  16578. QCPLayoutElement::update(phase);
  16579. if (!mAxisRect)
  16580. {
  16581. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  16582. return;
  16583. }
  16584. mAxisRect.data()->update(phase);
  16585. switch (phase)
  16586. {
  16587. case upMargins:
  16588. {
  16589. if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop)
  16590. {
  16591. setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom());
  16592. setMinimumSize(0, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom());
  16593. } else
  16594. {
  16595. setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), QWIDGETSIZE_MAX);
  16596. setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), 0);
  16597. }
  16598. break;
  16599. }
  16600. case upLayout:
  16601. {
  16602. mAxisRect.data()->setOuterRect(rect());
  16603. break;
  16604. }
  16605. default: break;
  16606. }
  16607. }
  16608. /* inherits documentation from base class */
  16609. void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const
  16610. {
  16611. painter->setAntialiasing(false);
  16612. }
  16613. /* inherits documentation from base class */
  16614. void QCPColorScale::mousePressEvent(QMouseEvent *event, const QVariant &details)
  16615. {
  16616. if (!mAxisRect)
  16617. {
  16618. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  16619. return;
  16620. }
  16621. mAxisRect.data()->mousePressEvent(event, details);
  16622. }
  16623. /* inherits documentation from base class */
  16624. void QCPColorScale::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  16625. {
  16626. if (!mAxisRect)
  16627. {
  16628. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  16629. return;
  16630. }
  16631. mAxisRect.data()->mouseMoveEvent(event, startPos);
  16632. }
  16633. /* inherits documentation from base class */
  16634. void QCPColorScale::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  16635. {
  16636. if (!mAxisRect)
  16637. {
  16638. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  16639. return;
  16640. }
  16641. mAxisRect.data()->mouseReleaseEvent(event, startPos);
  16642. }
  16643. /* inherits documentation from base class */
  16644. void QCPColorScale::wheelEvent(QWheelEvent *event)
  16645. {
  16646. if (!mAxisRect)
  16647. {
  16648. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  16649. return;
  16650. }
  16651. mAxisRect.data()->wheelEvent(event);
  16652. }
  16653. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16654. //////////////////// QCPColorScaleAxisRectPrivate
  16655. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16656. /*! \class QCPColorScaleAxisRectPrivate
  16657. \internal
  16658. \brief An axis rect subclass for use in a QCPColorScale
  16659. This is a private class and not part of the public QCustomPlot interface.
  16660. It provides the axis rect functionality for the QCPColorScale class.
  16661. */
  16662. /*!
  16663. Creates a new instance, as a child of \a parentColorScale.
  16664. */
  16665. QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) :
  16666. QCPAxisRect(parentColorScale->parentPlot(), true),
  16667. mParentColorScale(parentColorScale),
  16668. mGradientImageInvalidated(true)
  16669. {
  16670. setParentLayerable(parentColorScale);
  16671. setMinimumMargins(QMargins(0, 0, 0, 0));
  16672. QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
  16673. foreach (QCPAxis::AxisType type, allAxisTypes)
  16674. {
  16675. axis(type)->setVisible(true);
  16676. axis(type)->grid()->setVisible(false);
  16677. axis(type)->setPadding(0);
  16678. connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts)));
  16679. connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts)));
  16680. }
  16681. connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange)));
  16682. connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange)));
  16683. connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange)));
  16684. connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange)));
  16685. connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType)));
  16686. connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType)));
  16687. connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType)));
  16688. connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType)));
  16689. // make layer transfers of color scale transfer to axis rect and axes
  16690. // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect:
  16691. connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*)));
  16692. foreach (QCPAxis::AxisType type, allAxisTypes)
  16693. connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*)));
  16694. }
  16695. /*! \internal
  16696. Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws
  16697. it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation.
  16698. \seebaseclassmethod
  16699. */
  16700. void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter)
  16701. {
  16702. if (mGradientImageInvalidated)
  16703. updateGradientImage();
  16704. bool mirrorHorz = false;
  16705. bool mirrorVert = false;
  16706. if (mParentColorScale->mColorAxis)
  16707. {
  16708. mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop);
  16709. mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight);
  16710. }
  16711. painter->drawImage(rect().adjusted(0, -1, 0, -1), mGradientImage.mirrored(mirrorHorz, mirrorVert));
  16712. QCPAxisRect::draw(painter);
  16713. }
  16714. /*! \internal
  16715. Uses the current gradient of the parent \ref QCPColorScale (specified in the constructor) to
  16716. generate a gradient image. This gradient image will be used in the \ref draw method.
  16717. */
  16718. void QCPColorScaleAxisRectPrivate::updateGradientImage()
  16719. {
  16720. if (rect().isEmpty())
  16721. return;
  16722. const QImage::Format format = QImage::Format_ARGB32_Premultiplied;
  16723. int n = mParentColorScale->mGradient.levelCount();
  16724. int w, h;
  16725. QVector<double> data(n);
  16726. for (int i=0; i<n; ++i)
  16727. data[i] = i;
  16728. if (mParentColorScale->mType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop)
  16729. {
  16730. w = n;
  16731. h = rect().height();
  16732. mGradientImage = QImage(w, h, format);
  16733. QVector<QRgb*> pixels;
  16734. for (int y=0; y<h; ++y)
  16735. pixels.append(reinterpret_cast<QRgb*>(mGradientImage.scanLine(y)));
  16736. mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n);
  16737. for (int y=1; y<h; ++y)
  16738. memcpy(pixels.at(y), pixels.first(), n*sizeof(QRgb));
  16739. } else
  16740. {
  16741. w = rect().width();
  16742. h = n;
  16743. mGradientImage = QImage(w, h, format);
  16744. for (int y=0; y<h; ++y)
  16745. {
  16746. QRgb *pixels = reinterpret_cast<QRgb*>(mGradientImage.scanLine(y));
  16747. const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1));
  16748. for (int x=0; x<w; ++x)
  16749. pixels[x] = lineColor;
  16750. }
  16751. }
  16752. mGradientImageInvalidated = false;
  16753. }
  16754. /*! \internal
  16755. This slot is connected to the selectionChanged signals of the four axes in the constructor. It
  16756. synchronizes the selection state of the axes.
  16757. */
  16758. void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts selectedParts)
  16759. {
  16760. // axis bases of four axes shall always (de-)selected synchronously:
  16761. QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
  16762. foreach (QCPAxis::AxisType type, allAxisTypes)
  16763. {
  16764. if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
  16765. if (senderAxis->axisType() == type)
  16766. continue;
  16767. if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
  16768. {
  16769. if (selectedParts.testFlag(QCPAxis::spAxis))
  16770. axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis);
  16771. else
  16772. axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis);
  16773. }
  16774. }
  16775. }
  16776. /*! \internal
  16777. This slot is connected to the selectableChanged signals of the four axes in the constructor. It
  16778. synchronizes the selectability of the axes.
  16779. */
  16780. void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts)
  16781. {
  16782. // synchronize axis base selectability:
  16783. QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
  16784. foreach (QCPAxis::AxisType type, allAxisTypes)
  16785. {
  16786. if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
  16787. if (senderAxis->axisType() == type)
  16788. continue;
  16789. if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
  16790. {
  16791. if (selectableParts.testFlag(QCPAxis::spAxis))
  16792. axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis);
  16793. else
  16794. axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis);
  16795. }
  16796. }
  16797. }
  16798. /* end of 'src/layoutelements/layoutelement-colorscale.cpp' */
  16799. /* including file 'src/plottables/plottable-graph.cpp', size 73960 */
  16800. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  16801. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16802. //////////////////// QCPGraphData
  16803. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16804. /*! \class QCPGraphData
  16805. \brief Holds the data of one single data point for QCPGraph.
  16806. The stored data is:
  16807. \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
  16808. \li \a value: coordinate on the value axis of this data point (this is the \a mainValue)
  16809. The container for storing multiple data points is \ref QCPGraphDataContainer. It is a typedef for
  16810. \ref QCPDataContainer with \ref QCPGraphData as the DataType template parameter. See the
  16811. documentation there for an explanation regarding the data type's generic methods.
  16812. \see QCPGraphDataContainer
  16813. */
  16814. /* start documentation of inline functions */
  16815. /*! \fn double QCPGraphData::sortKey() const
  16816. Returns the \a key member of this data point.
  16817. For a general explanation of what this method is good for in the context of the data container,
  16818. see the documentation of \ref QCPDataContainer.
  16819. */
  16820. /*! \fn static QCPGraphData QCPGraphData::fromSortKey(double sortKey)
  16821. Returns a data point with the specified \a sortKey. All other members are set to zero.
  16822. For a general explanation of what this method is good for in the context of the data container,
  16823. see the documentation of \ref QCPDataContainer.
  16824. */
  16825. /*! \fn static static bool QCPGraphData::sortKeyIsMainKey()
  16826. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  16827. this method returns true.
  16828. For a general explanation of what this method is good for in the context of the data container,
  16829. see the documentation of \ref QCPDataContainer.
  16830. */
  16831. /*! \fn double QCPGraphData::mainKey() const
  16832. Returns the \a key member of this data point.
  16833. For a general explanation of what this method is good for in the context of the data container,
  16834. see the documentation of \ref QCPDataContainer.
  16835. */
  16836. /*! \fn double QCPGraphData::mainValue() const
  16837. Returns the \a value member of this data point.
  16838. For a general explanation of what this method is good for in the context of the data container,
  16839. see the documentation of \ref QCPDataContainer.
  16840. */
  16841. /*! \fn QCPRange QCPGraphData::valueRange() const
  16842. Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
  16843. For a general explanation of what this method is good for in the context of the data container,
  16844. see the documentation of \ref QCPDataContainer.
  16845. */
  16846. /* end documentation of inline functions */
  16847. /*!
  16848. Constructs a data point with key and value set to zero.
  16849. */
  16850. QCPGraphData::QCPGraphData() :
  16851. key(0),
  16852. value(0)
  16853. {
  16854. }
  16855. /*!
  16856. Constructs a data point with the specified \a key and \a value.
  16857. */
  16858. QCPGraphData::QCPGraphData(double key, double value) :
  16859. key(key),
  16860. value(value)
  16861. {
  16862. }
  16863. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16864. //////////////////// QCPGraph
  16865. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16866. /*! \class QCPGraph
  16867. \brief A plottable representing a graph in a plot.
  16868. \image html QCPGraph.png
  16869. Usually you create new graphs by calling QCustomPlot::addGraph. The resulting instance can be
  16870. accessed via QCustomPlot::graph.
  16871. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
  16872. also access and modify the data via the \ref data method, which returns a pointer to the internal
  16873. \ref QCPGraphDataContainer.
  16874. Graphs are used to display single-valued data. Single-valued means that there should only be one
  16875. data point per unique key coordinate. In other words, the graph can't have \a loops. If you do
  16876. want to plot non-single-valued curves, rather use the QCPCurve plottable.
  16877. Gaps in the graph line can be created by adding data points with NaN as value
  16878. (<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
  16879. separated.
  16880. \section qcpgraph-appearance Changing the appearance
  16881. The appearance of the graph is mainly determined by the line style, scatter style, brush and pen
  16882. of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen).
  16883. \subsection filling Filling under or between graphs
  16884. QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to
  16885. the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill,
  16886. just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent.
  16887. By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill
  16888. between this graph and another one, call \ref setChannelFillGraph with the other graph as
  16889. parameter.
  16890. \see QCustomPlot::addGraph, QCustomPlot::graph
  16891. */
  16892. /* start of documentation of inline functions */
  16893. /*! \fn QSharedPointer<QCPGraphDataContainer> QCPGraph::data() const
  16894. Returns a shared pointer to the internal data storage of type \ref QCPGraphDataContainer. You may
  16895. use it to directly manipulate the data, which may be more convenient and faster than using the
  16896. regular \ref setData or \ref addData methods.
  16897. */
  16898. /* end of documentation of inline functions */
  16899. /*!
  16900. Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  16901. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  16902. the same orientation. If either of these restrictions is violated, a corresponding message is
  16903. printed to the debug output (qDebug), the construction is not aborted, though.
  16904. The created QCPGraph is automatically registered with the QCustomPlot instance inferred from \a
  16905. keyAxis. This QCustomPlot instance takes ownership of the QCPGraph, so do not delete it manually
  16906. but use QCustomPlot::removePlottable() instead.
  16907. To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function.
  16908. */
  16909. QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  16910. QCPAbstractPlottable1D<QCPGraphData>(keyAxis, valueAxis)
  16911. {
  16912. // special handling for QCPGraphs to maintain the simple graph interface:
  16913. mParentPlot->registerGraph(this);
  16914. setPen(QPen(Qt::blue, 0));
  16915. setBrush(Qt::NoBrush);
  16916. setLineStyle(lsLine);
  16917. setScatterSkip(0);
  16918. setChannelFillGraph(0);
  16919. setAdaptiveSampling(true);
  16920. }
  16921. QCPGraph::~QCPGraph()
  16922. {
  16923. }
  16924. /*! \overload
  16925. Replaces the current data container with the provided \a data container.
  16926. Since a QSharedPointer is used, multiple QCPGraphs may share the same data container safely.
  16927. Modifying the data in the container will then affect all graphs that share the container. Sharing
  16928. can be achieved by simply exchanging the data containers wrapped in shared pointers:
  16929. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-1
  16930. If you do not wish to share containers, but create a copy from an existing container, rather use
  16931. the \ref QCPDataContainer<DataType>::set method on the graph's data container directly:
  16932. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-2
  16933. \see addData
  16934. */
  16935. void QCPGraph::setData(QSharedPointer<QCPGraphDataContainer> data)
  16936. {
  16937. mDataContainer = data;
  16938. }
  16939. /*! \overload
  16940. Replaces the current data with the provided points in \a keys and \a values. The provided
  16941. vectors should have equal length. Else, the number of added points will be the size of the
  16942. smallest vector.
  16943. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  16944. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  16945. \see addData
  16946. */
  16947. void QCPGraph::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  16948. {
  16949. mDataContainer->clear();
  16950. addData(keys, values, alreadySorted);
  16951. }
  16952. /*!
  16953. Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
  16954. \ref lsNone and \ref setScatterStyle to the desired scatter style.
  16955. \see setScatterStyle
  16956. */
  16957. void QCPGraph::setLineStyle(LineStyle ls)
  16958. {
  16959. mLineStyle = ls;
  16960. }
  16961. /*!
  16962. Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points
  16963. are drawn (e.g. for line-only-plots with appropriate line style).
  16964. \see QCPScatterStyle, setLineStyle
  16965. */
  16966. void QCPGraph::setScatterStyle(const QCPScatterStyle &style)
  16967. {
  16968. mScatterStyle = style;
  16969. }
  16970. /*!
  16971. If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of
  16972. scatter points are skipped/not drawn after every drawn scatter point.
  16973. This can be used to make the data appear sparser while for example still having a smooth line,
  16974. and to improve performance for very high density plots.
  16975. If \a skip is set to 0 (default), all scatter points are drawn.
  16976. \see setScatterStyle
  16977. */
  16978. void QCPGraph::setScatterSkip(int skip)
  16979. {
  16980. mScatterSkip = qMax(0, skip);
  16981. }
  16982. /*!
  16983. Sets the target graph for filling the area between this graph and \a targetGraph with the current
  16984. brush (\ref setBrush).
  16985. When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To
  16986. disable any filling, set the brush to Qt::NoBrush.
  16987. \see setBrush
  16988. */
  16989. void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph)
  16990. {
  16991. // prevent setting channel target to this graph itself:
  16992. if (targetGraph == this)
  16993. {
  16994. qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself";
  16995. mChannelFillGraph = 0;
  16996. return;
  16997. }
  16998. // prevent setting channel target to a graph not in the plot:
  16999. if (targetGraph && targetGraph->mParentPlot != mParentPlot)
  17000. {
  17001. qDebug() << Q_FUNC_INFO << "targetGraph not in same plot";
  17002. mChannelFillGraph = 0;
  17003. return;
  17004. }
  17005. mChannelFillGraph = targetGraph;
  17006. }
  17007. /*!
  17008. Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive
  17009. sampling technique can drastically improve the replot performance for graphs with a larger number
  17010. of points (e.g. above 10,000), without notably changing the appearance of the graph.
  17011. By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive
  17012. sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no
  17013. disadvantage in almost all cases.
  17014. \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling"
  17015. As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are
  17016. reproduced reliably, as well as the overall shape of the data set. The replot time reduces
  17017. dramatically though. This allows QCustomPlot to display large amounts of data in realtime.
  17018. \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling"
  17019. Care must be taken when using high-density scatter plots in combination with adaptive sampling.
  17020. The adaptive sampling algorithm treats scatter plots more carefully than line plots which still
  17021. gives a significant reduction of replot times, but not quite as much as for line plots. This is
  17022. because scatter plots inherently need more data points to be preserved in order to still resemble
  17023. the original, non-adaptive-sampling plot. As shown above, the results still aren't quite
  17024. identical, as banding occurs for the outer data points. This is in fact intentional, such that
  17025. the boundaries of the data cloud stay visible to the viewer. How strong the banding appears,
  17026. depends on the point density, i.e. the number of points in the plot.
  17027. For some situations with scatter plots it might thus be desirable to manually turn adaptive
  17028. sampling off. For example, when saving the plot to disk. This can be achieved by setting \a
  17029. enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled
  17030. back to true afterwards.
  17031. */
  17032. void QCPGraph::setAdaptiveSampling(bool enabled)
  17033. {
  17034. mAdaptiveSampling = enabled;
  17035. }
  17036. /*! \overload
  17037. Adds the provided points in \a keys and \a values to the current data. The provided vectors
  17038. should have equal length. Else, the number of added points will be the size of the smallest
  17039. vector.
  17040. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  17041. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  17042. Alternatively, you can also access and modify the data directly via the \ref data method, which
  17043. returns a pointer to the internal data container.
  17044. */
  17045. void QCPGraph::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  17046. {
  17047. if (keys.size() != values.size())
  17048. qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
  17049. const int n = qMin(keys.size(), values.size());
  17050. QVector<QCPGraphData> tempData(n);
  17051. QVector<QCPGraphData>::iterator it = tempData.begin();
  17052. const QVector<QCPGraphData>::iterator itEnd = tempData.end();
  17053. int i = 0;
  17054. while (it != itEnd)
  17055. {
  17056. it->key = keys[i];
  17057. it->value = values[i];
  17058. ++it;
  17059. ++i;
  17060. }
  17061. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  17062. }
  17063. /*! \overload
  17064. Adds the provided data point as \a key and \a value to the current data.
  17065. Alternatively, you can also access and modify the data directly via the \ref data method, which
  17066. returns a pointer to the internal data container.
  17067. */
  17068. void QCPGraph::addData(double key, double value)
  17069. {
  17070. mDataContainer->add(QCPGraphData(key, value));
  17071. }
  17072. /* inherits documentation from base class */
  17073. double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  17074. {
  17075. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  17076. return -1;
  17077. if (!mKeyAxis || !mValueAxis)
  17078. return -1;
  17079. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
  17080. {
  17081. QCPGraphDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  17082. double result = pointDistance(pos, closestDataPoint);
  17083. if (details)
  17084. {
  17085. int pointIndex = closestDataPoint-mDataContainer->constBegin();
  17086. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  17087. }
  17088. return result;
  17089. } else
  17090. return -1;
  17091. }
  17092. /* inherits documentation from base class */
  17093. QCPRange QCPGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  17094. {
  17095. return mDataContainer->keyRange(foundRange, inSignDomain);
  17096. }
  17097. /* inherits documentation from base class */
  17098. QCPRange QCPGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  17099. {
  17100. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  17101. }
  17102. /* inherits documentation from base class */
  17103. void QCPGraph::draw(QCPPainter *painter)
  17104. {
  17105. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  17106. if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
  17107. if (mLineStyle == lsNone && mScatterStyle.isNone()) return;
  17108. QVector<QPointF> lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments
  17109. // loop over and draw segments of unselected/selected data:
  17110. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  17111. getDataSegments(selectedSegments, unselectedSegments);
  17112. allSegments << unselectedSegments << selectedSegments;
  17113. for (int i=0; i<allSegments.size(); ++i)
  17114. {
  17115. bool isSelectedSegment = i >= unselectedSegments.size();
  17116. // get line pixel points appropriate to line style:
  17117. 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)
  17118. getLines(&lines, lineDataRange);
  17119. // check data validity if flag set:
  17120. #ifdef QCUSTOMPLOT_CHECK_DATA
  17121. QCPGraphDataContainer::const_iterator it;
  17122. for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  17123. {
  17124. if (QCP::isInvalidData(it->key, it->value))
  17125. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
  17126. }
  17127. #endif
  17128. // draw fill of graph:
  17129. if (isSelectedSegment && mSelectionDecorator)
  17130. mSelectionDecorator->applyBrush(painter);
  17131. else
  17132. painter->setBrush(mBrush);
  17133. painter->setPen(Qt::NoPen);
  17134. drawFill(painter, &lines);
  17135. // draw line:
  17136. if (mLineStyle != lsNone)
  17137. {
  17138. if (isSelectedSegment && mSelectionDecorator)
  17139. mSelectionDecorator->applyPen(painter);
  17140. else
  17141. painter->setPen(mPen);
  17142. painter->setBrush(Qt::NoBrush);
  17143. if (mLineStyle == lsImpulse)
  17144. drawImpulsePlot(painter, lines);
  17145. else
  17146. drawLinePlot(painter, lines); // also step plots can be drawn as a line plot
  17147. }
  17148. // draw scatters:
  17149. QCPScatterStyle finalScatterStyle = mScatterStyle;
  17150. if (isSelectedSegment && mSelectionDecorator)
  17151. finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
  17152. if (!finalScatterStyle.isNone())
  17153. {
  17154. getScatters(&scatters, allSegments.at(i));
  17155. drawScatterPlot(painter, scatters, finalScatterStyle);
  17156. }
  17157. }
  17158. // draw other selection decoration that isn't just line/scatter pens and brushes:
  17159. if (mSelectionDecorator)
  17160. mSelectionDecorator->drawDecoration(painter, selection());
  17161. }
  17162. /* inherits documentation from base class */
  17163. void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  17164. {
  17165. // draw fill:
  17166. if (mBrush.style() != Qt::NoBrush)
  17167. {
  17168. applyFillAntialiasingHint(painter);
  17169. painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
  17170. }
  17171. // draw line vertically centered:
  17172. if (mLineStyle != lsNone)
  17173. {
  17174. applyDefaultAntialiasingHint(painter);
  17175. painter->setPen(mPen);
  17176. 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
  17177. }
  17178. // draw scatter symbol:
  17179. if (!mScatterStyle.isNone())
  17180. {
  17181. applyScattersAntialiasingHint(painter);
  17182. // scale scatter pixmap if it's too large to fit in legend icon rect:
  17183. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
  17184. {
  17185. QCPScatterStyle scaledStyle(mScatterStyle);
  17186. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  17187. scaledStyle.applyTo(painter, mPen);
  17188. scaledStyle.drawShape(painter, QRectF(rect).center());
  17189. } else
  17190. {
  17191. mScatterStyle.applyTo(painter, mPen);
  17192. mScatterStyle.drawShape(painter, QRectF(rect).center());
  17193. }
  17194. }
  17195. }
  17196. /*! \internal
  17197. This method retrieves an optimized set of data points via \ref getOptimizedLineData, an branches
  17198. out to the line style specific functions such as \ref dataToLines, \ref dataToStepLeftLines, etc.
  17199. according to the line style of the graph.
  17200. \a lines will be filled with points in pixel coordinates, that can be drawn with the according
  17201. draw functions like \ref drawLinePlot and \ref drawImpulsePlot. The points returned in \a lines
  17202. aren't necessarily the original data points. For example, step line styles require additional
  17203. points to form the steps when drawn. If the line style of the graph is \ref lsNone, the \a
  17204. lines vector will be empty.
  17205. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  17206. conversion. In this function, the specified range may exceed the total data bounds without harm:
  17207. a correspondingly trimmed data range will be used. This takes the burden off the user of this
  17208. function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
  17209. getDataSegments.
  17210. \see getScatters
  17211. */
  17212. void QCPGraph::getLines(QVector<QPointF> *lines, const QCPDataRange &dataRange) const
  17213. {
  17214. if (!lines) return;
  17215. QCPGraphDataContainer::const_iterator begin, end;
  17216. getVisibleDataBounds(begin, end, dataRange);
  17217. if (begin == end)
  17218. {
  17219. lines->clear();
  17220. return;
  17221. }
  17222. QVector<QCPGraphData> lineData;
  17223. if (mLineStyle != lsNone)
  17224. getOptimizedLineData(&lineData, begin, end);
  17225. if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in lineData (significantly simplifies following processing)
  17226. std::reverse(lineData.begin(), lineData.end());
  17227. switch (mLineStyle)
  17228. {
  17229. case lsNone: lines->clear(); break;
  17230. case lsLine: *lines = dataToLines(lineData); break;
  17231. case lsStepLeft: *lines = dataToStepLeftLines(lineData); break;
  17232. case lsStepRight: *lines = dataToStepRightLines(lineData); break;
  17233. case lsStepCenter: *lines = dataToStepCenterLines(lineData); break;
  17234. case lsImpulse: *lines = dataToImpulseLines(lineData); break;
  17235. }
  17236. }
  17237. /*! \internal
  17238. This method retrieves an optimized set of data points via \ref getOptimizedScatterData and then
  17239. converts them to pixel coordinates. The resulting points are returned in \a scatters, and can be
  17240. passed to \ref drawScatterPlot.
  17241. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  17242. conversion. In this function, the specified range may exceed the total data bounds without harm:
  17243. a correspondingly trimmed data range will be used. This takes the burden off the user of this
  17244. function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
  17245. getDataSegments.
  17246. */
  17247. void QCPGraph::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange) const
  17248. {
  17249. if (!scatters) return;
  17250. QCPAxis *keyAxis = mKeyAxis.data();
  17251. QCPAxis *valueAxis = mValueAxis.data();
  17252. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; scatters->clear(); return; }
  17253. QCPGraphDataContainer::const_iterator begin, end;
  17254. getVisibleDataBounds(begin, end, dataRange);
  17255. if (begin == end)
  17256. {
  17257. scatters->clear();
  17258. return;
  17259. }
  17260. QVector<QCPGraphData> data;
  17261. getOptimizedScatterData(&data, begin, end);
  17262. if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in data (significantly simplifies following processing)
  17263. std::reverse(data.begin(), data.end());
  17264. scatters->resize(data.size());
  17265. if (keyAxis->orientation() == Qt::Vertical)
  17266. {
  17267. for (int i=0; i<data.size(); ++i)
  17268. {
  17269. if (!qIsNaN(data.at(i).value))
  17270. {
  17271. (*scatters)[i].setX(valueAxis->coordToPixel(data.at(i).value));
  17272. (*scatters)[i].setY(keyAxis->coordToPixel(data.at(i).key));
  17273. }
  17274. }
  17275. } else
  17276. {
  17277. for (int i=0; i<data.size(); ++i)
  17278. {
  17279. if (!qIsNaN(data.at(i).value))
  17280. {
  17281. (*scatters)[i].setX(keyAxis->coordToPixel(data.at(i).key));
  17282. (*scatters)[i].setY(valueAxis->coordToPixel(data.at(i).value));
  17283. }
  17284. }
  17285. }
  17286. }
  17287. /*! \internal
  17288. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  17289. coordinate points which are suitable for drawing the line style \ref lsLine.
  17290. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  17291. getLines if the line style is set accordingly.
  17292. \see dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
  17293. */
  17294. QVector<QPointF> QCPGraph::dataToLines(const QVector<QCPGraphData> &data) const
  17295. {
  17296. QVector<QPointF> result;
  17297. QCPAxis *keyAxis = mKeyAxis.data();
  17298. QCPAxis *valueAxis = mValueAxis.data();
  17299. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  17300. result.resize(data.size());
  17301. // transform data points to pixels:
  17302. if (keyAxis->orientation() == Qt::Vertical)
  17303. {
  17304. for (int i=0; i<data.size(); ++i)
  17305. {
  17306. result[i].setX(valueAxis->coordToPixel(data.at(i).value));
  17307. result[i].setY(keyAxis->coordToPixel(data.at(i).key));
  17308. }
  17309. } else // key axis is horizontal
  17310. {
  17311. for (int i=0; i<data.size(); ++i)
  17312. {
  17313. result[i].setX(keyAxis->coordToPixel(data.at(i).key));
  17314. result[i].setY(valueAxis->coordToPixel(data.at(i).value));
  17315. }
  17316. }
  17317. return result;
  17318. }
  17319. /*! \internal
  17320. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  17321. coordinate points which are suitable for drawing the line style \ref lsStepLeft.
  17322. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  17323. getLines if the line style is set accordingly.
  17324. \see dataToLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
  17325. */
  17326. QVector<QPointF> QCPGraph::dataToStepLeftLines(const QVector<QCPGraphData> &data) const
  17327. {
  17328. QVector<QPointF> result;
  17329. QCPAxis *keyAxis = mKeyAxis.data();
  17330. QCPAxis *valueAxis = mValueAxis.data();
  17331. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  17332. result.resize(data.size()*2);
  17333. // calculate steps from data and transform to pixel coordinates:
  17334. if (keyAxis->orientation() == Qt::Vertical)
  17335. {
  17336. double lastValue = valueAxis->coordToPixel(data.first().value);
  17337. for (int i=0; i<data.size(); ++i)
  17338. {
  17339. const double key = keyAxis->coordToPixel(data.at(i).key);
  17340. result[i*2+0].setX(lastValue);
  17341. result[i*2+0].setY(key);
  17342. lastValue = valueAxis->coordToPixel(data.at(i).value);
  17343. result[i*2+1].setX(lastValue);
  17344. result[i*2+1].setY(key);
  17345. }
  17346. } else // key axis is horizontal
  17347. {
  17348. double lastValue = valueAxis->coordToPixel(data.first().value);
  17349. for (int i=0; i<data.size(); ++i)
  17350. {
  17351. const double key = keyAxis->coordToPixel(data.at(i).key);
  17352. result[i*2+0].setX(key);
  17353. result[i*2+0].setY(lastValue);
  17354. lastValue = valueAxis->coordToPixel(data.at(i).value);
  17355. result[i*2+1].setX(key);
  17356. result[i*2+1].setY(lastValue);
  17357. }
  17358. }
  17359. return result;
  17360. }
  17361. /*! \internal
  17362. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  17363. coordinate points which are suitable for drawing the line style \ref lsStepRight.
  17364. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  17365. getLines if the line style is set accordingly.
  17366. \see dataToLines, dataToStepLeftLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
  17367. */
  17368. QVector<QPointF> QCPGraph::dataToStepRightLines(const QVector<QCPGraphData> &data) const
  17369. {
  17370. QVector<QPointF> result;
  17371. QCPAxis *keyAxis = mKeyAxis.data();
  17372. QCPAxis *valueAxis = mValueAxis.data();
  17373. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  17374. result.resize(data.size()*2);
  17375. // calculate steps from data and transform to pixel coordinates:
  17376. if (keyAxis->orientation() == Qt::Vertical)
  17377. {
  17378. double lastKey = keyAxis->coordToPixel(data.first().key);
  17379. for (int i=0; i<data.size(); ++i)
  17380. {
  17381. const double value = valueAxis->coordToPixel(data.at(i).value);
  17382. result[i*2+0].setX(value);
  17383. result[i*2+0].setY(lastKey);
  17384. lastKey = keyAxis->coordToPixel(data.at(i).key);
  17385. result[i*2+1].setX(value);
  17386. result[i*2+1].setY(lastKey);
  17387. }
  17388. } else // key axis is horizontal
  17389. {
  17390. double lastKey = keyAxis->coordToPixel(data.first().key);
  17391. for (int i=0; i<data.size(); ++i)
  17392. {
  17393. const double value = valueAxis->coordToPixel(data.at(i).value);
  17394. result[i*2+0].setX(lastKey);
  17395. result[i*2+0].setY(value);
  17396. lastKey = keyAxis->coordToPixel(data.at(i).key);
  17397. result[i*2+1].setX(lastKey);
  17398. result[i*2+1].setY(value);
  17399. }
  17400. }
  17401. return result;
  17402. }
  17403. /*! \internal
  17404. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  17405. coordinate points which are suitable for drawing the line style \ref lsStepCenter.
  17406. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  17407. getLines if the line style is set accordingly.
  17408. \see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToImpulseLines, getLines, drawLinePlot
  17409. */
  17410. QVector<QPointF> QCPGraph::dataToStepCenterLines(const QVector<QCPGraphData> &data) const
  17411. {
  17412. QVector<QPointF> result;
  17413. QCPAxis *keyAxis = mKeyAxis.data();
  17414. QCPAxis *valueAxis = mValueAxis.data();
  17415. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  17416. result.resize(data.size()*2);
  17417. // calculate steps from data and transform to pixel coordinates:
  17418. if (keyAxis->orientation() == Qt::Vertical)
  17419. {
  17420. double lastKey = keyAxis->coordToPixel(data.first().key);
  17421. double lastValue = valueAxis->coordToPixel(data.first().value);
  17422. result[0].setX(lastValue);
  17423. result[0].setY(lastKey);
  17424. for (int i=1; i<data.size(); ++i)
  17425. {
  17426. const double key = (keyAxis->coordToPixel(data.at(i).key)+lastKey)*0.5;
  17427. result[i*2-1].setX(lastValue);
  17428. result[i*2-1].setY(key);
  17429. lastValue = valueAxis->coordToPixel(data.at(i).value);
  17430. lastKey = keyAxis->coordToPixel(data.at(i).key);
  17431. result[i*2+0].setX(lastValue);
  17432. result[i*2+0].setY(key);
  17433. }
  17434. result[data.size()*2-1].setX(lastValue);
  17435. result[data.size()*2-1].setY(lastKey);
  17436. } else // key axis is horizontal
  17437. {
  17438. double lastKey = keyAxis->coordToPixel(data.first().key);
  17439. double lastValue = valueAxis->coordToPixel(data.first().value);
  17440. result[0].setX(lastKey);
  17441. result[0].setY(lastValue);
  17442. for (int i=1; i<data.size(); ++i)
  17443. {
  17444. const double key = (keyAxis->coordToPixel(data.at(i).key)+lastKey)*0.5;
  17445. result[i*2-1].setX(key);
  17446. result[i*2-1].setY(lastValue);
  17447. lastValue = valueAxis->coordToPixel(data.at(i).value);
  17448. lastKey = keyAxis->coordToPixel(data.at(i).key);
  17449. result[i*2+0].setX(key);
  17450. result[i*2+0].setY(lastValue);
  17451. }
  17452. result[data.size()*2-1].setX(lastKey);
  17453. result[data.size()*2-1].setY(lastValue);
  17454. }
  17455. return result;
  17456. }
  17457. /*! \internal
  17458. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  17459. coordinate points which are suitable for drawing the line style \ref lsImpulse.
  17460. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  17461. getLines if the line style is set accordingly.
  17462. \see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, getLines, drawImpulsePlot
  17463. */
  17464. QVector<QPointF> QCPGraph::dataToImpulseLines(const QVector<QCPGraphData> &data) const
  17465. {
  17466. QVector<QPointF> result;
  17467. QCPAxis *keyAxis = mKeyAxis.data();
  17468. QCPAxis *valueAxis = mValueAxis.data();
  17469. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  17470. result.resize(data.size()*2);
  17471. // transform data points to pixels:
  17472. if (keyAxis->orientation() == Qt::Vertical)
  17473. {
  17474. for (int i=0; i<data.size(); ++i)
  17475. {
  17476. const double key = keyAxis->coordToPixel(data.at(i).key);
  17477. result[i*2+0].setX(valueAxis->coordToPixel(0));
  17478. result[i*2+0].setY(key);
  17479. result[i*2+1].setX(valueAxis->coordToPixel(data.at(i).value));
  17480. result[i*2+1].setY(key);
  17481. }
  17482. } else // key axis is horizontal
  17483. {
  17484. for (int i=0; i<data.size(); ++i)
  17485. {
  17486. const double key = keyAxis->coordToPixel(data.at(i).key);
  17487. result[i*2+0].setX(key);
  17488. result[i*2+0].setY(valueAxis->coordToPixel(0));
  17489. result[i*2+1].setX(key);
  17490. result[i*2+1].setY(valueAxis->coordToPixel(data.at(i).value));
  17491. }
  17492. }
  17493. return result;
  17494. }
  17495. /*! \internal
  17496. Draws the fill of the graph using the specified \a painter, with the currently set brush.
  17497. Depending on whether a normal fill or a channel fill (\ref setChannelFillGraph) is needed, \ref
  17498. getFillPolygon or \ref getChannelFillPolygon are used to find the according fill polygons.
  17499. In order to handle NaN Data points correctly (the fill needs to be split into disjoint areas),
  17500. this method first determines a list of non-NaN segments with \ref getNonNanSegments, on which to
  17501. operate. In the channel fill case, \ref getOverlappingSegments is used to consolidate the non-NaN
  17502. segments of the two involved graphs, before passing the overlapping pairs to \ref
  17503. getChannelFillPolygon.
  17504. Pass the points of this graph's line as \a lines, in pixel coordinates.
  17505. \see drawLinePlot, drawImpulsePlot, drawScatterPlot
  17506. */
  17507. void QCPGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lines) const
  17508. {
  17509. if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot
  17510. if (painter->brush().style() == Qt::NoBrush || painter->brush().color().alpha() == 0) return;
  17511. applyFillAntialiasingHint(painter);
  17512. QVector<QCPDataRange> segments = getNonNanSegments(lines, keyAxis()->orientation());
  17513. if (!mChannelFillGraph)
  17514. {
  17515. // draw base fill under graph, fill goes all the way to the zero-value-line:
  17516. for (int i=0; i<segments.size(); ++i)
  17517. painter->drawPolygon(getFillPolygon(lines, segments.at(i)));
  17518. } else
  17519. {
  17520. // draw fill between this graph and mChannelFillGraph:
  17521. QVector<QPointF> otherLines;
  17522. mChannelFillGraph->getLines(&otherLines, QCPDataRange(0, mChannelFillGraph->dataCount()));
  17523. if (!otherLines.isEmpty())
  17524. {
  17525. QVector<QCPDataRange> otherSegments = getNonNanSegments(&otherLines, mChannelFillGraph->keyAxis()->orientation());
  17526. QVector<QPair<QCPDataRange, QCPDataRange> > segmentPairs = getOverlappingSegments(segments, lines, otherSegments, &otherLines);
  17527. for (int i=0; i<segmentPairs.size(); ++i)
  17528. painter->drawPolygon(getChannelFillPolygon(lines, segmentPairs.at(i).first, &otherLines, segmentPairs.at(i).second));
  17529. }
  17530. }
  17531. }
  17532. /*! \internal
  17533. Draws scatter symbols at every point passed in \a scatters, given in pixel coordinates. The
  17534. scatters will be drawn with \a painter and have the appearance as specified in \a style.
  17535. \see drawLinePlot, drawImpulsePlot
  17536. */
  17537. void QCPGraph::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &scatters, const QCPScatterStyle &style) const
  17538. {
  17539. applyScattersAntialiasingHint(painter);
  17540. style.applyTo(painter, mPen);
  17541. for (int i=0; i<scatters.size(); ++i)
  17542. style.drawShape(painter, scatters.at(i).x(), scatters.at(i).y());
  17543. }
  17544. /*! \internal
  17545. Draws lines between the points in \a lines, given in pixel coordinates.
  17546. \see drawScatterPlot, drawImpulsePlot, QCPAbstractPlottable1D::drawPolyline
  17547. */
  17548. void QCPGraph::drawLinePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
  17549. {
  17550. if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
  17551. {
  17552. applyDefaultAntialiasingHint(painter);
  17553. drawPolyline(painter, lines);
  17554. }
  17555. }
  17556. /*! \internal
  17557. Draws impulses from the provided data, i.e. it connects all line pairs in \a lines, given in
  17558. pixel coordinates. The \a lines necessary for impulses are generated by \ref dataToImpulseLines
  17559. from the regular graph data points.
  17560. \see drawLinePlot, drawScatterPlot
  17561. */
  17562. void QCPGraph::drawImpulsePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
  17563. {
  17564. if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
  17565. {
  17566. applyDefaultAntialiasingHint(painter);
  17567. QPen oldPen = painter->pen();
  17568. QPen newPen = painter->pen();
  17569. newPen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line
  17570. painter->setPen(newPen);
  17571. painter->drawLines(lines);
  17572. painter->setPen(oldPen);
  17573. }
  17574. }
  17575. /*! \internal
  17576. Returns via \a lineData the data points that need to be visualized for this graph when plotting
  17577. graph lines, taking into consideration the currently visible axis ranges and, if \ref
  17578. setAdaptiveSampling is enabled, local point densities. The considered data can be restricted
  17579. further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref
  17580. getDataSegments).
  17581. This method is used by \ref getLines to retrieve the basic working set of data.
  17582. \see getOptimizedScatterData
  17583. */
  17584. void QCPGraph::getOptimizedLineData(QVector<QCPGraphData> *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const
  17585. {
  17586. if (!lineData) return;
  17587. QCPAxis *keyAxis = mKeyAxis.data();
  17588. QCPAxis *valueAxis = mValueAxis.data();
  17589. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  17590. if (begin == end) return;
  17591. int dataCount = end-begin;
  17592. int maxCount = std::numeric_limits<int>::max();
  17593. if (mAdaptiveSampling)
  17594. {
  17595. double keyPixelSpan = qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key));
  17596. if (2*keyPixelSpan+2 < (double)std::numeric_limits<int>::max())
  17597. maxCount = 2*keyPixelSpan+2;
  17598. }
  17599. if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
  17600. {
  17601. QCPGraphDataContainer::const_iterator it = begin;
  17602. double minValue = it->value;
  17603. double maxValue = it->value;
  17604. QCPGraphDataContainer::const_iterator currentIntervalFirstPoint = it;
  17605. int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction
  17606. int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
  17607. double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(begin->key)+reversedRound));
  17608. double lastIntervalEndKey = currentIntervalStartKey;
  17609. double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
  17610. bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
  17611. int intervalDataCount = 1;
  17612. ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect
  17613. while (it != end)
  17614. {
  17615. if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary
  17616. {
  17617. if (it->value < minValue)
  17618. minValue = it->value;
  17619. else if (it->value > maxValue)
  17620. maxValue = it->value;
  17621. ++intervalDataCount;
  17622. } else // new pixel interval started
  17623. {
  17624. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
  17625. {
  17626. if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point
  17627. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value));
  17628. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
  17629. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
  17630. 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
  17631. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.8, (it-1)->value));
  17632. } else
  17633. lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value));
  17634. lastIntervalEndKey = (it-1)->key;
  17635. minValue = it->value;
  17636. maxValue = it->value;
  17637. currentIntervalFirstPoint = it;
  17638. currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it->key)+reversedRound));
  17639. if (keyEpsilonVariable)
  17640. keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
  17641. intervalDataCount = 1;
  17642. }
  17643. ++it;
  17644. }
  17645. // handle last interval:
  17646. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
  17647. {
  17648. if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point
  17649. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value));
  17650. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
  17651. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
  17652. } else
  17653. lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value));
  17654. } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output
  17655. {
  17656. lineData->resize(dataCount);
  17657. std::copy(begin, end, lineData->begin());
  17658. }
  17659. }
  17660. /*! \internal
  17661. Returns via \a scatterData the data points that need to be visualized for this graph when
  17662. plotting scatter points, taking into consideration the currently visible axis ranges and, if \ref
  17663. setAdaptiveSampling is enabled, local point densities. The considered data can be restricted
  17664. further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref
  17665. getDataSegments).
  17666. This method is used by \ref getScatters to retrieve the basic working set of data.
  17667. \see getOptimizedLineData
  17668. */
  17669. void QCPGraph::getOptimizedScatterData(QVector<QCPGraphData> *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const
  17670. {
  17671. if (!scatterData) return;
  17672. QCPAxis *keyAxis = mKeyAxis.data();
  17673. QCPAxis *valueAxis = mValueAxis.data();
  17674. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  17675. const int scatterModulo = mScatterSkip+1;
  17676. const bool doScatterSkip = mScatterSkip > 0;
  17677. int beginIndex = begin-mDataContainer->constBegin();
  17678. int endIndex = end-mDataContainer->constBegin();
  17679. while (doScatterSkip && begin != end && beginIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter
  17680. {
  17681. ++beginIndex;
  17682. ++begin;
  17683. }
  17684. if (begin == end) return;
  17685. int dataCount = end-begin;
  17686. int maxCount = std::numeric_limits<int>::max();
  17687. if (mAdaptiveSampling)
  17688. {
  17689. int keyPixelSpan = qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key));
  17690. maxCount = 2*keyPixelSpan+2;
  17691. }
  17692. if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
  17693. {
  17694. double valueMaxRange = valueAxis->range().upper;
  17695. double valueMinRange = valueAxis->range().lower;
  17696. QCPGraphDataContainer::const_iterator it = begin;
  17697. int itIndex = beginIndex;
  17698. double minValue = it->value;
  17699. double maxValue = it->value;
  17700. QCPGraphDataContainer::const_iterator minValueIt = it;
  17701. QCPGraphDataContainer::const_iterator maxValueIt = it;
  17702. QCPGraphDataContainer::const_iterator currentIntervalStart = it;
  17703. int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction
  17704. int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
  17705. double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(begin->key)+reversedRound));
  17706. double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
  17707. bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
  17708. int intervalDataCount = 1;
  17709. // advance iterator to second (non-skipped) data point because adaptive sampling works in 1 point retrospect:
  17710. if (!doScatterSkip)
  17711. ++it;
  17712. else
  17713. {
  17714. itIndex += scatterModulo;
  17715. if (itIndex < endIndex) // make sure we didn't jump over end
  17716. it += scatterModulo;
  17717. else
  17718. {
  17719. it = end;
  17720. itIndex = endIndex;
  17721. }
  17722. }
  17723. // main loop over data points:
  17724. while (it != end)
  17725. {
  17726. if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary
  17727. {
  17728. if (it->value < minValue && it->value > valueMinRange && it->value < valueMaxRange)
  17729. {
  17730. minValue = it->value;
  17731. minValueIt = it;
  17732. } else if (it->value > maxValue && it->value > valueMinRange && it->value < valueMaxRange)
  17733. {
  17734. maxValue = it->value;
  17735. maxValueIt = it;
  17736. }
  17737. ++intervalDataCount;
  17738. } else // new pixel started
  17739. {
  17740. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
  17741. {
  17742. // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
  17743. double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
  17744. int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
  17745. QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart;
  17746. int c = 0;
  17747. while (intervalIt != it)
  17748. {
  17749. if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange)
  17750. scatterData->append(*intervalIt);
  17751. ++c;
  17752. if (!doScatterSkip)
  17753. ++intervalIt;
  17754. else
  17755. intervalIt += scatterModulo; // since we know indices of "currentIntervalStart", "intervalIt" and "it" are multiples of scatterModulo, we can't accidentally jump over "it" here
  17756. }
  17757. } else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange)
  17758. scatterData->append(*currentIntervalStart);
  17759. minValue = it->value;
  17760. maxValue = it->value;
  17761. currentIntervalStart = it;
  17762. currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it->key)+reversedRound));
  17763. if (keyEpsilonVariable)
  17764. keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
  17765. intervalDataCount = 1;
  17766. }
  17767. // advance to next data point:
  17768. if (!doScatterSkip)
  17769. ++it;
  17770. else
  17771. {
  17772. itIndex += scatterModulo;
  17773. if (itIndex < endIndex) // make sure we didn't jump over end
  17774. it += scatterModulo;
  17775. else
  17776. {
  17777. it = end;
  17778. itIndex = endIndex;
  17779. }
  17780. }
  17781. }
  17782. // handle last interval:
  17783. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
  17784. {
  17785. // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
  17786. double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
  17787. int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
  17788. QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart;
  17789. int intervalItIndex = intervalIt-mDataContainer->constBegin();
  17790. int c = 0;
  17791. while (intervalIt != it)
  17792. {
  17793. if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange)
  17794. scatterData->append(*intervalIt);
  17795. ++c;
  17796. if (!doScatterSkip)
  17797. ++intervalIt;
  17798. 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:
  17799. {
  17800. intervalItIndex += scatterModulo;
  17801. if (intervalItIndex < itIndex)
  17802. intervalIt += scatterModulo;
  17803. else
  17804. {
  17805. intervalIt = it;
  17806. intervalItIndex = itIndex;
  17807. }
  17808. }
  17809. }
  17810. } else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange)
  17811. scatterData->append(*currentIntervalStart);
  17812. } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output
  17813. {
  17814. QCPGraphDataContainer::const_iterator it = begin;
  17815. int itIndex = beginIndex;
  17816. scatterData->reserve(dataCount);
  17817. while (it != end)
  17818. {
  17819. scatterData->append(*it);
  17820. // advance to next data point:
  17821. if (!doScatterSkip)
  17822. ++it;
  17823. else
  17824. {
  17825. itIndex += scatterModulo;
  17826. if (itIndex < endIndex)
  17827. it += scatterModulo;
  17828. else
  17829. {
  17830. it = end;
  17831. itIndex = endIndex;
  17832. }
  17833. }
  17834. }
  17835. }
  17836. }
  17837. /*!
  17838. This method outputs the currently visible data range via \a begin and \a end. The returned range
  17839. will also never exceed \a rangeRestriction.
  17840. This method takes into account that the drawing of data lines at the axis rect border always
  17841. requires the points just outside the visible axis range. So \a begin and \a end may actually
  17842. indicate a range that contains one additional data point to the left and right of the visible
  17843. axis range.
  17844. */
  17845. void QCPGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
  17846. {
  17847. if (rangeRestriction.isEmpty())
  17848. {
  17849. end = mDataContainer->constEnd();
  17850. begin = end;
  17851. } else
  17852. {
  17853. QCPAxis *keyAxis = mKeyAxis.data();
  17854. QCPAxis *valueAxis = mValueAxis.data();
  17855. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  17856. // get visible data range:
  17857. begin = mDataContainer->findBegin(keyAxis->range().lower);
  17858. end = mDataContainer->findEnd(keyAxis->range().upper);
  17859. // limit lower/upperEnd to rangeRestriction:
  17860. mDataContainer->limitIteratorsToDataRange(begin, end, rangeRestriction); // this also ensures rangeRestriction outside data bounds doesn't break anything
  17861. }
  17862. }
  17863. /*! \internal
  17864. This method goes through the passed points in \a lineData and returns a list of the segments
  17865. which don't contain NaN data points.
  17866. \a keyOrientation defines whether the \a x or \a y member of the passed QPointF is used to check
  17867. for NaN. If \a keyOrientation is \c Qt::Horizontal, the \a y member is checked, if it is \c
  17868. Qt::Vertical, the \a x member is checked.
  17869. \see getOverlappingSegments, drawFill
  17870. */
  17871. QVector<QCPDataRange> QCPGraph::getNonNanSegments(const QVector<QPointF> *lineData, Qt::Orientation keyOrientation) const
  17872. {
  17873. QVector<QCPDataRange> result;
  17874. const int n = lineData->size();
  17875. QCPDataRange currentSegment(-1, -1);
  17876. int i = 0;
  17877. if (keyOrientation == Qt::Horizontal)
  17878. {
  17879. while (i < n)
  17880. {
  17881. while (i < n && qIsNaN(lineData->at(i).y())) // seek next non-NaN data point
  17882. ++i;
  17883. if (i == n)
  17884. break;
  17885. currentSegment.setBegin(i++);
  17886. while (i < n && !qIsNaN(lineData->at(i).y())) // seek next NaN data point or end of data
  17887. ++i;
  17888. currentSegment.setEnd(i++);
  17889. result.append(currentSegment);
  17890. }
  17891. } else // keyOrientation == Qt::Vertical
  17892. {
  17893. while (i < n)
  17894. {
  17895. while (i < n && qIsNaN(lineData->at(i).x())) // seek next non-NaN data point
  17896. ++i;
  17897. if (i == n)
  17898. break;
  17899. currentSegment.setBegin(i++);
  17900. while (i < n && !qIsNaN(lineData->at(i).x())) // seek next NaN data point or end of data
  17901. ++i;
  17902. currentSegment.setEnd(i++);
  17903. result.append(currentSegment);
  17904. }
  17905. }
  17906. return result;
  17907. }
  17908. /*! \internal
  17909. This method takes two segment lists (e.g. created by \ref getNonNanSegments) \a thisSegments and
  17910. \a otherSegments, and their associated point data \a thisData and \a otherData.
  17911. It returns all pairs of segments (the first from \a thisSegments, the second from \a
  17912. otherSegments), which overlap in plot coordinates.
  17913. This method is useful in the case of a channel fill between two graphs, when only those non-NaN
  17914. segments which actually overlap in their key coordinate shall be considered for drawing a channel
  17915. fill polygon.
  17916. It is assumed that the passed segments in \a thisSegments are ordered ascending by index, and
  17917. that the segments don't overlap themselves. The same is assumed for the segments in \a
  17918. otherSegments. This is fulfilled when the segments are obtained via \ref getNonNanSegments.
  17919. \see getNonNanSegments, segmentsIntersect, drawFill, getChannelFillPolygon
  17920. */
  17921. QVector<QPair<QCPDataRange, QCPDataRange> > QCPGraph::getOverlappingSegments(QVector<QCPDataRange> thisSegments, const QVector<QPointF> *thisData, QVector<QCPDataRange> otherSegments, const QVector<QPointF> *otherData) const
  17922. {
  17923. QVector<QPair<QCPDataRange, QCPDataRange> > result;
  17924. if (thisData->isEmpty() || otherData->isEmpty() || thisSegments.isEmpty() || otherSegments.isEmpty())
  17925. return result;
  17926. int thisIndex = 0;
  17927. int otherIndex = 0;
  17928. const bool verticalKey = mKeyAxis->orientation() == Qt::Vertical;
  17929. while (thisIndex < thisSegments.size() && otherIndex < otherSegments.size())
  17930. {
  17931. if (thisSegments.at(thisIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow
  17932. {
  17933. ++thisIndex;
  17934. continue;
  17935. }
  17936. if (otherSegments.at(otherIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow
  17937. {
  17938. ++otherIndex;
  17939. continue;
  17940. }
  17941. double thisLower, thisUpper, otherLower, otherUpper;
  17942. if (!verticalKey)
  17943. {
  17944. thisLower = thisData->at(thisSegments.at(thisIndex).begin()).x();
  17945. thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).x();
  17946. otherLower = otherData->at(otherSegments.at(otherIndex).begin()).x();
  17947. otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).x();
  17948. } else
  17949. {
  17950. thisLower = thisData->at(thisSegments.at(thisIndex).begin()).y();
  17951. thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).y();
  17952. otherLower = otherData->at(otherSegments.at(otherIndex).begin()).y();
  17953. otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).y();
  17954. }
  17955. int bPrecedence;
  17956. if (segmentsIntersect(thisLower, thisUpper, otherLower, otherUpper, bPrecedence))
  17957. result.append(QPair<QCPDataRange, QCPDataRange>(thisSegments.at(thisIndex), otherSegments.at(otherIndex)));
  17958. if (bPrecedence <= 0) // otherSegment doesn't reach as far as thisSegment, so continue with next otherSegment, keeping current thisSegment
  17959. ++otherIndex;
  17960. else // otherSegment reaches further than thisSegment, so continue with next thisSegment, keeping current otherSegment
  17961. ++thisIndex;
  17962. }
  17963. return result;
  17964. }
  17965. /*! \internal
  17966. Returns whether the segments defined by the coordinates (aLower, aUpper) and (bLower, bUpper)
  17967. have overlap.
  17968. The output parameter \a bPrecedence indicates whether the \a b segment reaches farther than the
  17969. \a a segment or not. If \a bPrecedence returns 1, segment \a b reaches the farthest to higher
  17970. coordinates (i.e. bUpper > aUpper). If it returns -1, segment \a a reaches the farthest. Only if
  17971. both segment's upper bounds are identical, 0 is returned as \a bPrecedence.
  17972. It is assumed that the lower bounds always have smaller or equal values than the upper bounds.
  17973. \see getOverlappingSegments
  17974. */
  17975. bool QCPGraph::segmentsIntersect(double aLower, double aUpper, double bLower, double bUpper, int &bPrecedence) const
  17976. {
  17977. bPrecedence = 0;
  17978. if (aLower > bUpper)
  17979. {
  17980. bPrecedence = -1;
  17981. return false;
  17982. } else if (bLower > aUpper)
  17983. {
  17984. bPrecedence = 1;
  17985. return false;
  17986. } else
  17987. {
  17988. if (aUpper > bUpper)
  17989. bPrecedence = -1;
  17990. else if (aUpper < bUpper)
  17991. bPrecedence = 1;
  17992. return true;
  17993. }
  17994. }
  17995. /*! \internal
  17996. Returns the point which closes the fill polygon on the zero-value-line parallel to the key axis.
  17997. The logarithmic axis scale case is a bit special, since the zero-value-line in pixel coordinates
  17998. is in positive or negative infinity. So this case is handled separately by just closing the fill
  17999. polygon on the axis which lies in the direction towards the zero value.
  18000. \a matchingDataPoint will provide the key (in pixels) of the returned point. Depending on whether
  18001. the key axis of this graph is horizontal or vertical, \a matchingDataPoint will provide the x or
  18002. y value of the returned point, respectively.
  18003. */
  18004. QPointF QCPGraph::getFillBasePoint(QPointF matchingDataPoint) const
  18005. {
  18006. QCPAxis *keyAxis = mKeyAxis.data();
  18007. QCPAxis *valueAxis = mValueAxis.data();
  18008. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
  18009. QPointF result;
  18010. if (valueAxis->scaleType() == QCPAxis::stLinear)
  18011. {
  18012. if (keyAxis->orientation() == Qt::Horizontal)
  18013. {
  18014. result.setX(matchingDataPoint.x());
  18015. result.setY(valueAxis->coordToPixel(0));
  18016. } else // keyAxis->orientation() == Qt::Vertical
  18017. {
  18018. result.setX(valueAxis->coordToPixel(0));
  18019. result.setY(matchingDataPoint.y());
  18020. }
  18021. } else // valueAxis->mScaleType == QCPAxis::stLogarithmic
  18022. {
  18023. // In logarithmic scaling we can't just draw to value 0 so we just fill all the way
  18024. // to the axis which is in the direction towards 0
  18025. if (keyAxis->orientation() == Qt::Vertical)
  18026. {
  18027. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
  18028. (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
  18029. result.setX(keyAxis->axisRect()->right());
  18030. else
  18031. result.setX(keyAxis->axisRect()->left());
  18032. result.setY(matchingDataPoint.y());
  18033. } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom)
  18034. {
  18035. result.setX(matchingDataPoint.x());
  18036. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
  18037. (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
  18038. result.setY(keyAxis->axisRect()->top());
  18039. else
  18040. result.setY(keyAxis->axisRect()->bottom());
  18041. }
  18042. }
  18043. return result;
  18044. }
  18045. /*! \internal
  18046. Returns the polygon needed for drawing normal fills between this graph and the key axis.
  18047. Pass the graph's data points (in pixel coordinates) as \a lineData, and specify the \a segment
  18048. which shall be used for the fill. The collection of \a lineData points described by \a segment
  18049. must not contain NaN data points (see \ref getNonNanSegments).
  18050. The returned fill polygon will be closed at the key axis (the zero-value line) for linear value
  18051. axes. For logarithmic value axes the polygon will reach just beyond the corresponding axis rect
  18052. side (see \ref getFillBasePoint).
  18053. For increased performance (due to implicit sharing), keep the returned QPolygonF const.
  18054. \see drawFill, getNonNanSegments
  18055. */
  18056. const QPolygonF QCPGraph::getFillPolygon(const QVector<QPointF> *lineData, QCPDataRange segment) const
  18057. {
  18058. if (segment.size() < 2)
  18059. return QPolygonF();
  18060. QPolygonF result(segment.size()+2);
  18061. result[0] = getFillBasePoint(lineData->at(segment.begin()));
  18062. std::copy(lineData->constBegin()+segment.begin(), lineData->constBegin()+segment.end(), result.begin()+1);
  18063. result[result.size()-1] = getFillBasePoint(lineData->at(segment.end()-1));
  18064. return result;
  18065. }
  18066. /*! \internal
  18067. Returns the polygon needed for drawing (partial) channel fills between this graph and the graph
  18068. specified by \ref setChannelFillGraph.
  18069. The data points of this graph are passed as pixel coordinates via \a thisData, the data of the
  18070. other graph as \a otherData. The returned polygon will be calculated for the specified data
  18071. segments \a thisSegment and \a otherSegment, pertaining to the respective \a thisData and \a
  18072. otherData, respectively.
  18073. The passed \a thisSegment and \a otherSegment should correspond to the segment pairs returned by
  18074. \ref getOverlappingSegments, to make sure only segments that actually have key coordinate overlap
  18075. need to be processed here.
  18076. For increased performance due to implicit sharing, keep the returned QPolygonF const.
  18077. \see drawFill, getOverlappingSegments, getNonNanSegments
  18078. */
  18079. const QPolygonF QCPGraph::getChannelFillPolygon(const QVector<QPointF> *thisData, QCPDataRange thisSegment, const QVector<QPointF> *otherData, QCPDataRange otherSegment) const
  18080. {
  18081. if (!mChannelFillGraph)
  18082. return QPolygonF();
  18083. QCPAxis *keyAxis = mKeyAxis.data();
  18084. QCPAxis *valueAxis = mValueAxis.data();
  18085. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); }
  18086. if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); }
  18087. if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation())
  18088. 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)
  18089. if (thisData->isEmpty()) return QPolygonF();
  18090. QVector<QPointF> thisSegmentData(thisSegment.size());
  18091. QVector<QPointF> otherSegmentData(otherSegment.size());
  18092. std::copy(thisData->constBegin()+thisSegment.begin(), thisData->constBegin()+thisSegment.end(), thisSegmentData.begin());
  18093. std::copy(otherData->constBegin()+otherSegment.begin(), otherData->constBegin()+otherSegment.end(), otherSegmentData.begin());
  18094. // pointers to be able to swap them, depending which data range needs cropping:
  18095. QVector<QPointF> *staticData = &thisSegmentData;
  18096. QVector<QPointF> *croppedData = &otherSegmentData;
  18097. // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType):
  18098. if (keyAxis->orientation() == Qt::Horizontal)
  18099. {
  18100. // x is key
  18101. // crop lower bound:
  18102. if (staticData->first().x() < croppedData->first().x()) // other one must be cropped
  18103. qSwap(staticData, croppedData);
  18104. const int lowBound = findIndexBelowX(croppedData, staticData->first().x());
  18105. if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
  18106. croppedData->remove(0, lowBound);
  18107. // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation:
  18108. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18109. double slope;
  18110. if (!qFuzzyCompare(croppedData->at(1).x(), croppedData->at(0).x()))
  18111. slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x());
  18112. else
  18113. slope = 0;
  18114. (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x()));
  18115. (*croppedData)[0].setX(staticData->first().x());
  18116. // crop upper bound:
  18117. if (staticData->last().x() > croppedData->last().x()) // other one must be cropped
  18118. qSwap(staticData, croppedData);
  18119. int highBound = findIndexAboveX(croppedData, staticData->last().x());
  18120. if (highBound == -1) return QPolygonF(); // key ranges have no overlap
  18121. croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
  18122. // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation:
  18123. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18124. const int li = croppedData->size()-1; // last index
  18125. if (!qFuzzyCompare(croppedData->at(li).x(), croppedData->at(li-1).x()))
  18126. slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x());
  18127. else
  18128. slope = 0;
  18129. (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x()));
  18130. (*croppedData)[li].setX(staticData->last().x());
  18131. } else // mKeyAxis->orientation() == Qt::Vertical
  18132. {
  18133. // y is key
  18134. // crop lower bound:
  18135. if (staticData->first().y() < croppedData->first().y()) // other one must be cropped
  18136. qSwap(staticData, croppedData);
  18137. int lowBound = findIndexBelowY(croppedData, staticData->first().y());
  18138. if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
  18139. croppedData->remove(0, lowBound);
  18140. // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation:
  18141. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18142. double slope;
  18143. if (!qFuzzyCompare(croppedData->at(1).y(), croppedData->at(0).y())) // avoid division by zero in step plots
  18144. slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y());
  18145. else
  18146. slope = 0;
  18147. (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y()));
  18148. (*croppedData)[0].setY(staticData->first().y());
  18149. // crop upper bound:
  18150. if (staticData->last().y() > croppedData->last().y()) // other one must be cropped
  18151. qSwap(staticData, croppedData);
  18152. int highBound = findIndexAboveY(croppedData, staticData->last().y());
  18153. if (highBound == -1) return QPolygonF(); // key ranges have no overlap
  18154. croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
  18155. // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation:
  18156. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18157. int li = croppedData->size()-1; // last index
  18158. if (!qFuzzyCompare(croppedData->at(li).y(), croppedData->at(li-1).y())) // avoid division by zero in step plots
  18159. slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y());
  18160. else
  18161. slope = 0;
  18162. (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y()));
  18163. (*croppedData)[li].setY(staticData->last().y());
  18164. }
  18165. // return joined:
  18166. for (int i=otherSegmentData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted
  18167. thisSegmentData << otherSegmentData.at(i);
  18168. return QPolygonF(thisSegmentData);
  18169. }
  18170. /*! \internal
  18171. Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in
  18172. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  18173. axis is horizontal.
  18174. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  18175. */
  18176. int QCPGraph::findIndexAboveX(const QVector<QPointF> *data, double x) const
  18177. {
  18178. for (int i=data->size()-1; i>=0; --i)
  18179. {
  18180. if (data->at(i).x() < x)
  18181. {
  18182. if (i<data->size()-1)
  18183. return i+1;
  18184. else
  18185. return data->size()-1;
  18186. }
  18187. }
  18188. return -1;
  18189. }
  18190. /*! \internal
  18191. Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in
  18192. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  18193. axis is horizontal.
  18194. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  18195. */
  18196. int QCPGraph::findIndexBelowX(const QVector<QPointF> *data, double x) const
  18197. {
  18198. for (int i=0; i<data->size(); ++i)
  18199. {
  18200. if (data->at(i).x() > x)
  18201. {
  18202. if (i>0)
  18203. return i-1;
  18204. else
  18205. return 0;
  18206. }
  18207. }
  18208. return -1;
  18209. }
  18210. /*! \internal
  18211. Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in
  18212. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  18213. axis is vertical.
  18214. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  18215. */
  18216. int QCPGraph::findIndexAboveY(const QVector<QPointF> *data, double y) const
  18217. {
  18218. for (int i=data->size()-1; i>=0; --i)
  18219. {
  18220. if (data->at(i).y() < y)
  18221. {
  18222. if (i<data->size()-1)
  18223. return i+1;
  18224. else
  18225. return data->size()-1;
  18226. }
  18227. }
  18228. return -1;
  18229. }
  18230. /*! \internal
  18231. Calculates the minimum distance in pixels the graph's representation has from the given \a
  18232. pixelPoint. This is used to determine whether the graph was clicked or not, e.g. in \ref
  18233. selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that if
  18234. the graph has a line representation, the returned distance may be smaller than the distance to
  18235. the \a closestData point, since the distance to the graph line is also taken into account.
  18236. If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape
  18237. is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns -1.0.
  18238. */
  18239. double QCPGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const
  18240. {
  18241. closestData = mDataContainer->constEnd();
  18242. if (mDataContainer->isEmpty())
  18243. return -1.0;
  18244. if (mLineStyle == lsNone && mScatterStyle.isNone())
  18245. return -1.0;
  18246. // calculate minimum distances to graph data points and find closestData iterator:
  18247. double minDistSqr = std::numeric_limits<double>::max();
  18248. // determine which key range comes into question, taking selection tolerance around pos into account:
  18249. double posKeyMin, posKeyMax, dummy;
  18250. pixelsToCoords(pixelPoint-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy);
  18251. pixelsToCoords(pixelPoint+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy);
  18252. if (posKeyMin > posKeyMax)
  18253. qSwap(posKeyMin, posKeyMax);
  18254. // iterate over found data points and then choose the one with the shortest distance to pos:
  18255. QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true);
  18256. QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true);
  18257. for (QCPGraphDataContainer::const_iterator it=begin; it!=end; ++it)
  18258. {
  18259. const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
  18260. if (currentDistSqr < minDistSqr)
  18261. {
  18262. minDistSqr = currentDistSqr;
  18263. closestData = it;
  18264. }
  18265. }
  18266. // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point):
  18267. if (mLineStyle != lsNone)
  18268. {
  18269. // line displayed, calculate distance to line segments:
  18270. QVector<QPointF> lineData;
  18271. getLines(&lineData, QCPDataRange(0, dataCount()));
  18272. QCPVector2D p(pixelPoint);
  18273. const int step = mLineStyle==lsImpulse ? 2 : 1; // impulse plot differs from other line styles in that the lineData points are only pairwise connected
  18274. for (int i=0; i<lineData.size()-1; i+=step)
  18275. {
  18276. const double currentDistSqr = p.distanceSquaredToLine(lineData.at(i), lineData.at(i+1));
  18277. if (currentDistSqr < minDistSqr)
  18278. minDistSqr = currentDistSqr;
  18279. }
  18280. }
  18281. return qSqrt(minDistSqr);
  18282. }
  18283. /*! \internal
  18284. Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in
  18285. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  18286. axis is vertical.
  18287. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  18288. */
  18289. int QCPGraph::findIndexBelowY(const QVector<QPointF> *data, double y) const
  18290. {
  18291. for (int i=0; i<data->size(); ++i)
  18292. {
  18293. if (data->at(i).y() > y)
  18294. {
  18295. if (i>0)
  18296. return i-1;
  18297. else
  18298. return 0;
  18299. }
  18300. }
  18301. return -1;
  18302. }
  18303. /* end of 'src/plottables/plottable-graph.cpp' */
  18304. /* including file 'src/plottables/plottable-curve.cpp', size 63527 */
  18305. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  18306. ////////////////////////////////////////////////////////////////////////////////////////////////////
  18307. //////////////////// QCPCurveData
  18308. ////////////////////////////////////////////////////////////////////////////////////////////////////
  18309. /*! \class QCPCurveData
  18310. \brief Holds the data of one single data point for QCPCurve.
  18311. The stored data is:
  18312. \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)
  18313. \li \a key: coordinate on the key axis of this curve point (this is the \a mainKey)
  18314. \li \a value: coordinate on the value axis of this curve point (this is the \a mainValue)
  18315. The container for storing multiple data points is \ref QCPCurveDataContainer. It is a typedef for
  18316. \ref QCPDataContainer with \ref QCPCurveData as the DataType template parameter. See the
  18317. documentation there for an explanation regarding the data type's generic methods.
  18318. \see QCPCurveDataContainer
  18319. */
  18320. /* start documentation of inline functions */
  18321. /*! \fn double QCPCurveData::sortKey() const
  18322. Returns the \a t member of this data point.
  18323. For a general explanation of what this method is good for in the context of the data container,
  18324. see the documentation of \ref QCPDataContainer.
  18325. */
  18326. /*! \fn static QCPCurveData QCPCurveData::fromSortKey(double sortKey)
  18327. Returns a data point with the specified \a sortKey (assigned to the data point's \a t member).
  18328. All other members are set to zero.
  18329. For a general explanation of what this method is good for in the context of the data container,
  18330. see the documentation of \ref QCPDataContainer.
  18331. */
  18332. /*! \fn static static bool QCPCurveData::sortKeyIsMainKey()
  18333. Since the member \a key is the data point key coordinate and the member \a t is the data ordering
  18334. parameter, this method returns false.
  18335. For a general explanation of what this method is good for in the context of the data container,
  18336. see the documentation of \ref QCPDataContainer.
  18337. */
  18338. /*! \fn double QCPCurveData::mainKey() const
  18339. Returns the \a key member of this data point.
  18340. For a general explanation of what this method is good for in the context of the data container,
  18341. see the documentation of \ref QCPDataContainer.
  18342. */
  18343. /*! \fn double QCPCurveData::mainValue() const
  18344. Returns the \a value member of this data point.
  18345. For a general explanation of what this method is good for in the context of the data container,
  18346. see the documentation of \ref QCPDataContainer.
  18347. */
  18348. /*! \fn QCPRange QCPCurveData::valueRange() const
  18349. Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
  18350. For a general explanation of what this method is good for in the context of the data container,
  18351. see the documentation of \ref QCPDataContainer.
  18352. */
  18353. /* end documentation of inline functions */
  18354. /*!
  18355. Constructs a curve data point with t, key and value set to zero.
  18356. */
  18357. QCPCurveData::QCPCurveData() :
  18358. t(0),
  18359. key(0),
  18360. value(0)
  18361. {
  18362. }
  18363. /*!
  18364. Constructs a curve data point with the specified \a t, \a key and \a value.
  18365. */
  18366. QCPCurveData::QCPCurveData(double t, double key, double value) :
  18367. t(t),
  18368. key(key),
  18369. value(value)
  18370. {
  18371. }
  18372. ////////////////////////////////////////////////////////////////////////////////////////////////////
  18373. //////////////////// QCPCurve
  18374. ////////////////////////////////////////////////////////////////////////////////////////////////////
  18375. /*! \class QCPCurve
  18376. \brief A plottable representing a parametric curve in a plot.
  18377. \image html QCPCurve.png
  18378. Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate,
  18379. so their visual representation can have \a loops. This is realized by introducing a third
  18380. coordinate \a t, which defines the order of the points described by the other two coordinates \a
  18381. x and \a y.
  18382. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
  18383. also access and modify the curve's data via the \ref data method, which returns a pointer to the
  18384. internal \ref QCPCurveDataContainer.
  18385. Gaps in the curve can be created by adding data points with NaN as key and value
  18386. (<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
  18387. separated.
  18388. \section qcpcurve-appearance Changing the appearance
  18389. The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush).
  18390. \section qcpcurve-usage Usage
  18391. Like all data representing objects in QCustomPlot, the QCPCurve is a plottable
  18392. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  18393. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  18394. Usually, you first create an instance:
  18395. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-1
  18396. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  18397. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  18398. The newly created plottable can be modified, e.g.:
  18399. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-2
  18400. */
  18401. /* start of documentation of inline functions */
  18402. /*! \fn QSharedPointer<QCPCurveDataContainer> QCPCurve::data() const
  18403. Returns a shared pointer to the internal data storage of type \ref QCPCurveDataContainer. You may
  18404. use it to directly manipulate the data, which may be more convenient and faster than using the
  18405. regular \ref setData or \ref addData methods.
  18406. */
  18407. /* end of documentation of inline functions */
  18408. /*!
  18409. Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  18410. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  18411. the same orientation. If either of these restrictions is violated, a corresponding message is
  18412. printed to the debug output (qDebug), the construction is not aborted, though.
  18413. The created QCPCurve is automatically registered with the QCustomPlot instance inferred from \a
  18414. keyAxis. This QCustomPlot instance takes ownership of the QCPCurve, so do not delete it manually
  18415. but use QCustomPlot::removePlottable() instead.
  18416. */
  18417. QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  18418. QCPAbstractPlottable1D<QCPCurveData>(keyAxis, valueAxis)
  18419. {
  18420. // modify inherited properties from abstract plottable:
  18421. setPen(QPen(Qt::blue, 0));
  18422. setBrush(Qt::NoBrush);
  18423. setScatterStyle(QCPScatterStyle());
  18424. setLineStyle(lsLine);
  18425. setScatterSkip(0);
  18426. }
  18427. QCPCurve::~QCPCurve()
  18428. {
  18429. }
  18430. /*! \overload
  18431. Replaces the current data container with the provided \a data container.
  18432. Since a QSharedPointer is used, multiple QCPCurves may share the same data container safely.
  18433. Modifying the data in the container will then affect all curves that share the container. Sharing
  18434. can be achieved by simply exchanging the data containers wrapped in shared pointers:
  18435. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-1
  18436. If you do not wish to share containers, but create a copy from an existing container, rather use
  18437. the \ref QCPDataContainer<DataType>::set method on the curve's data container directly:
  18438. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-2
  18439. \see addData
  18440. */
  18441. void QCPCurve::setData(QSharedPointer<QCPCurveDataContainer> data)
  18442. {
  18443. mDataContainer = data;
  18444. }
  18445. /*! \overload
  18446. Replaces the current data with the provided points in \a t, \a keys and \a values. The provided
  18447. vectors should have equal length. Else, the number of added points will be the size of the
  18448. smallest vector.
  18449. If you can guarantee that the passed data points are sorted by \a t in ascending order, you can
  18450. set \a alreadySorted to true, to improve performance by saving a sorting run.
  18451. \see addData
  18452. */
  18453. void QCPCurve::setData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  18454. {
  18455. mDataContainer->clear();
  18456. addData(t, keys, values, alreadySorted);
  18457. }
  18458. /*! \overload
  18459. Replaces the current data with the provided points in \a keys and \a values. The provided vectors
  18460. should have equal length. Else, the number of added points will be the size of the smallest
  18461. vector.
  18462. The t parameter of each data point will be set to the integer index of the respective key/value
  18463. pair.
  18464. \see addData
  18465. */
  18466. void QCPCurve::setData(const QVector<double> &keys, const QVector<double> &values)
  18467. {
  18468. mDataContainer->clear();
  18469. addData(keys, values);
  18470. }
  18471. /*!
  18472. Sets the visual appearance of single data points in the plot. If set to \ref
  18473. QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate
  18474. line style).
  18475. \see QCPScatterStyle, setLineStyle
  18476. */
  18477. void QCPCurve::setScatterStyle(const QCPScatterStyle &style)
  18478. {
  18479. mScatterStyle = style;
  18480. }
  18481. /*!
  18482. If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of
  18483. scatter points are skipped/not drawn after every drawn scatter point.
  18484. This can be used to make the data appear sparser while for example still having a smooth line,
  18485. and to improve performance for very high density plots.
  18486. If \a skip is set to 0 (default), all scatter points are drawn.
  18487. \see setScatterStyle
  18488. */
  18489. void QCPCurve::setScatterSkip(int skip)
  18490. {
  18491. mScatterSkip = qMax(0, skip);
  18492. }
  18493. /*!
  18494. Sets how the single data points are connected in the plot or how they are represented visually
  18495. apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref
  18496. setScatterStyle to the desired scatter style.
  18497. \see setScatterStyle
  18498. */
  18499. void QCPCurve::setLineStyle(QCPCurve::LineStyle style)
  18500. {
  18501. mLineStyle = style;
  18502. }
  18503. /*! \overload
  18504. Adds the provided points in \a t, \a keys and \a values to the current data. The provided vectors
  18505. should have equal length. Else, the number of added points will be the size of the smallest
  18506. vector.
  18507. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  18508. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  18509. Alternatively, you can also access and modify the data directly via the \ref data method, which
  18510. returns a pointer to the internal data container.
  18511. */
  18512. void QCPCurve::addData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  18513. {
  18514. if (t.size() != keys.size() || t.size() != values.size())
  18515. qDebug() << Q_FUNC_INFO << "ts, keys and values have different sizes:" << t.size() << keys.size() << values.size();
  18516. const int n = qMin(qMin(t.size(), keys.size()), values.size());
  18517. QVector<QCPCurveData> tempData(n);
  18518. QVector<QCPCurveData>::iterator it = tempData.begin();
  18519. const QVector<QCPCurveData>::iterator itEnd = tempData.end();
  18520. int i = 0;
  18521. while (it != itEnd)
  18522. {
  18523. it->t = t[i];
  18524. it->key = keys[i];
  18525. it->value = values[i];
  18526. ++it;
  18527. ++i;
  18528. }
  18529. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  18530. }
  18531. /*! \overload
  18532. Adds the provided points in \a keys and \a values to the current data. The provided vectors
  18533. should have equal length. Else, the number of added points will be the size of the smallest
  18534. vector.
  18535. The t parameter of each data point will be set to the integer index of the respective key/value
  18536. pair.
  18537. Alternatively, you can also access and modify the data directly via the \ref data method, which
  18538. returns a pointer to the internal data container.
  18539. */
  18540. void QCPCurve::addData(const QVector<double> &keys, const QVector<double> &values)
  18541. {
  18542. if (keys.size() != values.size())
  18543. qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
  18544. const int n = qMin(keys.size(), values.size());
  18545. double tStart;
  18546. if (!mDataContainer->isEmpty())
  18547. tStart = (mDataContainer->constEnd()-1)->t + 1.0;
  18548. else
  18549. tStart = 0;
  18550. QVector<QCPCurveData> tempData(n);
  18551. QVector<QCPCurveData>::iterator it = tempData.begin();
  18552. const QVector<QCPCurveData>::iterator itEnd = tempData.end();
  18553. int i = 0;
  18554. while (it != itEnd)
  18555. {
  18556. it->t = tStart + i;
  18557. it->key = keys[i];
  18558. it->value = values[i];
  18559. ++it;
  18560. ++i;
  18561. }
  18562. mDataContainer->add(tempData, true); // don't modify tempData beyond this to prevent copy on write
  18563. }
  18564. /*! \overload
  18565. Adds the provided data point as \a t, \a key and \a value to the current data.
  18566. Alternatively, you can also access and modify the data directly via the \ref data method, which
  18567. returns a pointer to the internal data container.
  18568. */
  18569. void QCPCurve::addData(double t, double key, double value)
  18570. {
  18571. mDataContainer->add(QCPCurveData(t, key, value));
  18572. }
  18573. /*! \overload
  18574. Adds the provided data point as \a key and \a value to the current data.
  18575. The t parameter is generated automatically by increments of 1 for each point, starting at the
  18576. highest t of previously existing data or 0, if the curve data is empty.
  18577. Alternatively, you can also access and modify the data directly via the \ref data method, which
  18578. returns a pointer to the internal data container.
  18579. */
  18580. void QCPCurve::addData(double key, double value)
  18581. {
  18582. if (!mDataContainer->isEmpty())
  18583. mDataContainer->add(QCPCurveData((mDataContainer->constEnd()-1)->t + 1.0, key, value));
  18584. else
  18585. mDataContainer->add(QCPCurveData(0.0, key, value));
  18586. }
  18587. /* inherits documentation from base class */
  18588. double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  18589. {
  18590. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  18591. return -1;
  18592. if (!mKeyAxis || !mValueAxis)
  18593. return -1;
  18594. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
  18595. {
  18596. QCPCurveDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  18597. double result = pointDistance(pos, closestDataPoint);
  18598. if (details)
  18599. {
  18600. int pointIndex = closestDataPoint-mDataContainer->constBegin();
  18601. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  18602. }
  18603. return result;
  18604. } else
  18605. return -1;
  18606. }
  18607. /* inherits documentation from base class */
  18608. QCPRange QCPCurve::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  18609. {
  18610. return mDataContainer->keyRange(foundRange, inSignDomain);
  18611. }
  18612. /* inherits documentation from base class */
  18613. QCPRange QCPCurve::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  18614. {
  18615. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  18616. }
  18617. /* inherits documentation from base class */
  18618. void QCPCurve::draw(QCPPainter *painter)
  18619. {
  18620. if (mDataContainer->isEmpty()) return;
  18621. // allocate line vector:
  18622. QVector<QPointF> lines, scatters;
  18623. // loop over and draw segments of unselected/selected data:
  18624. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  18625. getDataSegments(selectedSegments, unselectedSegments);
  18626. allSegments << unselectedSegments << selectedSegments;
  18627. for (int i=0; i<allSegments.size(); ++i)
  18628. {
  18629. bool isSelectedSegment = i >= unselectedSegments.size();
  18630. // fill with curve data:
  18631. QPen finalCurvePen = mPen; // determine the final pen already here, because the line optimization depends on its stroke width
  18632. if (isSelectedSegment && mSelectionDecorator)
  18633. finalCurvePen = mSelectionDecorator->pen();
  18634. 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)
  18635. getCurveLines(&lines, lineDataRange, finalCurvePen.widthF());
  18636. // check data validity if flag set:
  18637. #ifdef QCUSTOMPLOT_CHECK_DATA
  18638. for (QCPCurveDataContainer::const_iterator it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  18639. {
  18640. if (QCP::isInvalidData(it->t) ||
  18641. QCP::isInvalidData(it->key, it->value))
  18642. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
  18643. }
  18644. #endif
  18645. // draw curve fill:
  18646. applyFillAntialiasingHint(painter);
  18647. if (isSelectedSegment && mSelectionDecorator)
  18648. mSelectionDecorator->applyBrush(painter);
  18649. else
  18650. painter->setBrush(mBrush);
  18651. painter->setPen(Qt::NoPen);
  18652. if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0)
  18653. painter->drawPolygon(QPolygonF(lines));
  18654. // draw curve line:
  18655. if (mLineStyle != lsNone)
  18656. {
  18657. painter->setPen(finalCurvePen);
  18658. painter->setBrush(Qt::NoBrush);
  18659. drawCurveLine(painter, lines);
  18660. }
  18661. // draw scatters:
  18662. QCPScatterStyle finalScatterStyle = mScatterStyle;
  18663. if (isSelectedSegment && mSelectionDecorator)
  18664. finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
  18665. if (!finalScatterStyle.isNone())
  18666. {
  18667. getScatters(&scatters, allSegments.at(i), finalScatterStyle.size());
  18668. drawScatterPlot(painter, scatters, finalScatterStyle);
  18669. }
  18670. }
  18671. // draw other selection decoration that isn't just line/scatter pens and brushes:
  18672. if (mSelectionDecorator)
  18673. mSelectionDecorator->drawDecoration(painter, selection());
  18674. }
  18675. /* inherits documentation from base class */
  18676. void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  18677. {
  18678. // draw fill:
  18679. if (mBrush.style() != Qt::NoBrush)
  18680. {
  18681. applyFillAntialiasingHint(painter);
  18682. painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
  18683. }
  18684. // draw line vertically centered:
  18685. if (mLineStyle != lsNone)
  18686. {
  18687. applyDefaultAntialiasingHint(painter);
  18688. painter->setPen(mPen);
  18689. 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
  18690. }
  18691. // draw scatter symbol:
  18692. if (!mScatterStyle.isNone())
  18693. {
  18694. applyScattersAntialiasingHint(painter);
  18695. // scale scatter pixmap if it's too large to fit in legend icon rect:
  18696. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
  18697. {
  18698. QCPScatterStyle scaledStyle(mScatterStyle);
  18699. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  18700. scaledStyle.applyTo(painter, mPen);
  18701. scaledStyle.drawShape(painter, QRectF(rect).center());
  18702. } else
  18703. {
  18704. mScatterStyle.applyTo(painter, mPen);
  18705. mScatterStyle.drawShape(painter, QRectF(rect).center());
  18706. }
  18707. }
  18708. }
  18709. /*! \internal
  18710. Draws lines between the points in \a lines, given in pixel coordinates.
  18711. \see drawScatterPlot, getCurveLines
  18712. */
  18713. void QCPCurve::drawCurveLine(QCPPainter *painter, const QVector<QPointF> &lines) const
  18714. {
  18715. if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
  18716. {
  18717. applyDefaultAntialiasingHint(painter);
  18718. drawPolyline(painter, lines);
  18719. }
  18720. }
  18721. /*! \internal
  18722. Draws scatter symbols at every point passed in \a points, given in pixel coordinates. The
  18723. scatters will be drawn with \a painter and have the appearance as specified in \a style.
  18724. \see drawCurveLine, getCurveLines
  18725. */
  18726. void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &points, const QCPScatterStyle &style) const
  18727. {
  18728. // draw scatter point symbols:
  18729. applyScattersAntialiasingHint(painter);
  18730. style.applyTo(painter, mPen);
  18731. for (int i=0; i<points.size(); ++i)
  18732. if (!qIsNaN(points.at(i).x()) && !qIsNaN(points.at(i).y()))
  18733. style.drawShape(painter, points.at(i));
  18734. }
  18735. /*! \internal
  18736. Called by \ref draw to generate points in pixel coordinates which represent the line of the
  18737. curve.
  18738. Line segments that aren't visible in the current axis rect are handled in an optimized way. They
  18739. are projected onto a rectangle slightly larger than the visible axis rect and simplified
  18740. regarding point count. The algorithm makes sure to preserve appearance of lines and fills inside
  18741. the visible axis rect by generating new temporary points on the outer rect if necessary.
  18742. \a lines will be filled with points in pixel coordinates, that can be drawn with \ref
  18743. drawCurveLine.
  18744. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  18745. conversion. In this function, the specified range may exceed the total data bounds without harm:
  18746. a correspondingly trimmed data range will be used. This takes the burden off the user of this
  18747. function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
  18748. getDataSegments.
  18749. \a penWidth specifies the pen width that will be used to later draw the lines generated by this
  18750. function. This is needed here to calculate an accordingly wider margin around the axis rect when
  18751. performing the line optimization.
  18752. Methods that are also involved in the algorithm are: \ref getRegion, \ref getOptimizedPoint, \ref
  18753. getOptimizedCornerPoints \ref mayTraverse, \ref getTraverse, \ref getTraverseCornerPoints.
  18754. \see drawCurveLine, drawScatterPlot
  18755. */
  18756. void QCPCurve::getCurveLines(QVector<QPointF> *lines, const QCPDataRange &dataRange, double penWidth) const
  18757. {
  18758. if (!lines) return;
  18759. lines->clear();
  18760. QCPAxis *keyAxis = mKeyAxis.data();
  18761. QCPAxis *valueAxis = mValueAxis.data();
  18762. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  18763. // add margins to rect to compensate for stroke width
  18764. const double strokeMargin = qMax(qreal(1.0), qreal(penWidth*0.75)); // stroke radius + 50% safety
  18765. const double keyMin = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().lower)-strokeMargin*keyAxis->pixelOrientation());
  18766. const double keyMax = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().upper)+strokeMargin*keyAxis->pixelOrientation());
  18767. const double valueMin = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().lower)-strokeMargin*valueAxis->pixelOrientation());
  18768. const double valueMax = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().upper)+strokeMargin*valueAxis->pixelOrientation());
  18769. QCPCurveDataContainer::const_iterator itBegin = mDataContainer->constBegin();
  18770. QCPCurveDataContainer::const_iterator itEnd = mDataContainer->constEnd();
  18771. mDataContainer->limitIteratorsToDataRange(itBegin, itEnd, dataRange);
  18772. if (itBegin == itEnd)
  18773. return;
  18774. QCPCurveDataContainer::const_iterator it = itBegin;
  18775. QCPCurveDataContainer::const_iterator prevIt = itEnd-1;
  18776. int prevRegion = getRegion(prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin);
  18777. 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)
  18778. while (it != itEnd)
  18779. {
  18780. const int currentRegion = getRegion(it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  18781. if (currentRegion != prevRegion) // changed region, possibly need to add some optimized edge points or original points if entering R
  18782. {
  18783. if (currentRegion != 5) // segment doesn't end in R, so it's a candidate for removal
  18784. {
  18785. QPointF crossA, crossB;
  18786. if (prevRegion == 5) // we're coming from R, so add this point optimized
  18787. {
  18788. lines->append(getOptimizedPoint(currentRegion, it->key, it->value, prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin));
  18789. // 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
  18790. *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  18791. } else if (mayTraverse(prevRegion, currentRegion) &&
  18792. getTraverse(prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin, crossA, crossB))
  18793. {
  18794. // add the two cross points optimized if segment crosses R and if segment isn't virtual zeroth segment between last and first curve point:
  18795. QVector<QPointF> beforeTraverseCornerPoints, afterTraverseCornerPoints;
  18796. getTraverseCornerPoints(prevRegion, currentRegion, keyMin, valueMax, keyMax, valueMin, beforeTraverseCornerPoints, afterTraverseCornerPoints);
  18797. if (it != itBegin)
  18798. {
  18799. *lines << beforeTraverseCornerPoints;
  18800. lines->append(crossA);
  18801. lines->append(crossB);
  18802. *lines << afterTraverseCornerPoints;
  18803. } else
  18804. {
  18805. lines->append(crossB);
  18806. *lines << afterTraverseCornerPoints;
  18807. trailingPoints << beforeTraverseCornerPoints << crossA ;
  18808. }
  18809. } 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)
  18810. {
  18811. *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  18812. }
  18813. } else // segment does end in R, so we add previous point optimized and this point at original position
  18814. {
  18815. 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
  18816. trailingPoints << getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  18817. else
  18818. lines->append(getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin));
  18819. lines->append(coordsToPixels(it->key, it->value));
  18820. }
  18821. } else // region didn't change
  18822. {
  18823. if (currentRegion == 5) // still in R, keep adding original points
  18824. {
  18825. lines->append(coordsToPixels(it->key, it->value));
  18826. } else // still outside R, no need to add anything
  18827. {
  18828. // see how this is not doing anything? That's the main optimization...
  18829. }
  18830. }
  18831. prevIt = it;
  18832. prevRegion = currentRegion;
  18833. ++it;
  18834. }
  18835. *lines << trailingPoints;
  18836. }
  18837. /*! \internal
  18838. Called by \ref draw to generate points in pixel coordinates which represent the scatters of the
  18839. curve. If a scatter skip is configured (\ref setScatterSkip), the returned points are accordingly
  18840. sparser.
  18841. Scatters that aren't visible in the current axis rect are optimized away.
  18842. \a scatters will be filled with points in pixel coordinates, that can be drawn with \ref
  18843. drawScatterPlot.
  18844. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  18845. conversion.
  18846. \a scatterWidth specifies the scatter width that will be used to later draw the scatters at pixel
  18847. coordinates generated by this function. This is needed here to calculate an accordingly wider
  18848. margin around the axis rect when performing the data point reduction.
  18849. \see draw, drawScatterPlot
  18850. */
  18851. void QCPCurve::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange, double scatterWidth) const
  18852. {
  18853. if (!scatters) return;
  18854. scatters->clear();
  18855. QCPAxis *keyAxis = mKeyAxis.data();
  18856. QCPAxis *valueAxis = mValueAxis.data();
  18857. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  18858. QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin();
  18859. QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd();
  18860. mDataContainer->limitIteratorsToDataRange(begin, end, dataRange);
  18861. if (begin == end)
  18862. return;
  18863. const int scatterModulo = mScatterSkip+1;
  18864. const bool doScatterSkip = mScatterSkip > 0;
  18865. int endIndex = end-mDataContainer->constBegin();
  18866. QCPRange keyRange = keyAxis->range();
  18867. QCPRange valueRange = valueAxis->range();
  18868. // extend range to include width of scatter symbols:
  18869. keyRange.lower = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.lower)-scatterWidth*keyAxis->pixelOrientation());
  18870. keyRange.upper = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.upper)+scatterWidth*keyAxis->pixelOrientation());
  18871. valueRange.lower = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.lower)-scatterWidth*valueAxis->pixelOrientation());
  18872. valueRange.upper = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.upper)+scatterWidth*valueAxis->pixelOrientation());
  18873. QCPCurveDataContainer::const_iterator it = begin;
  18874. int itIndex = begin-mDataContainer->constBegin();
  18875. while (doScatterSkip && it != end && itIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter
  18876. {
  18877. ++itIndex;
  18878. ++it;
  18879. }
  18880. if (keyAxis->orientation() == Qt::Vertical)
  18881. {
  18882. while (it != end)
  18883. {
  18884. if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value))
  18885. scatters->append(QPointF(valueAxis->coordToPixel(it->value), keyAxis->coordToPixel(it->key)));
  18886. // advance iterator to next (non-skipped) data point:
  18887. if (!doScatterSkip)
  18888. ++it;
  18889. else
  18890. {
  18891. itIndex += scatterModulo;
  18892. if (itIndex < endIndex) // make sure we didn't jump over end
  18893. it += scatterModulo;
  18894. else
  18895. {
  18896. it = end;
  18897. itIndex = endIndex;
  18898. }
  18899. }
  18900. }
  18901. } else
  18902. {
  18903. while (it != end)
  18904. {
  18905. if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value))
  18906. scatters->append(QPointF(keyAxis->coordToPixel(it->key), valueAxis->coordToPixel(it->value)));
  18907. // advance iterator to next (non-skipped) data point:
  18908. if (!doScatterSkip)
  18909. ++it;
  18910. else
  18911. {
  18912. itIndex += scatterModulo;
  18913. if (itIndex < endIndex) // make sure we didn't jump over end
  18914. it += scatterModulo;
  18915. else
  18916. {
  18917. it = end;
  18918. itIndex = endIndex;
  18919. }
  18920. }
  18921. }
  18922. }
  18923. }
  18924. /*! \internal
  18925. This function is part of the curve optimization algorithm of \ref getCurveLines.
  18926. It returns the region of the given point (\a key, \a value) with respect to a rectangle defined
  18927. by \a keyMin, \a keyMax, \a valueMin, and \a valueMax.
  18928. The regions are enumerated from top to bottom (\a valueMin to \a valueMax) and left to right (\a
  18929. keyMin to \a keyMax):
  18930. <table style="width:10em; text-align:center">
  18931. <tr><td>1</td><td>4</td><td>7</td></tr>
  18932. <tr><td>2</td><td style="border:1px solid black">5</td><td>8</td></tr>
  18933. <tr><td>3</td><td>6</td><td>9</td></tr>
  18934. </table>
  18935. With the rectangle being region 5, and the outer regions extending infinitely outwards. In the
  18936. curve optimization algorithm, region 5 is considered to be the visible portion of the plot.
  18937. */
  18938. int QCPCurve::getRegion(double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
  18939. {
  18940. if (key < keyMin) // region 123
  18941. {
  18942. if (value > valueMax)
  18943. return 1;
  18944. else if (value < valueMin)
  18945. return 3;
  18946. else
  18947. return 2;
  18948. } else if (key > keyMax) // region 789
  18949. {
  18950. if (value > valueMax)
  18951. return 7;
  18952. else if (value < valueMin)
  18953. return 9;
  18954. else
  18955. return 8;
  18956. } else // region 456
  18957. {
  18958. if (value > valueMax)
  18959. return 4;
  18960. else if (value < valueMin)
  18961. return 6;
  18962. else
  18963. return 5;
  18964. }
  18965. }
  18966. /*! \internal
  18967. This function is part of the curve optimization algorithm of \ref getCurveLines.
  18968. This method is used in case the current segment passes from inside the visible rect (region 5,
  18969. see \ref getRegion) to any of the outer regions (\a otherRegion). The current segment is given by
  18970. the line connecting (\a key, \a value) with (\a otherKey, \a otherValue).
  18971. It returns the intersection point of the segment with the border of region 5.
  18972. For this function it doesn't matter whether (\a key, \a value) is the point inside region 5 or
  18973. whether it's (\a otherKey, \a otherValue), i.e. whether the segment is coming from region 5 or
  18974. leaving it. It is important though that \a otherRegion correctly identifies the other region not
  18975. equal to 5.
  18976. */
  18977. QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
  18978. {
  18979. // The intersection point interpolation here is done in pixel coordinates, so we don't need to
  18980. // differentiate between different axis scale types. Note that the nomenclature
  18981. // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be
  18982. // different in pixel coordinates (horz/vert key axes, reversed ranges)
  18983. const double keyMinPx = mKeyAxis->coordToPixel(keyMin);
  18984. const double keyMaxPx = mKeyAxis->coordToPixel(keyMax);
  18985. const double valueMinPx = mValueAxis->coordToPixel(valueMin);
  18986. const double valueMaxPx = mValueAxis->coordToPixel(valueMax);
  18987. const double otherValuePx = mValueAxis->coordToPixel(otherValue);
  18988. const double valuePx = mValueAxis->coordToPixel(value);
  18989. const double otherKeyPx = mKeyAxis->coordToPixel(otherKey);
  18990. const double keyPx = mKeyAxis->coordToPixel(key);
  18991. double intersectKeyPx = keyMinPx; // initial key just a fail-safe
  18992. double intersectValuePx = valueMinPx; // initial value just a fail-safe
  18993. switch (otherRegion)
  18994. {
  18995. case 1: // top and left edge
  18996. {
  18997. intersectValuePx = valueMaxPx;
  18998. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  18999. 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)
  19000. {
  19001. intersectKeyPx = keyMinPx;
  19002. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19003. }
  19004. break;
  19005. }
  19006. case 2: // left edge
  19007. {
  19008. intersectKeyPx = keyMinPx;
  19009. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19010. break;
  19011. }
  19012. case 3: // bottom and left edge
  19013. {
  19014. intersectValuePx = valueMinPx;
  19015. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19016. 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)
  19017. {
  19018. intersectKeyPx = keyMinPx;
  19019. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19020. }
  19021. break;
  19022. }
  19023. case 4: // top edge
  19024. {
  19025. intersectValuePx = valueMaxPx;
  19026. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19027. break;
  19028. }
  19029. case 5:
  19030. {
  19031. break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table
  19032. }
  19033. case 6: // bottom edge
  19034. {
  19035. intersectValuePx = valueMinPx;
  19036. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19037. break;
  19038. }
  19039. case 7: // top and right edge
  19040. {
  19041. intersectValuePx = valueMaxPx;
  19042. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19043. 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)
  19044. {
  19045. intersectKeyPx = keyMaxPx;
  19046. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19047. }
  19048. break;
  19049. }
  19050. case 8: // right edge
  19051. {
  19052. intersectKeyPx = keyMaxPx;
  19053. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19054. break;
  19055. }
  19056. case 9: // bottom and right edge
  19057. {
  19058. intersectValuePx = valueMinPx;
  19059. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19060. 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)
  19061. {
  19062. intersectKeyPx = keyMaxPx;
  19063. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19064. }
  19065. break;
  19066. }
  19067. }
  19068. if (mKeyAxis->orientation() == Qt::Horizontal)
  19069. return QPointF(intersectKeyPx, intersectValuePx);
  19070. else
  19071. return QPointF(intersectValuePx, intersectKeyPx);
  19072. }
  19073. /*! \internal
  19074. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19075. In situations where a single segment skips over multiple regions it might become necessary to add
  19076. extra points at the corners of region 5 (see \ref getRegion) such that the optimized segment
  19077. doesn't unintentionally cut through the visible area of the axis rect and create plot artifacts.
  19078. This method provides these points that must be added, assuming the original segment doesn't
  19079. start, end, or traverse region 5. (Corner points where region 5 is traversed are calculated by
  19080. \ref getTraverseCornerPoints.)
  19081. For example, consider a segment which directly goes from region 4 to 2 but originally is far out
  19082. to the top left such that it doesn't cross region 5. Naively optimizing these points by
  19083. projecting them on the top and left borders of region 5 will create a segment that surely crosses
  19084. 5, creating a visual artifact in the plot. This method prevents this by providing extra points at
  19085. the top left corner, making the optimized curve correctly pass from region 4 to 1 to 2 without
  19086. traversing 5.
  19087. */
  19088. 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
  19089. {
  19090. QVector<QPointF> result;
  19091. switch (prevRegion)
  19092. {
  19093. case 1:
  19094. {
  19095. switch (currentRegion)
  19096. {
  19097. case 2: { result << coordsToPixels(keyMin, valueMax); break; }
  19098. case 4: { result << coordsToPixels(keyMin, valueMax); break; }
  19099. case 3: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); break; }
  19100. case 7: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); break; }
  19101. case 6: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19102. case 8: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19103. 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
  19104. if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R
  19105. { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); }
  19106. else
  19107. { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); }
  19108. break;
  19109. }
  19110. }
  19111. break;
  19112. }
  19113. case 2:
  19114. {
  19115. switch (currentRegion)
  19116. {
  19117. case 1: { result << coordsToPixels(keyMin, valueMax); break; }
  19118. case 3: { result << coordsToPixels(keyMin, valueMin); break; }
  19119. case 4: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19120. case 6: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19121. case 7: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; }
  19122. case 9: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; }
  19123. }
  19124. break;
  19125. }
  19126. case 3:
  19127. {
  19128. switch (currentRegion)
  19129. {
  19130. case 2: { result << coordsToPixels(keyMin, valueMin); break; }
  19131. case 6: { result << coordsToPixels(keyMin, valueMin); break; }
  19132. case 1: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); break; }
  19133. case 9: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); break; }
  19134. case 4: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19135. case 8: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19136. 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
  19137. if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R
  19138. { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); }
  19139. else
  19140. { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); }
  19141. break;
  19142. }
  19143. }
  19144. break;
  19145. }
  19146. case 4:
  19147. {
  19148. switch (currentRegion)
  19149. {
  19150. case 1: { result << coordsToPixels(keyMin, valueMax); break; }
  19151. case 7: { result << coordsToPixels(keyMax, valueMax); break; }
  19152. case 2: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19153. case 8: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19154. case 3: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; }
  19155. case 9: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; }
  19156. }
  19157. break;
  19158. }
  19159. case 5:
  19160. {
  19161. switch (currentRegion)
  19162. {
  19163. case 1: { result << coordsToPixels(keyMin, valueMax); break; }
  19164. case 7: { result << coordsToPixels(keyMax, valueMax); break; }
  19165. case 9: { result << coordsToPixels(keyMax, valueMin); break; }
  19166. case 3: { result << coordsToPixels(keyMin, valueMin); break; }
  19167. }
  19168. break;
  19169. }
  19170. case 6:
  19171. {
  19172. switch (currentRegion)
  19173. {
  19174. case 3: { result << coordsToPixels(keyMin, valueMin); break; }
  19175. case 9: { result << coordsToPixels(keyMax, valueMin); break; }
  19176. case 2: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19177. case 8: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19178. case 1: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; }
  19179. case 7: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; }
  19180. }
  19181. break;
  19182. }
  19183. case 7:
  19184. {
  19185. switch (currentRegion)
  19186. {
  19187. case 4: { result << coordsToPixels(keyMax, valueMax); break; }
  19188. case 8: { result << coordsToPixels(keyMax, valueMax); break; }
  19189. case 1: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); break; }
  19190. case 9: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); break; }
  19191. case 2: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19192. case 6: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19193. 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
  19194. if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R
  19195. { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); }
  19196. else
  19197. { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); }
  19198. break;
  19199. }
  19200. }
  19201. break;
  19202. }
  19203. case 8:
  19204. {
  19205. switch (currentRegion)
  19206. {
  19207. case 7: { result << coordsToPixels(keyMax, valueMax); break; }
  19208. case 9: { result << coordsToPixels(keyMax, valueMin); break; }
  19209. case 4: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19210. case 6: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19211. case 1: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; }
  19212. case 3: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; }
  19213. }
  19214. break;
  19215. }
  19216. case 9:
  19217. {
  19218. switch (currentRegion)
  19219. {
  19220. case 6: { result << coordsToPixels(keyMax, valueMin); break; }
  19221. case 8: { result << coordsToPixels(keyMax, valueMin); break; }
  19222. case 3: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); break; }
  19223. case 7: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); break; }
  19224. case 2: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19225. case 4: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19226. 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
  19227. if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R
  19228. { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); }
  19229. else
  19230. { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); }
  19231. break;
  19232. }
  19233. }
  19234. break;
  19235. }
  19236. }
  19237. return result;
  19238. }
  19239. /*! \internal
  19240. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19241. This method returns whether a segment going from \a prevRegion to \a currentRegion (see \ref
  19242. getRegion) may traverse the visible region 5. This function assumes that neither \a prevRegion
  19243. nor \a currentRegion is 5 itself.
  19244. If this method returns false, the segment for sure doesn't pass region 5. If it returns true, the
  19245. segment may or may not pass region 5 and a more fine-grained calculation must be used (\ref
  19246. getTraverse).
  19247. */
  19248. bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const
  19249. {
  19250. switch (prevRegion)
  19251. {
  19252. case 1:
  19253. {
  19254. switch (currentRegion)
  19255. {
  19256. case 4:
  19257. case 7:
  19258. case 2:
  19259. case 3: return false;
  19260. default: return true;
  19261. }
  19262. }
  19263. case 2:
  19264. {
  19265. switch (currentRegion)
  19266. {
  19267. case 1:
  19268. case 3: return false;
  19269. default: return true;
  19270. }
  19271. }
  19272. case 3:
  19273. {
  19274. switch (currentRegion)
  19275. {
  19276. case 1:
  19277. case 2:
  19278. case 6:
  19279. case 9: return false;
  19280. default: return true;
  19281. }
  19282. }
  19283. case 4:
  19284. {
  19285. switch (currentRegion)
  19286. {
  19287. case 1:
  19288. case 7: return false;
  19289. default: return true;
  19290. }
  19291. }
  19292. case 5: return false; // should never occur
  19293. case 6:
  19294. {
  19295. switch (currentRegion)
  19296. {
  19297. case 3:
  19298. case 9: return false;
  19299. default: return true;
  19300. }
  19301. }
  19302. case 7:
  19303. {
  19304. switch (currentRegion)
  19305. {
  19306. case 1:
  19307. case 4:
  19308. case 8:
  19309. case 9: return false;
  19310. default: return true;
  19311. }
  19312. }
  19313. case 8:
  19314. {
  19315. switch (currentRegion)
  19316. {
  19317. case 7:
  19318. case 9: return false;
  19319. default: return true;
  19320. }
  19321. }
  19322. case 9:
  19323. {
  19324. switch (currentRegion)
  19325. {
  19326. case 3:
  19327. case 6:
  19328. case 8:
  19329. case 7: return false;
  19330. default: return true;
  19331. }
  19332. }
  19333. default: return true;
  19334. }
  19335. }
  19336. /*! \internal
  19337. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19338. This method assumes that the \ref mayTraverse test has returned true, so there is a chance the
  19339. segment defined by (\a prevKey, \a prevValue) and (\a key, \a value) goes through the visible
  19340. region 5.
  19341. The return value of this method indicates whether the segment actually traverses region 5 or not.
  19342. If the segment traverses 5, the output parameters \a crossA and \a crossB indicate the entry and
  19343. exit points of region 5. They will become the optimized points for that segment.
  19344. */
  19345. bool QCPCurve::getTraverse(double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin, QPointF &crossA, QPointF &crossB) const
  19346. {
  19347. // The intersection point interpolation here is done in pixel coordinates, so we don't need to
  19348. // differentiate between different axis scale types. Note that the nomenclature
  19349. // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be
  19350. // different in pixel coordinates (horz/vert key axes, reversed ranges)
  19351. QList<QPointF> intersections;
  19352. const double valueMinPx = mValueAxis->coordToPixel(valueMin);
  19353. const double valueMaxPx = mValueAxis->coordToPixel(valueMax);
  19354. const double keyMinPx = mKeyAxis->coordToPixel(keyMin);
  19355. const double keyMaxPx = mKeyAxis->coordToPixel(keyMax);
  19356. const double keyPx = mKeyAxis->coordToPixel(key);
  19357. const double valuePx = mValueAxis->coordToPixel(value);
  19358. const double prevKeyPx = mKeyAxis->coordToPixel(prevKey);
  19359. const double prevValuePx = mValueAxis->coordToPixel(prevValue);
  19360. if (qFuzzyIsNull(key-prevKey)) // line is parallel to value axis
  19361. {
  19362. // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here
  19363. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMinPx) : QPointF(valueMinPx, keyPx)); // direction will be taken care of at end of method
  19364. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMaxPx) : QPointF(valueMaxPx, keyPx));
  19365. } else if (qFuzzyIsNull(value-prevValue)) // line is parallel to key axis
  19366. {
  19367. // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here
  19368. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, valuePx) : QPointF(valuePx, keyMinPx)); // direction will be taken care of at end of method
  19369. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, valuePx) : QPointF(valuePx, keyMaxPx));
  19370. } else // line is skewed
  19371. {
  19372. double gamma;
  19373. double keyPerValuePx = (keyPx-prevKeyPx)/(valuePx-prevValuePx);
  19374. // check top of rect:
  19375. gamma = prevKeyPx + (valueMaxPx-prevValuePx)*keyPerValuePx;
  19376. if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed
  19377. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMaxPx) : QPointF(valueMaxPx, gamma));
  19378. // check bottom of rect:
  19379. gamma = prevKeyPx + (valueMinPx-prevValuePx)*keyPerValuePx;
  19380. if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed
  19381. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMinPx) : QPointF(valueMinPx, gamma));
  19382. const double valuePerKeyPx = 1.0/keyPerValuePx;
  19383. // check left of rect:
  19384. gamma = prevValuePx + (keyMinPx-prevKeyPx)*valuePerKeyPx;
  19385. if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed
  19386. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, gamma) : QPointF(gamma, keyMinPx));
  19387. // check right of rect:
  19388. gamma = prevValuePx + (keyMaxPx-prevKeyPx)*valuePerKeyPx;
  19389. if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed
  19390. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, gamma) : QPointF(gamma, keyMaxPx));
  19391. }
  19392. // handle cases where found points isn't exactly 2:
  19393. if (intersections.size() > 2)
  19394. {
  19395. // line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between:
  19396. double distSqrMax = 0;
  19397. QPointF pv1, pv2;
  19398. for (int i=0; i<intersections.size()-1; ++i)
  19399. {
  19400. for (int k=i+1; k<intersections.size(); ++k)
  19401. {
  19402. QPointF distPoint = intersections.at(i)-intersections.at(k);
  19403. double distSqr = distPoint.x()*distPoint.x()+distPoint.y()+distPoint.y();
  19404. if (distSqr > distSqrMax)
  19405. {
  19406. pv1 = intersections.at(i);
  19407. pv2 = intersections.at(k);
  19408. distSqrMax = distSqr;
  19409. }
  19410. }
  19411. }
  19412. intersections = QList<QPointF>() << pv1 << pv2;
  19413. } else if (intersections.size() != 2)
  19414. {
  19415. // one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment
  19416. return false;
  19417. }
  19418. // possibly re-sort points so optimized point segment has same direction as original segment:
  19419. double xDelta = keyPx-prevKeyPx;
  19420. double yDelta = valuePx-prevValuePx;
  19421. if (mKeyAxis->orientation() != Qt::Horizontal)
  19422. qSwap(xDelta, yDelta);
  19423. 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
  19424. intersections.move(0, 1);
  19425. crossA = intersections.at(0);
  19426. crossB = intersections.at(1);
  19427. return true;
  19428. }
  19429. /*! \internal
  19430. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19431. This method assumes that the \ref getTraverse test has returned true, so the segment definitely
  19432. traverses the visible region 5 when going from \a prevRegion to \a currentRegion.
  19433. In certain situations it is not sufficient to merely generate the entry and exit points of the
  19434. segment into/out of region 5, as \ref getTraverse provides. It may happen that a single segment, in
  19435. addition to traversing region 5, skips another region outside of region 5, which makes it
  19436. necessary to add an optimized corner point there (very similar to the job \ref
  19437. getOptimizedCornerPoints does for segments that are completely in outside regions and don't
  19438. traverse 5).
  19439. As an example, consider a segment going from region 1 to region 6, traversing the lower left
  19440. corner of region 5. In this configuration, the segment additionally crosses the border between
  19441. region 1 and 2 before entering region 5. This makes it necessary to add an additional point in
  19442. the top left corner, before adding the optimized traverse points. So in this case, the output
  19443. parameter \a beforeTraverse will contain the top left corner point, and \a afterTraverse will be
  19444. empty.
  19445. In some cases, such as when going from region 1 to 9, it may even be necessary to add additional
  19446. corner points before and after the traverse. Then both \a beforeTraverse and \a afterTraverse
  19447. return the respective corner points.
  19448. */
  19449. void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double keyMin, double valueMax, double keyMax, double valueMin, QVector<QPointF> &beforeTraverse, QVector<QPointF> &afterTraverse) const
  19450. {
  19451. switch (prevRegion)
  19452. {
  19453. case 1:
  19454. {
  19455. switch (currentRegion)
  19456. {
  19457. case 6: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; }
  19458. case 9: { beforeTraverse << coordsToPixels(keyMin, valueMax); afterTraverse << coordsToPixels(keyMax, valueMin); break; }
  19459. case 8: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; }
  19460. }
  19461. break;
  19462. }
  19463. case 2:
  19464. {
  19465. switch (currentRegion)
  19466. {
  19467. case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; }
  19468. case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; }
  19469. }
  19470. break;
  19471. }
  19472. case 3:
  19473. {
  19474. switch (currentRegion)
  19475. {
  19476. case 4: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; }
  19477. case 7: { beforeTraverse << coordsToPixels(keyMin, valueMin); afterTraverse << coordsToPixels(keyMax, valueMax); break; }
  19478. case 8: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; }
  19479. }
  19480. break;
  19481. }
  19482. case 4:
  19483. {
  19484. switch (currentRegion)
  19485. {
  19486. case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; }
  19487. case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; }
  19488. }
  19489. break;
  19490. }
  19491. case 5: { break; } // shouldn't happen because this method only handles full traverses
  19492. case 6:
  19493. {
  19494. switch (currentRegion)
  19495. {
  19496. case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; }
  19497. case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; }
  19498. }
  19499. break;
  19500. }
  19501. case 7:
  19502. {
  19503. switch (currentRegion)
  19504. {
  19505. case 2: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; }
  19506. case 3: { beforeTraverse << coordsToPixels(keyMax, valueMax); afterTraverse << coordsToPixels(keyMin, valueMin); break; }
  19507. case 6: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; }
  19508. }
  19509. break;
  19510. }
  19511. case 8:
  19512. {
  19513. switch (currentRegion)
  19514. {
  19515. case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; }
  19516. case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; }
  19517. }
  19518. break;
  19519. }
  19520. case 9:
  19521. {
  19522. switch (currentRegion)
  19523. {
  19524. case 2: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; }
  19525. case 1: { beforeTraverse << coordsToPixels(keyMax, valueMin); afterTraverse << coordsToPixels(keyMin, valueMax); break; }
  19526. case 4: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; }
  19527. }
  19528. break;
  19529. }
  19530. }
  19531. }
  19532. /*! \internal
  19533. Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a
  19534. pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in
  19535. \ref selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that
  19536. if the curve has a line representation, the returned distance may be smaller than the distance to
  19537. the \a closestData point, since the distance to the curve line is also taken into account.
  19538. If either the curve has no data or if the line style is \ref lsNone and the scatter style's shape
  19539. is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the curve), returns
  19540. -1.0.
  19541. */
  19542. double QCPCurve::pointDistance(const QPointF &pixelPoint, QCPCurveDataContainer::const_iterator &closestData) const
  19543. {
  19544. closestData = mDataContainer->constEnd();
  19545. if (mDataContainer->isEmpty())
  19546. return -1.0;
  19547. if (mLineStyle == lsNone && mScatterStyle.isNone())
  19548. return -1.0;
  19549. if (mDataContainer->size() == 1)
  19550. {
  19551. QPointF dataPoint = coordsToPixels(mDataContainer->constBegin()->key, mDataContainer->constBegin()->value);
  19552. closestData = mDataContainer->constBegin();
  19553. return QCPVector2D(dataPoint-pixelPoint).length();
  19554. }
  19555. // calculate minimum distances to curve data points and find closestData iterator:
  19556. double minDistSqr = std::numeric_limits<double>::max();
  19557. // iterate over found data points and then choose the one with the shortest distance to pos:
  19558. QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin();
  19559. QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd();
  19560. for (QCPCurveDataContainer::const_iterator it=begin; it!=end; ++it)
  19561. {
  19562. const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
  19563. if (currentDistSqr < minDistSqr)
  19564. {
  19565. minDistSqr = currentDistSqr;
  19566. closestData = it;
  19567. }
  19568. }
  19569. // calculate distance to line if there is one (if so, will probably be smaller than distance to closest data point):
  19570. if (mLineStyle != lsNone)
  19571. {
  19572. QVector<QPointF> lines;
  19573. 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
  19574. for (int i=0; i<lines.size()-1; ++i)
  19575. {
  19576. double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(lines.at(i), lines.at(i+1));
  19577. if (currentDistSqr < minDistSqr)
  19578. minDistSqr = currentDistSqr;
  19579. }
  19580. }
  19581. return qSqrt(minDistSqr);
  19582. }
  19583. /* end of 'src/plottables/plottable-curve.cpp' */
  19584. /* including file 'src/plottables/plottable-bars.cpp', size 43512 */
  19585. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  19586. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19587. //////////////////// QCPBarsGroup
  19588. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19589. /*! \class QCPBarsGroup
  19590. \brief Groups multiple QCPBars together so they appear side by side
  19591. \image html QCPBarsGroup.png
  19592. When showing multiple QCPBars in one plot which have bars at identical keys, it may be desirable
  19593. to have them appearing next to each other at each key. This is what adding the respective QCPBars
  19594. plottables to a QCPBarsGroup achieves. (An alternative approach is to stack them on top of each
  19595. other, see \ref QCPBars::moveAbove.)
  19596. \section qcpbarsgroup-usage Usage
  19597. To add a QCPBars plottable to the group, create a new group and then add the respective bars
  19598. intances:
  19599. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbarsgroup-creation
  19600. Alternatively to appending to the group like shown above, you can also set the group on the
  19601. QCPBars plottable via \ref QCPBars::setBarsGroup.
  19602. The spacing between the bars can be configured via \ref setSpacingType and \ref setSpacing. The
  19603. bars in this group appear in the plot in the order they were appended. To insert a bars plottable
  19604. at a certain index position, or to reposition a bars plottable which is already in the group, use
  19605. \ref insert.
  19606. To remove specific bars from the group, use either \ref remove or call \ref
  19607. QCPBars::setBarsGroup "QCPBars::setBarsGroup(0)" on the respective bars plottable.
  19608. To clear the entire group, call \ref clear, or simply delete the group.
  19609. \section qcpbarsgroup-example Example
  19610. The image above is generated with the following code:
  19611. \snippet documentation/doc-image-generator/mainwindow.cpp qcpbarsgroup-example
  19612. */
  19613. /* start of documentation of inline functions */
  19614. /*! \fn QList<QCPBars*> QCPBarsGroup::bars() const
  19615. Returns all bars currently in this group.
  19616. \see bars(int index)
  19617. */
  19618. /*! \fn int QCPBarsGroup::size() const
  19619. Returns the number of QCPBars plottables that are part of this group.
  19620. */
  19621. /*! \fn bool QCPBarsGroup::isEmpty() const
  19622. Returns whether this bars group is empty.
  19623. \see size
  19624. */
  19625. /*! \fn bool QCPBarsGroup::contains(QCPBars *bars)
  19626. Returns whether the specified \a bars plottable is part of this group.
  19627. */
  19628. /* end of documentation of inline functions */
  19629. /*!
  19630. Constructs a new bars group for the specified QCustomPlot instance.
  19631. */
  19632. QCPBarsGroup::QCPBarsGroup(QCustomPlot *parentPlot) :
  19633. QObject(parentPlot),
  19634. mParentPlot(parentPlot),
  19635. mSpacingType(stAbsolute),
  19636. mSpacing(4)
  19637. {
  19638. }
  19639. QCPBarsGroup::~QCPBarsGroup()
  19640. {
  19641. clear();
  19642. }
  19643. /*!
  19644. Sets how the spacing between adjacent bars is interpreted. See \ref SpacingType.
  19645. The actual spacing can then be specified with \ref setSpacing.
  19646. \see setSpacing
  19647. */
  19648. void QCPBarsGroup::setSpacingType(SpacingType spacingType)
  19649. {
  19650. mSpacingType = spacingType;
  19651. }
  19652. /*!
  19653. Sets the spacing between adjacent bars. What the number passed as \a spacing actually means, is
  19654. defined by the current \ref SpacingType, which can be set with \ref setSpacingType.
  19655. \see setSpacingType
  19656. */
  19657. void QCPBarsGroup::setSpacing(double spacing)
  19658. {
  19659. mSpacing = spacing;
  19660. }
  19661. /*!
  19662. Returns the QCPBars instance with the specified \a index in this group. If no such QCPBars
  19663. exists, returns 0.
  19664. \see bars(), size
  19665. */
  19666. QCPBars *QCPBarsGroup::bars(int index) const
  19667. {
  19668. if (index >= 0 && index < mBars.size())
  19669. {
  19670. return mBars.at(index);
  19671. } else
  19672. {
  19673. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  19674. return 0;
  19675. }
  19676. }
  19677. /*!
  19678. Removes all QCPBars plottables from this group.
  19679. \see isEmpty
  19680. */
  19681. void QCPBarsGroup::clear()
  19682. {
  19683. foreach (QCPBars *bars, mBars) // since foreach takes a copy, removing bars in the loop is okay
  19684. bars->setBarsGroup(0); // removes itself via removeBars
  19685. }
  19686. /*!
  19687. Adds the specified \a bars plottable to this group. Alternatively, you can also use \ref
  19688. QCPBars::setBarsGroup on the \a bars instance.
  19689. \see insert, remove
  19690. */
  19691. void QCPBarsGroup::append(QCPBars *bars)
  19692. {
  19693. if (!bars)
  19694. {
  19695. qDebug() << Q_FUNC_INFO << "bars is 0";
  19696. return;
  19697. }
  19698. if (!mBars.contains(bars))
  19699. bars->setBarsGroup(this);
  19700. else
  19701. qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast<quintptr>(bars);
  19702. }
  19703. /*!
  19704. Inserts the specified \a bars plottable into this group at the specified index position \a i.
  19705. This gives you full control over the ordering of the bars.
  19706. \a bars may already be part of this group. In that case, \a bars is just moved to the new index
  19707. position.
  19708. \see append, remove
  19709. */
  19710. void QCPBarsGroup::insert(int i, QCPBars *bars)
  19711. {
  19712. if (!bars)
  19713. {
  19714. qDebug() << Q_FUNC_INFO << "bars is 0";
  19715. return;
  19716. }
  19717. // first append to bars list normally:
  19718. if (!mBars.contains(bars))
  19719. bars->setBarsGroup(this);
  19720. // then move to according position:
  19721. mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size()-1));
  19722. }
  19723. /*!
  19724. Removes the specified \a bars plottable from this group.
  19725. \see contains, clear
  19726. */
  19727. void QCPBarsGroup::remove(QCPBars *bars)
  19728. {
  19729. if (!bars)
  19730. {
  19731. qDebug() << Q_FUNC_INFO << "bars is 0";
  19732. return;
  19733. }
  19734. if (mBars.contains(bars))
  19735. bars->setBarsGroup(0);
  19736. else
  19737. qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast<quintptr>(bars);
  19738. }
  19739. /*! \internal
  19740. Adds the specified \a bars to the internal mBars list of bars. This method does not change the
  19741. barsGroup property on \a bars.
  19742. \see unregisterBars
  19743. */
  19744. void QCPBarsGroup::registerBars(QCPBars *bars)
  19745. {
  19746. if (!mBars.contains(bars))
  19747. mBars.append(bars);
  19748. }
  19749. /*! \internal
  19750. Removes the specified \a bars from the internal mBars list of bars. This method does not change
  19751. the barsGroup property on \a bars.
  19752. \see registerBars
  19753. */
  19754. void QCPBarsGroup::unregisterBars(QCPBars *bars)
  19755. {
  19756. mBars.removeOne(bars);
  19757. }
  19758. /*! \internal
  19759. Returns the pixel offset in the key dimension the specified \a bars plottable should have at the
  19760. given key coordinate \a keyCoord. The offset is relative to the pixel position of the key
  19761. coordinate \a keyCoord.
  19762. */
  19763. double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord)
  19764. {
  19765. // find list of all base bars in case some mBars are stacked:
  19766. QList<const QCPBars*> baseBars;
  19767. foreach (const QCPBars *b, mBars)
  19768. {
  19769. while (b->barBelow())
  19770. b = b->barBelow();
  19771. if (!baseBars.contains(b))
  19772. baseBars.append(b);
  19773. }
  19774. // find base bar this "bars" is stacked on:
  19775. const QCPBars *thisBase = bars;
  19776. while (thisBase->barBelow())
  19777. thisBase = thisBase->barBelow();
  19778. // determine key pixel offset of this base bars considering all other base bars in this barsgroup:
  19779. double result = 0;
  19780. int index = baseBars.indexOf(thisBase);
  19781. if (index >= 0)
  19782. {
  19783. if (baseBars.size() % 2 == 1 && index == (baseBars.size()-1)/2) // is center bar (int division on purpose)
  19784. {
  19785. return result;
  19786. } else
  19787. {
  19788. double lowerPixelWidth, upperPixelWidth;
  19789. int startIndex;
  19790. int dir = (index <= (baseBars.size()-1)/2) ? -1 : 1; // if bar is to lower keys of center, dir is negative
  19791. if (baseBars.size() % 2 == 0) // even number of bars
  19792. {
  19793. startIndex = baseBars.size()/2 + (dir < 0 ? -1 : 0);
  19794. result += getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing
  19795. } else // uneven number of bars
  19796. {
  19797. startIndex = (baseBars.size()-1)/2+dir;
  19798. baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  19799. result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar
  19800. result += getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing
  19801. }
  19802. for (int i = startIndex; i != index; i += dir) // add widths and spacings of bars in between center and our bars
  19803. {
  19804. baseBars.at(i)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  19805. result += qAbs(upperPixelWidth-lowerPixelWidth);
  19806. result += getPixelSpacing(baseBars.at(i), keyCoord);
  19807. }
  19808. // finally half of our bars width:
  19809. baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  19810. result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5;
  19811. // correct sign of result depending on orientation and direction of key axis:
  19812. result *= dir*thisBase->keyAxis()->pixelOrientation();
  19813. }
  19814. }
  19815. return result;
  19816. }
  19817. /*! \internal
  19818. Returns the spacing in pixels which is between this \a bars and the following one, both at the
  19819. key coordinate \a keyCoord.
  19820. \note Typically the returned value doesn't depend on \a bars or \a keyCoord. \a bars is only
  19821. needed to get access to the key axis transformation and axis rect for the modes \ref
  19822. stAxisRectRatio and \ref stPlotCoords. The \a keyCoord is only relevant for spacings given in
  19823. \ref stPlotCoords on a logarithmic axis.
  19824. */
  19825. double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord)
  19826. {
  19827. switch (mSpacingType)
  19828. {
  19829. case stAbsolute:
  19830. {
  19831. return mSpacing;
  19832. }
  19833. case stAxisRectRatio:
  19834. {
  19835. if (bars->keyAxis()->orientation() == Qt::Horizontal)
  19836. return bars->keyAxis()->axisRect()->width()*mSpacing;
  19837. else
  19838. return bars->keyAxis()->axisRect()->height()*mSpacing;
  19839. }
  19840. case stPlotCoords:
  19841. {
  19842. double keyPixel = bars->keyAxis()->coordToPixel(keyCoord);
  19843. return qAbs(bars->keyAxis()->coordToPixel(keyCoord+mSpacing)-keyPixel);
  19844. }
  19845. }
  19846. return 0;
  19847. }
  19848. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19849. //////////////////// QCPBarsData
  19850. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19851. /*! \class QCPBarsData
  19852. \brief Holds the data of one single data point (one bar) for QCPBars.
  19853. The stored data is:
  19854. \li \a key: coordinate on the key axis of this bar (this is the \a mainKey and the \a sortKey)
  19855. \li \a value: height coordinate on the value axis of this bar (this is the \a mainValue)
  19856. The container for storing multiple data points is \ref QCPBarsDataContainer. It is a typedef for
  19857. \ref QCPDataContainer with \ref QCPBarsData as the DataType template parameter. See the
  19858. documentation there for an explanation regarding the data type's generic methods.
  19859. \see QCPBarsDataContainer
  19860. */
  19861. /* start documentation of inline functions */
  19862. /*! \fn double QCPBarsData::sortKey() const
  19863. Returns the \a key member of this data point.
  19864. For a general explanation of what this method is good for in the context of the data container,
  19865. see the documentation of \ref QCPDataContainer.
  19866. */
  19867. /*! \fn static QCPBarsData QCPBarsData::fromSortKey(double sortKey)
  19868. Returns a data point with the specified \a sortKey. All other members are set to zero.
  19869. For a general explanation of what this method is good for in the context of the data container,
  19870. see the documentation of \ref QCPDataContainer.
  19871. */
  19872. /*! \fn static static bool QCPBarsData::sortKeyIsMainKey()
  19873. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  19874. this method returns true.
  19875. For a general explanation of what this method is good for in the context of the data container,
  19876. see the documentation of \ref QCPDataContainer.
  19877. */
  19878. /*! \fn double QCPBarsData::mainKey() const
  19879. Returns the \a key member of this data point.
  19880. For a general explanation of what this method is good for in the context of the data container,
  19881. see the documentation of \ref QCPDataContainer.
  19882. */
  19883. /*! \fn double QCPBarsData::mainValue() const
  19884. Returns the \a value member of this data point.
  19885. For a general explanation of what this method is good for in the context of the data container,
  19886. see the documentation of \ref QCPDataContainer.
  19887. */
  19888. /*! \fn QCPRange QCPBarsData::valueRange() const
  19889. Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
  19890. For a general explanation of what this method is good for in the context of the data container,
  19891. see the documentation of \ref QCPDataContainer.
  19892. */
  19893. /* end documentation of inline functions */
  19894. /*!
  19895. Constructs a bar data point with key and value set to zero.
  19896. */
  19897. QCPBarsData::QCPBarsData() :
  19898. key(0),
  19899. value(0)
  19900. {
  19901. }
  19902. /*!
  19903. Constructs a bar data point with the specified \a key and \a value.
  19904. */
  19905. QCPBarsData::QCPBarsData(double key, double value) :
  19906. key(key),
  19907. value(value)
  19908. {
  19909. }
  19910. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19911. //////////////////// QCPBars
  19912. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19913. /*! \class QCPBars
  19914. \brief A plottable representing a bar chart in a plot.
  19915. \image html QCPBars.png
  19916. To plot data, assign it with the \ref setData or \ref addData functions.
  19917. \section qcpbars-appearance Changing the appearance
  19918. The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush).
  19919. The width of the individual bars can be controlled with \ref setWidthType and \ref setWidth.
  19920. Bar charts are stackable. This means, two QCPBars plottables can be placed on top of each other
  19921. (see \ref QCPBars::moveAbove). So when two bars are at the same key position, they will appear
  19922. stacked.
  19923. If you would like to group multiple QCPBars plottables together so they appear side by side as
  19924. shown below, use QCPBarsGroup.
  19925. \image html QCPBarsGroup.png
  19926. \section qcpbars-usage Usage
  19927. Like all data representing objects in QCustomPlot, the QCPBars is a plottable
  19928. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  19929. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  19930. Usually, you first create an instance:
  19931. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-1
  19932. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  19933. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  19934. The newly created plottable can be modified, e.g.:
  19935. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-2
  19936. */
  19937. /* start of documentation of inline functions */
  19938. /*! \fn QSharedPointer<QCPBarsDataContainer> QCPBars::data() const
  19939. Returns a shared pointer to the internal data storage of type \ref QCPBarsDataContainer. You may
  19940. use it to directly manipulate the data, which may be more convenient and faster than using the
  19941. regular \ref setData or \ref addData methods.
  19942. */
  19943. /*! \fn QCPBars *QCPBars::barBelow() const
  19944. Returns the bars plottable that is directly below this bars plottable.
  19945. If there is no such plottable, returns 0.
  19946. \see barAbove, moveBelow, moveAbove
  19947. */
  19948. /*! \fn QCPBars *QCPBars::barAbove() const
  19949. Returns the bars plottable that is directly above this bars plottable.
  19950. If there is no such plottable, returns 0.
  19951. \see barBelow, moveBelow, moveAbove
  19952. */
  19953. /* end of documentation of inline functions */
  19954. /*!
  19955. Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  19956. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  19957. the same orientation. If either of these restrictions is violated, a corresponding message is
  19958. printed to the debug output (qDebug), the construction is not aborted, though.
  19959. The created QCPBars is automatically registered with the QCustomPlot instance inferred from \a
  19960. keyAxis. This QCustomPlot instance takes ownership of the QCPBars, so do not delete it manually
  19961. but use QCustomPlot::removePlottable() instead.
  19962. */
  19963. QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  19964. QCPAbstractPlottable1D<QCPBarsData>(keyAxis, valueAxis),
  19965. mWidth(0.75),
  19966. mWidthType(wtPlotCoords),
  19967. mBarsGroup(0),
  19968. mBaseValue(0),
  19969. mStackingGap(0)
  19970. {
  19971. // modify inherited properties from abstract plottable:
  19972. mPen.setColor(Qt::blue);
  19973. mPen.setStyle(Qt::SolidLine);
  19974. mBrush.setColor(QColor(40, 50, 255, 30));
  19975. mBrush.setStyle(Qt::SolidPattern);
  19976. mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255)));
  19977. }
  19978. QCPBars::~QCPBars()
  19979. {
  19980. setBarsGroup(0);
  19981. if (mBarBelow || mBarAbove)
  19982. connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking
  19983. }
  19984. /*! \overload
  19985. Replaces the current data container with the provided \a data container.
  19986. Since a QSharedPointer is used, multiple QCPBars may share the same data container safely.
  19987. Modifying the data in the container will then affect all bars that share the container. Sharing
  19988. can be achieved by simply exchanging the data containers wrapped in shared pointers:
  19989. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-datasharing-1
  19990. If you do not wish to share containers, but create a copy from an existing container, rather use
  19991. the \ref QCPDataContainer<DataType>::set method on the bar's data container directly:
  19992. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-datasharing-2
  19993. \see addData
  19994. */
  19995. void QCPBars::setData(QSharedPointer<QCPBarsDataContainer> data)
  19996. {
  19997. mDataContainer = data;
  19998. }
  19999. /*! \overload
  20000. Replaces the current data with the provided points in \a keys and \a values. The provided
  20001. vectors should have equal length. Else, the number of added points will be the size of the
  20002. smallest vector.
  20003. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  20004. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  20005. \see addData
  20006. */
  20007. void QCPBars::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  20008. {
  20009. mDataContainer->clear();
  20010. addData(keys, values, alreadySorted);
  20011. }
  20012. /*!
  20013. Sets the width of the bars.
  20014. How the number passed as \a width is interpreted (e.g. screen pixels, plot coordinates,...),
  20015. depends on the currently set width type, see \ref setWidthType and \ref WidthType.
  20016. */
  20017. void QCPBars::setWidth(double width)
  20018. {
  20019. mWidth = width;
  20020. }
  20021. /*!
  20022. Sets how the width of the bars is defined. See the documentation of \ref WidthType for an
  20023. explanation of the possible values for \a widthType.
  20024. The default value is \ref wtPlotCoords.
  20025. \see setWidth
  20026. */
  20027. void QCPBars::setWidthType(QCPBars::WidthType widthType)
  20028. {
  20029. mWidthType = widthType;
  20030. }
  20031. /*!
  20032. Sets to which QCPBarsGroup this QCPBars instance belongs to. Alternatively, you can also use \ref
  20033. QCPBarsGroup::append.
  20034. To remove this QCPBars from any group, set \a barsGroup to 0.
  20035. */
  20036. void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup)
  20037. {
  20038. // deregister at old group:
  20039. if (mBarsGroup)
  20040. mBarsGroup->unregisterBars(this);
  20041. mBarsGroup = barsGroup;
  20042. // register at new group:
  20043. if (mBarsGroup)
  20044. mBarsGroup->registerBars(this);
  20045. }
  20046. /*!
  20047. Sets the base value of this bars plottable.
  20048. The base value defines where on the value coordinate the bars start. How far the bars extend from
  20049. the base value is given by their individual value data. For example, if the base value is set to
  20050. 1, a bar with data value 2 will have its lowest point at value coordinate 1 and highest point at
  20051. 3.
  20052. For stacked bars, only the base value of the bottom-most QCPBars has meaning.
  20053. The default base value is 0.
  20054. */
  20055. void QCPBars::setBaseValue(double baseValue)
  20056. {
  20057. mBaseValue = baseValue;
  20058. }
  20059. /*!
  20060. If this bars plottable is stacked on top of another bars plottable (\ref moveAbove), this method
  20061. allows specifying a distance in \a pixels, by which the drawn bar rectangles will be separated by
  20062. the bars below it.
  20063. */
  20064. void QCPBars::setStackingGap(double pixels)
  20065. {
  20066. mStackingGap = pixels;
  20067. }
  20068. /*! \overload
  20069. Adds the provided points in \a keys and \a values to the current data. The provided vectors
  20070. should have equal length. Else, the number of added points will be the size of the smallest
  20071. vector.
  20072. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  20073. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  20074. Alternatively, you can also access and modify the data directly via the \ref data method, which
  20075. returns a pointer to the internal data container.
  20076. */
  20077. void QCPBars::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  20078. {
  20079. if (keys.size() != values.size())
  20080. qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
  20081. const int n = qMin(keys.size(), values.size());
  20082. QVector<QCPBarsData> tempData(n);
  20083. QVector<QCPBarsData>::iterator it = tempData.begin();
  20084. const QVector<QCPBarsData>::iterator itEnd = tempData.end();
  20085. int i = 0;
  20086. while (it != itEnd)
  20087. {
  20088. it->key = keys[i];
  20089. it->value = values[i];
  20090. ++it;
  20091. ++i;
  20092. }
  20093. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  20094. }
  20095. /*! \overload
  20096. Adds the provided data point as \a key and \a value to the current data.
  20097. Alternatively, you can also access and modify the data directly via the \ref data method, which
  20098. returns a pointer to the internal data container.
  20099. */
  20100. void QCPBars::addData(double key, double value)
  20101. {
  20102. mDataContainer->add(QCPBarsData(key, value));
  20103. }
  20104. /*!
  20105. Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear
  20106. below the bars of \a bars. The move target \a bars must use the same key and value axis as this
  20107. plottable.
  20108. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
  20109. has a bars object below itself, this bars object is inserted between the two. If this bars object
  20110. is already between two other bars, the two other bars will be stacked on top of each other after
  20111. the operation.
  20112. To remove this bars plottable from any stacking, set \a bars to 0.
  20113. \see moveBelow, barAbove, barBelow
  20114. */
  20115. void QCPBars::moveBelow(QCPBars *bars)
  20116. {
  20117. if (bars == this) return;
  20118. if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
  20119. {
  20120. qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
  20121. return;
  20122. }
  20123. // remove from stacking:
  20124. connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
  20125. // if new bar given, insert this bar below it:
  20126. if (bars)
  20127. {
  20128. if (bars->mBarBelow)
  20129. connectBars(bars->mBarBelow.data(), this);
  20130. connectBars(this, bars);
  20131. }
  20132. }
  20133. /*!
  20134. Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear
  20135. above the bars of \a bars. The move target \a bars must use the same key and value axis as this
  20136. plottable.
  20137. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
  20138. has a bars object above itself, this bars object is inserted between the two. If this bars object
  20139. is already between two other bars, the two other bars will be stacked on top of each other after
  20140. the operation.
  20141. To remove this bars plottable from any stacking, set \a bars to 0.
  20142. \see moveBelow, barBelow, barAbove
  20143. */
  20144. void QCPBars::moveAbove(QCPBars *bars)
  20145. {
  20146. if (bars == this) return;
  20147. if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
  20148. {
  20149. qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
  20150. return;
  20151. }
  20152. // remove from stacking:
  20153. connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
  20154. // if new bar given, insert this bar above it:
  20155. if (bars)
  20156. {
  20157. if (bars->mBarAbove)
  20158. connectBars(this, bars->mBarAbove.data());
  20159. connectBars(bars, this);
  20160. }
  20161. }
  20162. /*!
  20163. \copydoc QCPPlottableInterface1D::selectTestRect
  20164. */
  20165. QCPDataSelection QCPBars::selectTestRect(const QRectF &rect, bool onlySelectable) const
  20166. {
  20167. QCPDataSelection result;
  20168. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  20169. return result;
  20170. if (!mKeyAxis || !mValueAxis)
  20171. return result;
  20172. QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  20173. getVisibleDataBounds(visibleBegin, visibleEnd);
  20174. for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  20175. {
  20176. if (rect.intersects(getBarRect(it->key, it->value)))
  20177. result.addDataRange(QCPDataRange(it-mDataContainer->constBegin(), it-mDataContainer->constBegin()+1), false);
  20178. }
  20179. result.simplify();
  20180. return result;
  20181. }
  20182. /* inherits documentation from base class */
  20183. double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  20184. {
  20185. Q_UNUSED(details)
  20186. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  20187. return -1;
  20188. if (!mKeyAxis || !mValueAxis)
  20189. return -1;
  20190. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
  20191. {
  20192. // get visible data range:
  20193. QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  20194. getVisibleDataBounds(visibleBegin, visibleEnd);
  20195. for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  20196. {
  20197. if (getBarRect(it->key, it->value).contains(pos))
  20198. {
  20199. if (details)
  20200. {
  20201. int pointIndex = it-mDataContainer->constBegin();
  20202. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  20203. }
  20204. return mParentPlot->selectionTolerance()*0.99;
  20205. }
  20206. }
  20207. }
  20208. return -1;
  20209. }
  20210. /* inherits documentation from base class */
  20211. QCPRange QCPBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  20212. {
  20213. /* Note: If this QCPBars uses absolute pixels as width (or is in a QCPBarsGroup with spacing in
  20214. absolute pixels), using this method to adapt the key axis range to fit the bars into the
  20215. currently visible axis range will not work perfectly. Because in the moment the axis range is
  20216. changed to the new range, the fixed pixel widths/spacings will represent different coordinate
  20217. spans than before, which in turn would require a different key range to perfectly fit, and so on.
  20218. The only solution would be to iteratively approach the perfect fitting axis range, but the
  20219. mismatch isn't large enough in most applications, to warrant this here. If a user does need a
  20220. better fit, he should call the corresponding axis rescale multiple times in a row.
  20221. */
  20222. QCPRange range;
  20223. range = mDataContainer->keyRange(foundRange, inSignDomain);
  20224. // determine exact range of bars by including bar width and barsgroup offset:
  20225. if (foundRange && mKeyAxis)
  20226. {
  20227. double lowerPixelWidth, upperPixelWidth, keyPixel;
  20228. // lower range bound:
  20229. getPixelWidth(range.lower, lowerPixelWidth, upperPixelWidth);
  20230. keyPixel = mKeyAxis.data()->coordToPixel(range.lower) + lowerPixelWidth;
  20231. if (mBarsGroup)
  20232. keyPixel += mBarsGroup->keyPixelOffset(this, range.lower);
  20233. const double lowerCorrected = mKeyAxis.data()->pixelToCoord(keyPixel);
  20234. if (!qIsNaN(lowerCorrected) && qIsFinite(lowerCorrected) && range.lower > lowerCorrected)
  20235. range.lower = lowerCorrected;
  20236. // upper range bound:
  20237. getPixelWidth(range.upper, lowerPixelWidth, upperPixelWidth);
  20238. keyPixel = mKeyAxis.data()->coordToPixel(range.upper) + upperPixelWidth;
  20239. if (mBarsGroup)
  20240. keyPixel += mBarsGroup->keyPixelOffset(this, range.upper);
  20241. const double upperCorrected = mKeyAxis.data()->pixelToCoord(keyPixel);
  20242. if (!qIsNaN(upperCorrected) && qIsFinite(upperCorrected) && range.upper < upperCorrected)
  20243. range.upper = upperCorrected;
  20244. }
  20245. return range;
  20246. }
  20247. /* inherits documentation from base class */
  20248. QCPRange QCPBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  20249. {
  20250. // Note: can't simply use mDataContainer->valueRange here because we need to
  20251. // take into account bar base value and possible stacking of multiple bars
  20252. QCPRange range;
  20253. range.lower = mBaseValue;
  20254. range.upper = mBaseValue;
  20255. bool haveLower = true; // set to true, because baseValue should always be visible in bar charts
  20256. bool haveUpper = true; // set to true, because baseValue should always be visible in bar charts
  20257. QCPBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin();
  20258. QCPBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd();
  20259. if (inKeyRange != QCPRange())
  20260. {
  20261. itBegin = mDataContainer->findBegin(inKeyRange.lower);
  20262. itEnd = mDataContainer->findEnd(inKeyRange.upper);
  20263. }
  20264. for (QCPBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it)
  20265. {
  20266. const double current = it->value + getStackedBaseValue(it->key, it->value >= 0);
  20267. if (qIsNaN(current)) continue;
  20268. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  20269. {
  20270. if (current < range.lower || !haveLower)
  20271. {
  20272. range.lower = current;
  20273. haveLower = true;
  20274. }
  20275. if (current > range.upper || !haveUpper)
  20276. {
  20277. range.upper = current;
  20278. haveUpper = true;
  20279. }
  20280. }
  20281. }
  20282. foundRange = true; // return true because bar charts always have the 0-line visible
  20283. return range;
  20284. }
  20285. /* inherits documentation from base class */
  20286. QPointF QCPBars::dataPixelPosition(int index) const
  20287. {
  20288. if (index >= 0 && index < mDataContainer->size())
  20289. {
  20290. QCPAxis *keyAxis = mKeyAxis.data();
  20291. QCPAxis *valueAxis = mValueAxis.data();
  20292. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
  20293. const QCPDataContainer<QCPBarsData>::const_iterator it = mDataContainer->constBegin()+index;
  20294. const double valuePixel = valueAxis->coordToPixel(getStackedBaseValue(it->key, it->value >= 0) + it->value);
  20295. const double keyPixel = keyAxis->coordToPixel(it->key) + (mBarsGroup ? mBarsGroup->keyPixelOffset(this, it->key) : 0);
  20296. if (keyAxis->orientation() == Qt::Horizontal)
  20297. return QPointF(keyPixel, valuePixel);
  20298. else
  20299. return QPointF(valuePixel, keyPixel);
  20300. } else
  20301. {
  20302. qDebug() << Q_FUNC_INFO << "Index out of bounds" << index;
  20303. return QPointF();
  20304. }
  20305. }
  20306. /* inherits documentation from base class */
  20307. void QCPBars::draw(QCPPainter *painter)
  20308. {
  20309. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  20310. if (mDataContainer->isEmpty()) return;
  20311. QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  20312. getVisibleDataBounds(visibleBegin, visibleEnd);
  20313. // loop over and draw segments of unselected/selected data:
  20314. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  20315. getDataSegments(selectedSegments, unselectedSegments);
  20316. allSegments << unselectedSegments << selectedSegments;
  20317. for (int i=0; i<allSegments.size(); ++i)
  20318. {
  20319. bool isSelectedSegment = i >= unselectedSegments.size();
  20320. QCPBarsDataContainer::const_iterator begin = visibleBegin;
  20321. QCPBarsDataContainer::const_iterator end = visibleEnd;
  20322. mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
  20323. if (begin == end)
  20324. continue;
  20325. for (QCPBarsDataContainer::const_iterator it=begin; it!=end; ++it)
  20326. {
  20327. // check data validity if flag set:
  20328. #ifdef QCUSTOMPLOT_CHECK_DATA
  20329. if (QCP::isInvalidData(it->key, it->value))
  20330. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range invalid." << "Plottable name:" << name();
  20331. #endif
  20332. // draw bar:
  20333. if (isSelectedSegment && mSelectionDecorator)
  20334. {
  20335. mSelectionDecorator->applyBrush(painter);
  20336. mSelectionDecorator->applyPen(painter);
  20337. } else
  20338. {
  20339. painter->setBrush(mBrush);
  20340. painter->setPen(mPen);
  20341. }
  20342. applyDefaultAntialiasingHint(painter);
  20343. painter->drawPolygon(getBarRect(it->key, it->value));
  20344. }
  20345. }
  20346. // draw other selection decoration that isn't just line/scatter pens and brushes:
  20347. if (mSelectionDecorator)
  20348. mSelectionDecorator->drawDecoration(painter, selection());
  20349. }
  20350. /* inherits documentation from base class */
  20351. void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  20352. {
  20353. // draw filled rect:
  20354. applyDefaultAntialiasingHint(painter);
  20355. painter->setBrush(mBrush);
  20356. painter->setPen(mPen);
  20357. QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
  20358. r.moveCenter(rect.center());
  20359. painter->drawRect(r);
  20360. }
  20361. /*! \internal
  20362. called by \ref draw to determine which data (key) range is visible at the current key axis range
  20363. setting, so only that needs to be processed. It also takes into account the bar width.
  20364. \a begin returns an iterator to the lowest data point that needs to be taken into account when
  20365. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  20366. lower may still be just outside the visible range.
  20367. \a end returns an iterator one higher than the highest visible data point. Same as before, \a end
  20368. may also lie just outside of the visible range.
  20369. if the plottable contains no data, both \a begin and \a end point to constEnd.
  20370. */
  20371. void QCPBars::getVisibleDataBounds(QCPBarsDataContainer::const_iterator &begin, QCPBarsDataContainer::const_iterator &end) const
  20372. {
  20373. if (!mKeyAxis)
  20374. {
  20375. qDebug() << Q_FUNC_INFO << "invalid key axis";
  20376. begin = mDataContainer->constEnd();
  20377. end = mDataContainer->constEnd();
  20378. return;
  20379. }
  20380. if (mDataContainer->isEmpty())
  20381. {
  20382. begin = mDataContainer->constEnd();
  20383. end = mDataContainer->constEnd();
  20384. return;
  20385. }
  20386. // get visible data range as QMap iterators
  20387. begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower);
  20388. end = mDataContainer->findEnd(mKeyAxis.data()->range().upper);
  20389. double lowerPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().lower);
  20390. double upperPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().upper);
  20391. bool isVisible = false;
  20392. // walk left from begin to find lower bar that actually is completely outside visible pixel range:
  20393. QCPBarsDataContainer::const_iterator it = begin;
  20394. while (it != mDataContainer->constBegin())
  20395. {
  20396. --it;
  20397. const QRectF barRect = getBarRect(it->key, it->value);
  20398. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  20399. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.left() <= lowerPixelBound));
  20400. else // keyaxis is vertical
  20401. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.bottom() >= lowerPixelBound));
  20402. if (isVisible)
  20403. begin = it;
  20404. else
  20405. break;
  20406. }
  20407. // walk right from ubound to find upper bar that actually is completely outside visible pixel range:
  20408. it = end;
  20409. while (it != mDataContainer->constEnd())
  20410. {
  20411. const QRectF barRect = getBarRect(it->key, it->value);
  20412. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  20413. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.right() >= upperPixelBound));
  20414. else // keyaxis is vertical
  20415. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.top() <= upperPixelBound));
  20416. if (isVisible)
  20417. end = it+1;
  20418. else
  20419. break;
  20420. ++it;
  20421. }
  20422. }
  20423. /*! \internal
  20424. Returns the rect in pixel coordinates of a single bar with the specified \a key and \a value. The
  20425. rect is shifted according to the bar stacking (see \ref moveAbove) and base value (see \ref
  20426. setBaseValue), and to have non-overlapping border lines with the bars stacked below.
  20427. */
  20428. QRectF QCPBars::getBarRect(double key, double value) const
  20429. {
  20430. QCPAxis *keyAxis = mKeyAxis.data();
  20431. QCPAxis *valueAxis = mValueAxis.data();
  20432. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QRectF(); }
  20433. double lowerPixelWidth, upperPixelWidth;
  20434. getPixelWidth(key, lowerPixelWidth, upperPixelWidth);
  20435. double base = getStackedBaseValue(key, value >= 0);
  20436. double basePixel = valueAxis->coordToPixel(base);
  20437. double valuePixel = valueAxis->coordToPixel(base+value);
  20438. double keyPixel = keyAxis->coordToPixel(key);
  20439. if (mBarsGroup)
  20440. keyPixel += mBarsGroup->keyPixelOffset(this, key);
  20441. double bottomOffset = (mBarBelow && mPen != Qt::NoPen ? 1 : 0)*(mPen.isCosmetic() ? 1 : mPen.widthF());
  20442. bottomOffset += mBarBelow ? mStackingGap : 0;
  20443. bottomOffset *= (value<0 ? -1 : 1)*valueAxis->pixelOrientation();
  20444. if (qAbs(valuePixel-basePixel) <= qAbs(bottomOffset))
  20445. bottomOffset = valuePixel-basePixel;
  20446. if (keyAxis->orientation() == Qt::Horizontal)
  20447. {
  20448. return QRectF(QPointF(keyPixel+lowerPixelWidth, valuePixel), QPointF(keyPixel+upperPixelWidth, basePixel+bottomOffset)).normalized();
  20449. } else
  20450. {
  20451. return QRectF(QPointF(basePixel+bottomOffset, keyPixel+lowerPixelWidth), QPointF(valuePixel, keyPixel+upperPixelWidth)).normalized();
  20452. }
  20453. }
  20454. /*! \internal
  20455. This function is used to determine the width of the bar at coordinate \a key, according to the
  20456. specified width (\ref setWidth) and width type (\ref setWidthType).
  20457. The output parameters \a lower and \a upper return the number of pixels the bar extends to lower
  20458. and higher keys, relative to the \a key coordinate (so with a non-reversed horizontal axis, \a
  20459. lower is negative and \a upper positive).
  20460. */
  20461. void QCPBars::getPixelWidth(double key, double &lower, double &upper) const
  20462. {
  20463. lower = 0;
  20464. upper = 0;
  20465. switch (mWidthType)
  20466. {
  20467. case wtAbsolute:
  20468. {
  20469. upper = mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  20470. lower = -upper;
  20471. break;
  20472. }
  20473. case wtAxisRectRatio:
  20474. {
  20475. if (mKeyAxis && mKeyAxis.data()->axisRect())
  20476. {
  20477. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  20478. upper = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  20479. else
  20480. upper = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  20481. lower = -upper;
  20482. } else
  20483. qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined";
  20484. break;
  20485. }
  20486. case wtPlotCoords:
  20487. {
  20488. if (mKeyAxis)
  20489. {
  20490. double keyPixel = mKeyAxis.data()->coordToPixel(key);
  20491. upper = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel;
  20492. lower = mKeyAxis.data()->coordToPixel(key-mWidth*0.5)-keyPixel;
  20493. // no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by
  20494. // coordinate transform which includes range direction
  20495. } else
  20496. qDebug() << Q_FUNC_INFO << "No key axis defined";
  20497. break;
  20498. }
  20499. }
  20500. }
  20501. /*! \internal
  20502. This function is called to find at which value to start drawing the base of a bar at \a key, when
  20503. it is stacked on top of another QCPBars (e.g. with \ref moveAbove).
  20504. positive and negative bars are separated per stack (positive are stacked above baseValue upwards,
  20505. negative are stacked below baseValue downwards). This can be indicated with \a positive. So if the
  20506. bar for which we need the base value is negative, set \a positive to false.
  20507. */
  20508. double QCPBars::getStackedBaseValue(double key, bool positive) const
  20509. {
  20510. if (mBarBelow)
  20511. {
  20512. double max = 0; // don't initialize with mBaseValue here because only base value of bottom-most bar has meaning in a bar stack
  20513. // find bars of mBarBelow that are approximately at key and find largest one:
  20514. double epsilon = qAbs(key)*(sizeof(key)==4 ? 1e-6 : 1e-14); // should be safe even when changed to use float at some point
  20515. if (key == 0)
  20516. epsilon = (sizeof(key)==4 ? 1e-6 : 1e-14);
  20517. QCPBarsDataContainer::const_iterator it = mBarBelow.data()->mDataContainer->findBegin(key-epsilon);
  20518. QCPBarsDataContainer::const_iterator itEnd = mBarBelow.data()->mDataContainer->findEnd(key+epsilon);
  20519. while (it != itEnd)
  20520. {
  20521. if (it->key > key-epsilon && it->key < key+epsilon)
  20522. {
  20523. if ((positive && it->value > max) ||
  20524. (!positive && it->value < max))
  20525. max = it->value;
  20526. }
  20527. ++it;
  20528. }
  20529. // recurse down the bar-stack to find the total height:
  20530. return max + mBarBelow.data()->getStackedBaseValue(key, positive);
  20531. } else
  20532. return mBaseValue;
  20533. }
  20534. /*! \internal
  20535. Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s)
  20536. currently above lower and below upper will become disconnected to lower/upper.
  20537. If lower is zero, upper will be disconnected at the bottom.
  20538. If upper is zero, lower will be disconnected at the top.
  20539. */
  20540. void QCPBars::connectBars(QCPBars *lower, QCPBars *upper)
  20541. {
  20542. if (!lower && !upper) return;
  20543. if (!lower) // disconnect upper at bottom
  20544. {
  20545. // disconnect old bar below upper:
  20546. if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
  20547. upper->mBarBelow.data()->mBarAbove = 0;
  20548. upper->mBarBelow = 0;
  20549. } else if (!upper) // disconnect lower at top
  20550. {
  20551. // disconnect old bar above lower:
  20552. if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
  20553. lower->mBarAbove.data()->mBarBelow = 0;
  20554. lower->mBarAbove = 0;
  20555. } else // connect lower and upper
  20556. {
  20557. // disconnect old bar above lower:
  20558. if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
  20559. lower->mBarAbove.data()->mBarBelow = 0;
  20560. // disconnect old bar below upper:
  20561. if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
  20562. upper->mBarBelow.data()->mBarAbove = 0;
  20563. lower->mBarAbove = upper;
  20564. upper->mBarBelow = lower;
  20565. }
  20566. }
  20567. /* end of 'src/plottables/plottable-bars.cpp' */
  20568. /* including file 'src/plottables/plottable-statisticalbox.cpp', size 28622 */
  20569. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  20570. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20571. //////////////////// QCPStatisticalBoxData
  20572. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20573. /*! \class QCPStatisticalBoxData
  20574. \brief Holds the data of one single data point for QCPStatisticalBox.
  20575. The stored data is:
  20576. \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
  20577. \li \a minimum: the position of the lower whisker, typically the minimum measurement of the
  20578. sample that's not considered an outlier.
  20579. \li \a lowerQuartile: the lower end of the box. The lower and the upper quartiles are the two
  20580. statistical quartiles around the median of the sample, they should contain 50% of the sample
  20581. data.
  20582. \li \a median: the value of the median mark inside the quartile box. The median separates the
  20583. sample data in half (50% of the sample data is below/above the median). (This is the \a mainValue)
  20584. \li \a upperQuartile: the upper end of the box. The lower and the upper quartiles are the two
  20585. statistical quartiles around the median of the sample, they should contain 50% of the sample
  20586. data.
  20587. \li \a maximum: the position of the upper whisker, typically the maximum measurement of the
  20588. sample that's not considered an outlier.
  20589. \li \a outliers: a QVector of outlier values that will be drawn as scatter points at the \a key
  20590. coordinate of this data point (see \ref QCPStatisticalBox::setOutlierStyle)
  20591. The container for storing multiple data points is \ref QCPStatisticalBoxDataContainer. It is a
  20592. typedef for \ref QCPDataContainer with \ref QCPStatisticalBoxData as the DataType template
  20593. parameter. See the documentation there for an explanation regarding the data type's generic
  20594. methods.
  20595. \see QCPStatisticalBoxDataContainer
  20596. */
  20597. /* start documentation of inline functions */
  20598. /*! \fn double QCPStatisticalBoxData::sortKey() const
  20599. Returns the \a key member of this data point.
  20600. For a general explanation of what this method is good for in the context of the data container,
  20601. see the documentation of \ref QCPDataContainer.
  20602. */
  20603. /*! \fn static QCPStatisticalBoxData QCPStatisticalBoxData::fromSortKey(double sortKey)
  20604. Returns a data point with the specified \a sortKey. All other members are set to zero.
  20605. For a general explanation of what this method is good for in the context of the data container,
  20606. see the documentation of \ref QCPDataContainer.
  20607. */
  20608. /*! \fn static static bool QCPStatisticalBoxData::sortKeyIsMainKey()
  20609. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  20610. this method returns true.
  20611. For a general explanation of what this method is good for in the context of the data container,
  20612. see the documentation of \ref QCPDataContainer.
  20613. */
  20614. /*! \fn double QCPStatisticalBoxData::mainKey() const
  20615. Returns the \a key member of this data point.
  20616. For a general explanation of what this method is good for in the context of the data container,
  20617. see the documentation of \ref QCPDataContainer.
  20618. */
  20619. /*! \fn double QCPStatisticalBoxData::mainValue() const
  20620. Returns the \a median member of this data point.
  20621. For a general explanation of what this method is good for in the context of the data container,
  20622. see the documentation of \ref QCPDataContainer.
  20623. */
  20624. /*! \fn QCPRange QCPStatisticalBoxData::valueRange() const
  20625. Returns a QCPRange spanning from the \a minimum to the \a maximum member of this statistical box
  20626. data point, possibly further expanded by outliers.
  20627. For a general explanation of what this method is good for in the context of the data container,
  20628. see the documentation of \ref QCPDataContainer.
  20629. */
  20630. /* end documentation of inline functions */
  20631. /*!
  20632. Constructs a data point with key and all values set to zero.
  20633. */
  20634. QCPStatisticalBoxData::QCPStatisticalBoxData() :
  20635. key(0),
  20636. minimum(0),
  20637. lowerQuartile(0),
  20638. median(0),
  20639. upperQuartile(0),
  20640. maximum(0)
  20641. {
  20642. }
  20643. /*!
  20644. Constructs a data point with the specified \a key, \a minimum, \a lowerQuartile, \a median, \a
  20645. upperQuartile, \a maximum and optionally a number of \a outliers.
  20646. */
  20647. QCPStatisticalBoxData::QCPStatisticalBoxData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers) :
  20648. key(key),
  20649. minimum(minimum),
  20650. lowerQuartile(lowerQuartile),
  20651. median(median),
  20652. upperQuartile(upperQuartile),
  20653. maximum(maximum),
  20654. outliers(outliers)
  20655. {
  20656. }
  20657. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20658. //////////////////// QCPStatisticalBox
  20659. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20660. /*! \class QCPStatisticalBox
  20661. \brief A plottable representing a single statistical box in a plot.
  20662. \image html QCPStatisticalBox.png
  20663. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
  20664. also access and modify the data via the \ref data method, which returns a pointer to the internal
  20665. \ref QCPStatisticalBoxDataContainer.
  20666. Additionally each data point can itself have a list of outliers, drawn as scatter points at the
  20667. key coordinate of the respective statistical box data point. They can either be set by using the
  20668. respective \ref addData(double,double,double,double,double,double,const QVector<double>&)
  20669. "addData" method or accessing the individual data points through \ref data, and setting the
  20670. <tt>QVector<double> outliers</tt> of the data points directly.
  20671. \section qcpstatisticalbox-appearance Changing the appearance
  20672. The appearance of each data point box, ranging from the lower to the upper quartile, is
  20673. controlled via \ref setPen and \ref setBrush. You may change the width of the boxes with \ref
  20674. setWidth in plot coordinates.
  20675. Each data point's visual representation also consists of two whiskers. Whiskers are the lines
  20676. which reach from the upper quartile to the maximum, and from the lower quartile to the minimum.
  20677. The appearance of the whiskers can be modified with: \ref setWhiskerPen, \ref setWhiskerBarPen,
  20678. \ref setWhiskerWidth. The whisker width is the width of the bar perpendicular to the whisker at
  20679. the top (for maximum) and bottom (for minimum). If the whisker pen is changed, make sure to set
  20680. the \c capStyle to \c Qt::FlatCap. Otherwise the backbone line might exceed the whisker bars by a
  20681. few pixels due to the pen cap being not perfectly flat.
  20682. The median indicator line inside the box has its own pen, \ref setMedianPen.
  20683. The outlier data points are drawn as normal scatter points. Their look can be controlled with
  20684. \ref setOutlierStyle
  20685. \section qcpstatisticalbox-usage Usage
  20686. Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable
  20687. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  20688. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  20689. Usually, you first create an instance:
  20690. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-1
  20691. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  20692. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  20693. The newly created plottable can be modified, e.g.:
  20694. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-2
  20695. */
  20696. /* start documentation of inline functions */
  20697. /*! \fn QSharedPointer<QCPStatisticalBoxDataContainer> QCPStatisticalBox::data() const
  20698. Returns a shared pointer to the internal data storage of type \ref
  20699. QCPStatisticalBoxDataContainer. You may use it to directly manipulate the data, which may be more
  20700. convenient and faster than using the regular \ref setData or \ref addData methods.
  20701. */
  20702. /* end documentation of inline functions */
  20703. /*!
  20704. Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its
  20705. value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and
  20706. not have the same orientation. If either of these restrictions is violated, a corresponding
  20707. message is printed to the debug output (qDebug), the construction is not aborted, though.
  20708. The created QCPStatisticalBox is automatically registered with the QCustomPlot instance inferred
  20709. from \a keyAxis. This QCustomPlot instance takes ownership of the QCPStatisticalBox, so do not
  20710. delete it manually but use QCustomPlot::removePlottable() instead.
  20711. */
  20712. QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  20713. QCPAbstractPlottable1D<QCPStatisticalBoxData>(keyAxis, valueAxis),
  20714. mWidth(0.5),
  20715. mWhiskerWidth(0.2),
  20716. mWhiskerPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap),
  20717. mWhiskerBarPen(Qt::black),
  20718. mWhiskerAntialiased(false),
  20719. mMedianPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap),
  20720. mOutlierStyle(QCPScatterStyle::ssCircle, Qt::blue, 6)
  20721. {
  20722. setPen(QPen(Qt::black));
  20723. setBrush(Qt::NoBrush);
  20724. }
  20725. /*! \overload
  20726. Replaces the current data container with the provided \a data container.
  20727. Since a QSharedPointer is used, multiple QCPStatisticalBoxes may share the same data container
  20728. safely. Modifying the data in the container will then affect all statistical boxes that share the
  20729. container. Sharing can be achieved by simply exchanging the data containers wrapped in shared
  20730. pointers:
  20731. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-datasharing-1
  20732. If you do not wish to share containers, but create a copy from an existing container, rather use
  20733. the \ref QCPDataContainer<DataType>::set method on the statistical box data container directly:
  20734. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-datasharing-2
  20735. \see addData
  20736. */
  20737. void QCPStatisticalBox::setData(QSharedPointer<QCPStatisticalBoxDataContainer> data)
  20738. {
  20739. mDataContainer = data;
  20740. }
  20741. /*! \overload
  20742. Replaces the current data with the provided points in \a keys, \a minimum, \a lowerQuartile, \a
  20743. median, \a upperQuartile and \a maximum. The provided vectors should have equal length. Else, the
  20744. number of added points will be the size of the smallest vector.
  20745. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  20746. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  20747. \see addData
  20748. */
  20749. 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)
  20750. {
  20751. mDataContainer->clear();
  20752. addData(keys, minimum, lowerQuartile, median, upperQuartile, maximum, alreadySorted);
  20753. }
  20754. /*!
  20755. Sets the width of the boxes in key coordinates.
  20756. \see setWhiskerWidth
  20757. */
  20758. void QCPStatisticalBox::setWidth(double width)
  20759. {
  20760. mWidth = width;
  20761. }
  20762. /*!
  20763. Sets the width of the whiskers in key coordinates.
  20764. Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
  20765. quartile to the minimum.
  20766. \see setWidth
  20767. */
  20768. void QCPStatisticalBox::setWhiskerWidth(double width)
  20769. {
  20770. mWhiskerWidth = width;
  20771. }
  20772. /*!
  20773. Sets the pen used for drawing the whisker backbone.
  20774. Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
  20775. quartile to the minimum.
  20776. Make sure to set the \c capStyle of the passed \a pen to \c Qt::FlatCap. Otherwise the backbone
  20777. line might exceed the whisker bars by a few pixels due to the pen cap being not perfectly flat.
  20778. \see setWhiskerBarPen
  20779. */
  20780. void QCPStatisticalBox::setWhiskerPen(const QPen &pen)
  20781. {
  20782. mWhiskerPen = pen;
  20783. }
  20784. /*!
  20785. Sets the pen used for drawing the whisker bars. Those are the lines parallel to the key axis at
  20786. each end of the whisker backbone.
  20787. Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
  20788. quartile to the minimum.
  20789. \see setWhiskerPen
  20790. */
  20791. void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen)
  20792. {
  20793. mWhiskerBarPen = pen;
  20794. }
  20795. /*!
  20796. Sets whether the statistical boxes whiskers are drawn with antialiasing or not.
  20797. Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and
  20798. QCustomPlot::setNotAntialiasedElements.
  20799. */
  20800. void QCPStatisticalBox::setWhiskerAntialiased(bool enabled)
  20801. {
  20802. mWhiskerAntialiased = enabled;
  20803. }
  20804. /*!
  20805. Sets the pen used for drawing the median indicator line inside the statistical boxes.
  20806. */
  20807. void QCPStatisticalBox::setMedianPen(const QPen &pen)
  20808. {
  20809. mMedianPen = pen;
  20810. }
  20811. /*!
  20812. Sets the appearance of the outlier data points.
  20813. Outliers can be specified with the method
  20814. \ref addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers)
  20815. */
  20816. void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style)
  20817. {
  20818. mOutlierStyle = style;
  20819. }
  20820. /*! \overload
  20821. Adds the provided points in \a keys, \a minimum, \a lowerQuartile, \a median, \a upperQuartile and
  20822. \a maximum to the current data. The provided vectors should have equal length. Else, the number
  20823. of added points will be the size of the smallest vector.
  20824. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  20825. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  20826. Alternatively, you can also access and modify the data directly via the \ref data method, which
  20827. returns a pointer to the internal data container.
  20828. */
  20829. 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)
  20830. {
  20831. if (keys.size() != minimum.size() || minimum.size() != lowerQuartile.size() || lowerQuartile.size() != median.size() ||
  20832. median.size() != upperQuartile.size() || upperQuartile.size() != maximum.size() || maximum.size() != keys.size())
  20833. qDebug() << Q_FUNC_INFO << "keys, minimum, lowerQuartile, median, upperQuartile, maximum have different sizes:"
  20834. << keys.size() << minimum.size() << lowerQuartile.size() << median.size() << upperQuartile.size() << maximum.size();
  20835. const int n = qMin(keys.size(), qMin(minimum.size(), qMin(lowerQuartile.size(), qMin(median.size(), qMin(upperQuartile.size(), maximum.size())))));
  20836. QVector<QCPStatisticalBoxData> tempData(n);
  20837. QVector<QCPStatisticalBoxData>::iterator it = tempData.begin();
  20838. const QVector<QCPStatisticalBoxData>::iterator itEnd = tempData.end();
  20839. int i = 0;
  20840. while (it != itEnd)
  20841. {
  20842. it->key = keys[i];
  20843. it->minimum = minimum[i];
  20844. it->lowerQuartile = lowerQuartile[i];
  20845. it->median = median[i];
  20846. it->upperQuartile = upperQuartile[i];
  20847. it->maximum = maximum[i];
  20848. ++it;
  20849. ++i;
  20850. }
  20851. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  20852. }
  20853. /*! \overload
  20854. Adds the provided data point as \a key, \a minimum, \a lowerQuartile, \a median, \a upperQuartile
  20855. and \a maximum to the current data.
  20856. Alternatively, you can also access and modify the data directly via the \ref data method, which
  20857. returns a pointer to the internal data container.
  20858. */
  20859. void QCPStatisticalBox::addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers)
  20860. {
  20861. mDataContainer->add(QCPStatisticalBoxData(key, minimum, lowerQuartile, median, upperQuartile, maximum, outliers));
  20862. }
  20863. /*!
  20864. \copydoc QCPPlottableInterface1D::selectTestRect
  20865. */
  20866. QCPDataSelection QCPStatisticalBox::selectTestRect(const QRectF &rect, bool onlySelectable) const
  20867. {
  20868. QCPDataSelection result;
  20869. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  20870. return result;
  20871. if (!mKeyAxis || !mValueAxis)
  20872. return result;
  20873. QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
  20874. getVisibleDataBounds(visibleBegin, visibleEnd);
  20875. for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  20876. {
  20877. if (rect.intersects(getQuartileBox(it)))
  20878. result.addDataRange(QCPDataRange(it-mDataContainer->constBegin(), it-mDataContainer->constBegin()+1), false);
  20879. }
  20880. result.simplify();
  20881. return result;
  20882. }
  20883. /* inherits documentation from base class */
  20884. double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  20885. {
  20886. Q_UNUSED(details)
  20887. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  20888. return -1;
  20889. if (!mKeyAxis || !mValueAxis)
  20890. return -1;
  20891. if (mKeyAxis->axisRect()->rect().contains(pos.toPoint()))
  20892. {
  20893. // get visible data range:
  20894. QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
  20895. QCPStatisticalBoxDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  20896. getVisibleDataBounds(visibleBegin, visibleEnd);
  20897. double minDistSqr = std::numeric_limits<double>::max();
  20898. for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  20899. {
  20900. if (getQuartileBox(it).contains(pos)) // quartile box
  20901. {
  20902. double currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
  20903. if (currentDistSqr < minDistSqr)
  20904. {
  20905. minDistSqr = currentDistSqr;
  20906. closestDataPoint = it;
  20907. }
  20908. } else // whiskers
  20909. {
  20910. const QVector<QLineF> whiskerBackbones(getWhiskerBackboneLines(it));
  20911. for (int i=0; i<whiskerBackbones.size(); ++i)
  20912. {
  20913. double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(whiskerBackbones.at(i));
  20914. if (currentDistSqr < minDistSqr)
  20915. {
  20916. minDistSqr = currentDistSqr;
  20917. closestDataPoint = it;
  20918. }
  20919. }
  20920. }
  20921. }
  20922. if (details)
  20923. {
  20924. int pointIndex = closestDataPoint-mDataContainer->constBegin();
  20925. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  20926. }
  20927. return qSqrt(minDistSqr);
  20928. }
  20929. return -1;
  20930. }
  20931. /* inherits documentation from base class */
  20932. QCPRange QCPStatisticalBox::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  20933. {
  20934. QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain);
  20935. // determine exact range by including width of bars/flags:
  20936. if (foundRange)
  20937. {
  20938. if (inSignDomain != QCP::sdPositive || range.lower-mWidth*0.5 > 0)
  20939. range.lower -= mWidth*0.5;
  20940. if (inSignDomain != QCP::sdNegative || range.upper+mWidth*0.5 < 0)
  20941. range.upper += mWidth*0.5;
  20942. }
  20943. return range;
  20944. }
  20945. /* inherits documentation from base class */
  20946. QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  20947. {
  20948. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  20949. }
  20950. /* inherits documentation from base class */
  20951. void QCPStatisticalBox::draw(QCPPainter *painter)
  20952. {
  20953. if (mDataContainer->isEmpty()) return;
  20954. QCPAxis *keyAxis = mKeyAxis.data();
  20955. QCPAxis *valueAxis = mValueAxis.data();
  20956. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  20957. QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
  20958. getVisibleDataBounds(visibleBegin, visibleEnd);
  20959. // loop over and draw segments of unselected/selected data:
  20960. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  20961. getDataSegments(selectedSegments, unselectedSegments);
  20962. allSegments << unselectedSegments << selectedSegments;
  20963. for (int i=0; i<allSegments.size(); ++i)
  20964. {
  20965. bool isSelectedSegment = i >= unselectedSegments.size();
  20966. QCPStatisticalBoxDataContainer::const_iterator begin = visibleBegin;
  20967. QCPStatisticalBoxDataContainer::const_iterator end = visibleEnd;
  20968. mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
  20969. if (begin == end)
  20970. continue;
  20971. for (QCPStatisticalBoxDataContainer::const_iterator it=begin; it!=end; ++it)
  20972. {
  20973. // check data validity if flag set:
  20974. # ifdef QCUSTOMPLOT_CHECK_DATA
  20975. if (QCP::isInvalidData(it->key, it->minimum) ||
  20976. QCP::isInvalidData(it->lowerQuartile, it->median) ||
  20977. QCP::isInvalidData(it->upperQuartile, it->maximum))
  20978. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range has invalid data." << "Plottable name:" << name();
  20979. for (int i=0; i<it->outliers.size(); ++i)
  20980. if (QCP::isInvalidData(it->outliers.at(i)))
  20981. qDebug() << Q_FUNC_INFO << "Data point outlier at" << it->key << "of drawn range invalid." << "Plottable name:" << name();
  20982. # endif
  20983. if (isSelectedSegment && mSelectionDecorator)
  20984. {
  20985. mSelectionDecorator->applyPen(painter);
  20986. mSelectionDecorator->applyBrush(painter);
  20987. } else
  20988. {
  20989. painter->setPen(mPen);
  20990. painter->setBrush(mBrush);
  20991. }
  20992. QCPScatterStyle finalOutlierStyle = mOutlierStyle;
  20993. if (isSelectedSegment && mSelectionDecorator)
  20994. finalOutlierStyle = mSelectionDecorator->getFinalScatterStyle(mOutlierStyle);
  20995. drawStatisticalBox(painter, it, finalOutlierStyle);
  20996. }
  20997. }
  20998. // draw other selection decoration that isn't just line/scatter pens and brushes:
  20999. if (mSelectionDecorator)
  21000. mSelectionDecorator->drawDecoration(painter, selection());
  21001. }
  21002. /* inherits documentation from base class */
  21003. void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  21004. {
  21005. // draw filled rect:
  21006. applyDefaultAntialiasingHint(painter);
  21007. painter->setPen(mPen);
  21008. painter->setBrush(mBrush);
  21009. QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
  21010. r.moveCenter(rect.center());
  21011. painter->drawRect(r);
  21012. }
  21013. /*!
  21014. Draws the graphical representation of a single statistical box with the data given by the
  21015. iterator \a it with the provided \a painter.
  21016. If the statistical box has a set of outlier data points, they are drawn with \a outlierStyle.
  21017. \see getQuartileBox, getWhiskerBackboneLines, getWhiskerBarLines
  21018. */
  21019. void QCPStatisticalBox::drawStatisticalBox(QCPPainter *painter, QCPStatisticalBoxDataContainer::const_iterator it, const QCPScatterStyle &outlierStyle) const
  21020. {
  21021. // draw quartile box:
  21022. applyDefaultAntialiasingHint(painter);
  21023. const QRectF quartileBox = getQuartileBox(it);
  21024. painter->drawRect(quartileBox);
  21025. // draw median line with cliprect set to quartile box:
  21026. painter->save();
  21027. painter->setClipRect(quartileBox, Qt::IntersectClip);
  21028. painter->setPen(mMedianPen);
  21029. painter->drawLine(QLineF(coordsToPixels(it->key-mWidth*0.5, it->median), coordsToPixels(it->key+mWidth*0.5, it->median)));
  21030. painter->restore();
  21031. // draw whisker lines:
  21032. applyAntialiasingHint(painter, mWhiskerAntialiased, QCP::aePlottables);
  21033. painter->setPen(mWhiskerPen);
  21034. painter->drawLines(getWhiskerBackboneLines(it));
  21035. painter->setPen(mWhiskerBarPen);
  21036. painter->drawLines(getWhiskerBarLines(it));
  21037. // draw outliers:
  21038. applyScattersAntialiasingHint(painter);
  21039. outlierStyle.applyTo(painter, mPen);
  21040. for (int i=0; i<it->outliers.size(); ++i)
  21041. outlierStyle.drawShape(painter, coordsToPixels(it->key, it->outliers.at(i)));
  21042. }
  21043. /*! \internal
  21044. called by \ref draw to determine which data (key) range is visible at the current key axis range
  21045. setting, so only that needs to be processed. It also takes into account the bar width.
  21046. \a begin returns an iterator to the lowest data point that needs to be taken into account when
  21047. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  21048. lower may still be just outside the visible range.
  21049. \a end returns an iterator one higher than the highest visible data point. Same as before, \a end
  21050. may also lie just outside of the visible range.
  21051. if the plottable contains no data, both \a begin and \a end point to constEnd.
  21052. */
  21053. void QCPStatisticalBox::getVisibleDataBounds(QCPStatisticalBoxDataContainer::const_iterator &begin, QCPStatisticalBoxDataContainer::const_iterator &end) const
  21054. {
  21055. if (!mKeyAxis)
  21056. {
  21057. qDebug() << Q_FUNC_INFO << "invalid key axis";
  21058. begin = mDataContainer->constEnd();
  21059. end = mDataContainer->constEnd();
  21060. return;
  21061. }
  21062. begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of box to include partially visible data points
  21063. end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of box to include partially visible data points
  21064. }
  21065. /*! \internal
  21066. Returns the box in plot coordinates (keys in x, values in y of the returned rect) that covers the
  21067. value range from the lower to the upper quartile, of the data given by \a it.
  21068. \see drawStatisticalBox, getWhiskerBackboneLines, getWhiskerBarLines
  21069. */
  21070. QRectF QCPStatisticalBox::getQuartileBox(QCPStatisticalBoxDataContainer::const_iterator it) const
  21071. {
  21072. QRectF result;
  21073. result.setTopLeft(coordsToPixels(it->key-mWidth*0.5, it->upperQuartile));
  21074. result.setBottomRight(coordsToPixels(it->key+mWidth*0.5, it->lowerQuartile));
  21075. return result;
  21076. }
  21077. /*! \internal
  21078. Returns the whisker backbones (keys in x, values in y of the returned lines) that cover the value
  21079. range from the minimum to the lower quartile, and from the upper quartile to the maximum of the
  21080. data given by \a it.
  21081. \see drawStatisticalBox, getQuartileBox, getWhiskerBarLines
  21082. */
  21083. QVector<QLineF> QCPStatisticalBox::getWhiskerBackboneLines(QCPStatisticalBoxDataContainer::const_iterator it) const
  21084. {
  21085. QVector<QLineF> result(2);
  21086. result[0].setPoints(coordsToPixels(it->key, it->lowerQuartile), coordsToPixels(it->key, it->minimum)); // min backbone
  21087. result[1].setPoints(coordsToPixels(it->key, it->upperQuartile), coordsToPixels(it->key, it->maximum)); // max backbone
  21088. return result;
  21089. }
  21090. /*! \internal
  21091. Returns the whisker bars (keys in x, values in y of the returned lines) that are placed at the
  21092. end of the whisker backbones, at the minimum and maximum of the data given by \a it.
  21093. \see drawStatisticalBox, getQuartileBox, getWhiskerBackboneLines
  21094. */
  21095. QVector<QLineF> QCPStatisticalBox::getWhiskerBarLines(QCPStatisticalBoxDataContainer::const_iterator it) const
  21096. {
  21097. QVector<QLineF> result(2);
  21098. result[0].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->minimum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->minimum)); // min bar
  21099. result[1].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->maximum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->maximum)); // max bar
  21100. return result;
  21101. }
  21102. /* end of 'src/plottables/plottable-statisticalbox.cpp' */
  21103. /* including file 'src/plottables/plottable-colormap.cpp', size 47881 */
  21104. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  21105. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21106. //////////////////// QCPColorMapData
  21107. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21108. /*! \class QCPColorMapData
  21109. \brief Holds the two-dimensional data of a QCPColorMap plottable.
  21110. This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref
  21111. QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a
  21112. color, depending on the value.
  21113. The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize).
  21114. Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref
  21115. setKeyRange, \ref setValueRange).
  21116. The data cells can be accessed in two ways: They can be directly addressed by an integer index
  21117. with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot
  21118. coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are
  21119. provided by the functions \ref coordToCell and \ref cellToCoord.
  21120. A \ref QCPColorMapData also holds an on-demand two-dimensional array of alpha values which (if
  21121. allocated) has the same size as the data map. It can be accessed via \ref setAlpha, \ref
  21122. fillAlpha and \ref clearAlpha. The memory for the alpha map is only allocated if needed, i.e. on
  21123. the first call of \ref setAlpha. \ref clearAlpha restores full opacity and frees the alpha map.
  21124. This class also buffers the minimum and maximum values that are in the data set, to provide
  21125. QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value
  21126. that is greater than the current maximum increases this maximum to the new value. However,
  21127. setting the cell that currently holds the maximum value to a smaller value doesn't decrease the
  21128. maximum again, because finding the true new maximum would require going through the entire data
  21129. array, which might be time consuming. The same holds for the data minimum. This functionality is
  21130. given by \ref recalculateDataBounds, such that you can decide when it is sensible to find the
  21131. true current minimum and maximum. The method QCPColorMap::rescaleDataRange offers a convenience
  21132. parameter \a recalculateDataBounds which may be set to true to automatically call \ref
  21133. recalculateDataBounds internally.
  21134. */
  21135. /* start of documentation of inline functions */
  21136. /*! \fn bool QCPColorMapData::isEmpty() const
  21137. Returns whether this instance carries no data. This is equivalent to having a size where at least
  21138. one of the dimensions is 0 (see \ref setSize).
  21139. */
  21140. /* end of documentation of inline functions */
  21141. /*!
  21142. Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction
  21143. and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap
  21144. at the coordinates \a keyRange and \a valueRange.
  21145. \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange
  21146. */
  21147. QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) :
  21148. mKeySize(0),
  21149. mValueSize(0),
  21150. mKeyRange(keyRange),
  21151. mValueRange(valueRange),
  21152. mIsEmpty(true),
  21153. mData(0),
  21154. mAlpha(0),
  21155. mDataModified(true)
  21156. {
  21157. setSize(keySize, valueSize);
  21158. fill(0);
  21159. }
  21160. QCPColorMapData::~QCPColorMapData()
  21161. {
  21162. if (mData)
  21163. delete[] mData;
  21164. if (mAlpha)
  21165. delete[] mAlpha;
  21166. }
  21167. /*!
  21168. Constructs a new QCPColorMapData instance copying the data and range of \a other.
  21169. */
  21170. QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) :
  21171. mKeySize(0),
  21172. mValueSize(0),
  21173. mIsEmpty(true),
  21174. mData(0),
  21175. mAlpha(0),
  21176. mDataModified(true)
  21177. {
  21178. *this = other;
  21179. }
  21180. /*!
  21181. Overwrites this color map data instance with the data stored in \a other. The alpha map state is
  21182. transferred, too.
  21183. */
  21184. QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other)
  21185. {
  21186. if (&other != this)
  21187. {
  21188. const int keySize = other.keySize();
  21189. const int valueSize = other.valueSize();
  21190. if (!other.mAlpha && mAlpha)
  21191. clearAlpha();
  21192. setSize(keySize, valueSize);
  21193. if (other.mAlpha && !mAlpha)
  21194. createAlpha(false);
  21195. setRange(other.keyRange(), other.valueRange());
  21196. if (!isEmpty())
  21197. {
  21198. memcpy(mData, other.mData, sizeof(mData[0])*keySize*valueSize);
  21199. if (mAlpha)
  21200. memcpy(mAlpha, other.mAlpha, sizeof(mAlpha[0])*keySize*valueSize);
  21201. }
  21202. mDataBounds = other.mDataBounds;
  21203. mDataModified = true;
  21204. }
  21205. return *this;
  21206. }
  21207. /* undocumented getter */
  21208. double QCPColorMapData::data(double key, double value)
  21209. {
  21210. int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5;
  21211. int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5;
  21212. if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
  21213. return mData[valueCell*mKeySize + keyCell];
  21214. else
  21215. return 0;
  21216. }
  21217. /* undocumented getter */
  21218. double QCPColorMapData::cell(int keyIndex, int valueIndex)
  21219. {
  21220. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  21221. return mData[valueIndex*mKeySize + keyIndex];
  21222. else
  21223. return 0;
  21224. }
  21225. /*!
  21226. Returns the alpha map value of the cell with the indices \a keyIndex and \a valueIndex.
  21227. If this color map data doesn't have an alpha map (because \ref setAlpha was never called after
  21228. creation or after a call to \ref clearAlpha), returns 255, which corresponds to full opacity.
  21229. \see setAlpha
  21230. */
  21231. unsigned char QCPColorMapData::alpha(int keyIndex, int valueIndex)
  21232. {
  21233. if (mAlpha && keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  21234. return mAlpha[valueIndex*mKeySize + keyIndex];
  21235. else
  21236. return 255;
  21237. }
  21238. /*!
  21239. Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in
  21240. the value dimension.
  21241. The current data is discarded and the map cells are set to 0, unless the map had already the
  21242. requested size.
  21243. Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref
  21244. isEmpty returns true.
  21245. \see setRange, setKeySize, setValueSize
  21246. */
  21247. void QCPColorMapData::setSize(int keySize, int valueSize)
  21248. {
  21249. if (keySize != mKeySize || valueSize != mValueSize)
  21250. {
  21251. mKeySize = keySize;
  21252. mValueSize = valueSize;
  21253. if (mData)
  21254. delete[] mData;
  21255. mIsEmpty = mKeySize == 0 || mValueSize == 0;
  21256. if (!mIsEmpty)
  21257. {
  21258. #ifdef __EXCEPTIONS
  21259. try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message
  21260. #endif
  21261. mData = new double[mKeySize*mValueSize];
  21262. #ifdef __EXCEPTIONS
  21263. } catch (...) { mData = 0; }
  21264. #endif
  21265. if (mData)
  21266. fill(0);
  21267. else
  21268. qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize;
  21269. } else
  21270. mData = 0;
  21271. if (mAlpha) // if we had an alpha map, recreate it with new size
  21272. createAlpha();
  21273. mDataModified = true;
  21274. }
  21275. }
  21276. /*!
  21277. Resizes the data array to have \a keySize cells in the key dimension.
  21278. The current data is discarded and the map cells are set to 0, unless the map had already the
  21279. requested size.
  21280. Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true.
  21281. \see setKeyRange, setSize, setValueSize
  21282. */
  21283. void QCPColorMapData::setKeySize(int keySize)
  21284. {
  21285. setSize(keySize, mValueSize);
  21286. }
  21287. /*!
  21288. Resizes the data array to have \a valueSize cells in the value dimension.
  21289. The current data is discarded and the map cells are set to 0, unless the map had already the
  21290. requested size.
  21291. Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true.
  21292. \see setValueRange, setSize, setKeySize
  21293. */
  21294. void QCPColorMapData::setValueSize(int valueSize)
  21295. {
  21296. setSize(mKeySize, valueSize);
  21297. }
  21298. /*!
  21299. Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area
  21300. covered by the color map in plot coordinates.
  21301. The outer cells will be centered on the range boundaries given to this function. For example, if
  21302. the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
  21303. be cells centered on the key coordinates 2, 2.5 and 3.
  21304. \see setSize
  21305. */
  21306. void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange)
  21307. {
  21308. setKeyRange(keyRange);
  21309. setValueRange(valueRange);
  21310. }
  21311. /*!
  21312. Sets the coordinate range the data shall be distributed over in the key dimension. Together with
  21313. the value range, This defines the rectangular area covered by the color map in plot coordinates.
  21314. The outer cells will be centered on the range boundaries given to this function. For example, if
  21315. the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
  21316. be cells centered on the key coordinates 2, 2.5 and 3.
  21317. \see setRange, setValueRange, setSize
  21318. */
  21319. void QCPColorMapData::setKeyRange(const QCPRange &keyRange)
  21320. {
  21321. mKeyRange = keyRange;
  21322. }
  21323. /*!
  21324. Sets the coordinate range the data shall be distributed over in the value dimension. Together with
  21325. the key range, This defines the rectangular area covered by the color map in plot coordinates.
  21326. The outer cells will be centered on the range boundaries given to this function. For example, if
  21327. the value size (\ref setValueSize) is 3 and \a valueRange is set to <tt>QCPRange(2, 3)</tt> there
  21328. will be cells centered on the value coordinates 2, 2.5 and 3.
  21329. \see setRange, setKeyRange, setSize
  21330. */
  21331. void QCPColorMapData::setValueRange(const QCPRange &valueRange)
  21332. {
  21333. mValueRange = valueRange;
  21334. }
  21335. /*!
  21336. Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a
  21337. z.
  21338. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  21339. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  21340. you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
  21341. determine the cell index. Rather directly access the cell index with \ref
  21342. QCPColorMapData::setCell.
  21343. \see setCell, setRange
  21344. */
  21345. void QCPColorMapData::setData(double key, double value, double z)
  21346. {
  21347. int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5;
  21348. int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5;
  21349. if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
  21350. {
  21351. mData[valueCell*mKeySize + keyCell] = z;
  21352. if (z < mDataBounds.lower)
  21353. mDataBounds.lower = z;
  21354. if (z > mDataBounds.upper)
  21355. mDataBounds.upper = z;
  21356. mDataModified = true;
  21357. }
  21358. }
  21359. /*!
  21360. Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices
  21361. enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see
  21362. \ref setSize).
  21363. In the standard plot configuration (horizontal key axis and vertical value axis, both not
  21364. range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with
  21365. indices (keySize-1, valueSize-1) is in the top right corner of the color map.
  21366. \see setData, setSize
  21367. */
  21368. void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z)
  21369. {
  21370. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  21371. {
  21372. mData[valueIndex*mKeySize + keyIndex] = z;
  21373. if (z < mDataBounds.lower)
  21374. mDataBounds.lower = z;
  21375. if (z > mDataBounds.upper)
  21376. mDataBounds.upper = z;
  21377. mDataModified = true;
  21378. } else
  21379. qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex;
  21380. }
  21381. /*!
  21382. Sets the alpha of the color map cell given by \a keyIndex and \a valueIndex to \a alpha. A value
  21383. of 0 for \a alpha results in a fully transparent cell, and a value of 255 results in a fully
  21384. opaque cell.
  21385. If an alpha map doesn't exist yet for this color map data, it will be created here. If you wish
  21386. to restore full opacity and free any allocated memory of the alpha map, call \ref clearAlpha.
  21387. Note that the cell-wise alpha which can be configured here is independent of any alpha configured
  21388. in the color map's gradient (\ref QCPColorGradient). If a cell is affected both by the cell-wise
  21389. and gradient alpha, the alpha values will be blended accordingly during rendering of the color
  21390. map.
  21391. \see fillAlpha, clearAlpha
  21392. */
  21393. void QCPColorMapData::setAlpha(int keyIndex, int valueIndex, unsigned char alpha)
  21394. {
  21395. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  21396. {
  21397. if (mAlpha || createAlpha())
  21398. {
  21399. mAlpha[valueIndex*mKeySize + keyIndex] = alpha;
  21400. mDataModified = true;
  21401. }
  21402. } else
  21403. qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex;
  21404. }
  21405. /*!
  21406. Goes through the data and updates the buffered minimum and maximum data values.
  21407. Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange
  21408. and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten
  21409. with a smaller or larger value respectively, since the buffered maximum/minimum values have been
  21410. updated the last time. Why this is the case is explained in the class description (\ref
  21411. QCPColorMapData).
  21412. Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a
  21413. recalculateDataBounds for convenience. Setting this to true will call this method for you, before
  21414. doing the rescale.
  21415. */
  21416. void QCPColorMapData::recalculateDataBounds()
  21417. {
  21418. if (mKeySize > 0 && mValueSize > 0)
  21419. {
  21420. double minHeight = mData[0];
  21421. double maxHeight = mData[0];
  21422. const int dataCount = mValueSize*mKeySize;
  21423. for (int i=0; i<dataCount; ++i)
  21424. {
  21425. if (mData[i] > maxHeight)
  21426. maxHeight = mData[i];
  21427. if (mData[i] < minHeight)
  21428. minHeight = mData[i];
  21429. }
  21430. mDataBounds.lower = minHeight;
  21431. mDataBounds.upper = maxHeight;
  21432. }
  21433. }
  21434. /*!
  21435. Frees the internal data memory.
  21436. This is equivalent to calling \ref setSize "setSize(0, 0)".
  21437. */
  21438. void QCPColorMapData::clear()
  21439. {
  21440. setSize(0, 0);
  21441. }
  21442. /*!
  21443. Frees the internal alpha map. The color map will have full opacity again.
  21444. */
  21445. void QCPColorMapData::clearAlpha()
  21446. {
  21447. if (mAlpha)
  21448. {
  21449. delete[] mAlpha;
  21450. mAlpha = 0;
  21451. mDataModified = true;
  21452. }
  21453. }
  21454. /*!
  21455. Sets all cells to the value \a z.
  21456. */
  21457. void QCPColorMapData::fill(double z)
  21458. {
  21459. const int dataCount = mValueSize*mKeySize;
  21460. for (int i=0; i<dataCount; ++i)
  21461. mData[i] = z;
  21462. mDataBounds = QCPRange(z, z);
  21463. mDataModified = true;
  21464. }
  21465. /*!
  21466. Sets the opacity of all color map cells to \a alpha. A value of 0 for \a alpha results in a fully
  21467. transparent color map, and a value of 255 results in a fully opaque color map.
  21468. If you wish to restore opacity to 100% and free any used memory for the alpha map, rather use
  21469. \ref clearAlpha.
  21470. \see setAlpha
  21471. */
  21472. void QCPColorMapData::fillAlpha(unsigned char alpha)
  21473. {
  21474. if (mAlpha || createAlpha(false))
  21475. {
  21476. const int dataCount = mValueSize*mKeySize;
  21477. for (int i=0; i<dataCount; ++i)
  21478. mAlpha[i] = alpha;
  21479. mDataModified = true;
  21480. }
  21481. }
  21482. /*!
  21483. Transforms plot coordinates given by \a key and \a value to cell indices of this QCPColorMapData
  21484. instance. The resulting cell indices are returned via the output parameters \a keyIndex and \a
  21485. valueIndex.
  21486. The retrieved key/value cell indices can then be used for example with \ref setCell.
  21487. If you are only interested in a key or value index, you may pass 0 as \a valueIndex or \a
  21488. keyIndex.
  21489. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  21490. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  21491. you shouldn't use the \ref QCPColorMapData::coordToCell method as it uses a linear transformation to
  21492. determine the cell index.
  21493. \see cellToCoord, QCPAxis::coordToPixel
  21494. */
  21495. void QCPColorMapData::coordToCell(double key, double value, int *keyIndex, int *valueIndex) const
  21496. {
  21497. if (keyIndex)
  21498. *keyIndex = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5;
  21499. if (valueIndex)
  21500. *valueIndex = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5;
  21501. }
  21502. /*!
  21503. Transforms cell indices given by \a keyIndex and \a valueIndex to cell indices of this QCPColorMapData
  21504. instance. The resulting coordinates are returned via the output parameters \a key and \a
  21505. value.
  21506. If you are only interested in a key or value coordinate, you may pass 0 as \a key or \a
  21507. value.
  21508. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  21509. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  21510. you shouldn't use the \ref QCPColorMapData::cellToCoord method as it uses a linear transformation to
  21511. determine the cell index.
  21512. \see coordToCell, QCPAxis::pixelToCoord
  21513. */
  21514. void QCPColorMapData::cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const
  21515. {
  21516. if (key)
  21517. *key = keyIndex/(double)(mKeySize-1)*(mKeyRange.upper-mKeyRange.lower)+mKeyRange.lower;
  21518. if (value)
  21519. *value = valueIndex/(double)(mValueSize-1)*(mValueRange.upper-mValueRange.lower)+mValueRange.lower;
  21520. }
  21521. /*! \internal
  21522. Allocates the internal alpha map with the current data map key/value size and, if \a
  21523. initializeOpaque is true, initializes all values to 255. If \a initializeOpaque is false, the
  21524. values are not initialized at all. In this case, the alpha map should be initialized manually,
  21525. e.g. with \ref fillAlpha.
  21526. If an alpha map exists already, it is deleted first. If this color map is empty (has either key
  21527. or value size zero, see \ref isEmpty), the alpha map is cleared.
  21528. The return value indicates the existence of the alpha map after the call. So this method returns
  21529. true if the data map isn't empty and an alpha map was successfully allocated.
  21530. */
  21531. bool QCPColorMapData::createAlpha(bool initializeOpaque)
  21532. {
  21533. clearAlpha();
  21534. if (isEmpty())
  21535. return false;
  21536. #ifdef __EXCEPTIONS
  21537. try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message
  21538. #endif
  21539. mAlpha = new unsigned char[mKeySize*mValueSize];
  21540. #ifdef __EXCEPTIONS
  21541. } catch (...) { mAlpha = 0; }
  21542. #endif
  21543. if (mAlpha)
  21544. {
  21545. if (initializeOpaque)
  21546. fillAlpha(255);
  21547. return true;
  21548. } else
  21549. {
  21550. qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize;
  21551. return false;
  21552. }
  21553. }
  21554. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21555. //////////////////// QCPColorMap
  21556. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21557. /*! \class QCPColorMap
  21558. \brief A plottable representing a two-dimensional color map in a plot.
  21559. \image html QCPColorMap.png
  21560. The data is stored in the class \ref QCPColorMapData, which can be accessed via the data()
  21561. method.
  21562. A color map has three dimensions to represent a data point: The \a key dimension, the \a value
  21563. dimension and the \a data dimension. As with other plottables such as graphs, \a key and \a value
  21564. correspond to two orthogonal axes on the QCustomPlot surface that you specify in the QCPColorMap
  21565. constructor. The \a data dimension however is encoded as the color of the point at (\a key, \a
  21566. value).
  21567. Set the number of points (or \a cells) in the key/value dimension via \ref
  21568. QCPColorMapData::setSize. The plot coordinate range over which these points will be displayed is
  21569. specified via \ref QCPColorMapData::setRange. The first cell will be centered on the lower range
  21570. boundary and the last cell will be centered on the upper range boundary. The data can be set by
  21571. either accessing the cells directly with QCPColorMapData::setCell or by addressing the cells via
  21572. their plot coordinates with \ref QCPColorMapData::setData. If possible, you should prefer
  21573. setCell, since it doesn't need to do any coordinate transformation and thus performs a bit
  21574. better.
  21575. The cell with index (0, 0) is at the bottom left, if the color map uses normal (i.e. not reversed)
  21576. key and value axes.
  21577. To show the user which colors correspond to which \a data values, a \ref QCPColorScale is
  21578. typically placed to the right of the axis rect. See the documentation there for details on how to
  21579. add and use a color scale.
  21580. \section qcpcolormap-appearance Changing the appearance
  21581. The central part of the appearance is the color gradient, which can be specified via \ref
  21582. setGradient. See the documentation of \ref QCPColorGradient for details on configuring a color
  21583. gradient.
  21584. The \a data range that is mapped to the colors of the gradient can be specified with \ref
  21585. setDataRange. To make the data range encompass the whole data set minimum to maximum, call \ref
  21586. rescaleDataRange.
  21587. \section qcpcolormap-transparency Transparency
  21588. Transparency in color maps can be achieved by two mechanisms. On one hand, you can specify alpha
  21589. values for color stops of the \ref QCPColorGradient, via the regular QColor interface. This will
  21590. cause the color map data which gets mapped to colors around those color stops to appear with the
  21591. accordingly interpolated transparency.
  21592. On the other hand you can also directly apply an alpha value to each cell independent of its
  21593. data, by using the alpha map feature of \ref QCPColorMapData. The relevant methods are \ref
  21594. QCPColorMapData::setAlpha, QCPColorMapData::fillAlpha and \ref QCPColorMapData::clearAlpha().
  21595. The two transparencies will be joined together in the plot and otherwise not interfere with each
  21596. other. They are mixed in a multiplicative matter, so an alpha of e.g. 50% (128/255) in both modes
  21597. simultaneously, will result in a total transparency of 25% (64/255).
  21598. \section qcpcolormap-usage Usage
  21599. Like all data representing objects in QCustomPlot, the QCPColorMap is a plottable
  21600. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  21601. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  21602. Usually, you first create an instance:
  21603. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-1
  21604. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  21605. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  21606. The newly created plottable can be modified, e.g.:
  21607. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-2
  21608. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  21609. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  21610. you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
  21611. determine the cell index. Rather directly access the cell index with \ref
  21612. QCPColorMapData::setCell.
  21613. */
  21614. /* start documentation of inline functions */
  21615. /*! \fn QCPColorMapData *QCPColorMap::data() const
  21616. Returns a pointer to the internal data storage of type \ref QCPColorMapData. Access this to
  21617. modify data points (cells) and the color map key/value range.
  21618. \see setData
  21619. */
  21620. /* end documentation of inline functions */
  21621. /* start documentation of signals */
  21622. /*! \fn void QCPColorMap::dataRangeChanged(const QCPRange &newRange);
  21623. This signal is emitted when the data range changes.
  21624. \see setDataRange
  21625. */
  21626. /*! \fn void QCPColorMap::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
  21627. This signal is emitted when the data scale type changes.
  21628. \see setDataScaleType
  21629. */
  21630. /*! \fn void QCPColorMap::gradientChanged(const QCPColorGradient &newGradient);
  21631. This signal is emitted when the gradient changes.
  21632. \see setGradient
  21633. */
  21634. /* end documentation of signals */
  21635. /*!
  21636. Constructs a color map with the specified \a keyAxis and \a valueAxis.
  21637. The created QCPColorMap is automatically registered with the QCustomPlot instance inferred from
  21638. \a keyAxis. This QCustomPlot instance takes ownership of the QCPColorMap, so do not delete it
  21639. manually but use QCustomPlot::removePlottable() instead.
  21640. */
  21641. QCPColorMap::QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  21642. QCPAbstractPlottable(keyAxis, valueAxis),
  21643. mDataScaleType(QCPAxis::stLinear),
  21644. mMapData(new QCPColorMapData(10, 10, QCPRange(0, 5), QCPRange(0, 5))),
  21645. mGradient(QCPColorGradient::gpCold),
  21646. mInterpolate(true),
  21647. mTightBoundary(false),
  21648. mMapImageInvalidated(true)
  21649. {
  21650. }
  21651. QCPColorMap::~QCPColorMap()
  21652. {
  21653. delete mMapData;
  21654. }
  21655. /*!
  21656. Replaces the current \ref data with the provided \a data.
  21657. If \a copy is set to true, the \a data object will only be copied. if false, the color map
  21658. takes ownership of the passed data and replaces the internal data pointer with it. This is
  21659. significantly faster than copying for large datasets.
  21660. */
  21661. void QCPColorMap::setData(QCPColorMapData *data, bool copy)
  21662. {
  21663. if (mMapData == data)
  21664. {
  21665. qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data);
  21666. return;
  21667. }
  21668. if (copy)
  21669. {
  21670. *mMapData = *data;
  21671. } else
  21672. {
  21673. delete mMapData;
  21674. mMapData = data;
  21675. }
  21676. mMapImageInvalidated = true;
  21677. }
  21678. /*!
  21679. Sets the data range of this color map to \a dataRange. The data range defines which data values
  21680. are mapped to the color gradient.
  21681. To make the data range span the full range of the data set, use \ref rescaleDataRange.
  21682. \see QCPColorScale::setDataRange
  21683. */
  21684. void QCPColorMap::setDataRange(const QCPRange &dataRange)
  21685. {
  21686. if (!QCPRange::validRange(dataRange)) return;
  21687. if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
  21688. {
  21689. if (mDataScaleType == QCPAxis::stLogarithmic)
  21690. mDataRange = dataRange.sanitizedForLogScale();
  21691. else
  21692. mDataRange = dataRange.sanitizedForLinScale();
  21693. mMapImageInvalidated = true;
  21694. emit dataRangeChanged(mDataRange);
  21695. }
  21696. }
  21697. /*!
  21698. Sets whether the data is correlated with the color gradient linearly or logarithmically.
  21699. \see QCPColorScale::setDataScaleType
  21700. */
  21701. void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType)
  21702. {
  21703. if (mDataScaleType != scaleType)
  21704. {
  21705. mDataScaleType = scaleType;
  21706. mMapImageInvalidated = true;
  21707. emit dataScaleTypeChanged(mDataScaleType);
  21708. if (mDataScaleType == QCPAxis::stLogarithmic)
  21709. setDataRange(mDataRange.sanitizedForLogScale());
  21710. }
  21711. }
  21712. /*!
  21713. Sets the color gradient that is used to represent the data. For more details on how to create an
  21714. own gradient or use one of the preset gradients, see \ref QCPColorGradient.
  21715. The colors defined by the gradient will be used to represent data values in the currently set
  21716. data range, see \ref setDataRange. Data points that are outside this data range will either be
  21717. colored uniformly with the respective gradient boundary color, or the gradient will repeat,
  21718. depending on \ref QCPColorGradient::setPeriodic.
  21719. \see QCPColorScale::setGradient
  21720. */
  21721. void QCPColorMap::setGradient(const QCPColorGradient &gradient)
  21722. {
  21723. if (mGradient != gradient)
  21724. {
  21725. mGradient = gradient;
  21726. mMapImageInvalidated = true;
  21727. emit gradientChanged(mGradient);
  21728. }
  21729. }
  21730. /*!
  21731. Sets whether the color map image shall use bicubic interpolation when displaying the color map
  21732. shrinked or expanded, and not at a 1:1 pixel-to-data scale.
  21733. \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled"
  21734. */
  21735. void QCPColorMap::setInterpolate(bool enabled)
  21736. {
  21737. mInterpolate = enabled;
  21738. mMapImageInvalidated = true; // because oversampling factors might need to change
  21739. }
  21740. /*!
  21741. Sets whether the outer most data rows and columns are clipped to the specified key and value
  21742. range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange).
  21743. if \a enabled is set to false, the data points at the border of the color map are drawn with the
  21744. same width and height as all other data points. Since the data points are represented by
  21745. rectangles of one color centered on the data coordinate, this means that the shown color map
  21746. extends by half a data point over the specified key/value range in each direction.
  21747. \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled"
  21748. */
  21749. void QCPColorMap::setTightBoundary(bool enabled)
  21750. {
  21751. mTightBoundary = enabled;
  21752. }
  21753. /*!
  21754. Associates the color scale \a colorScale with this color map.
  21755. This means that both the color scale and the color map synchronize their gradient, data range and
  21756. data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps
  21757. can be associated with one single color scale. This causes the color maps to also synchronize
  21758. those properties, via the mutual color scale.
  21759. This function causes the color map to adopt the current color gradient, data range and data scale
  21760. type of \a colorScale. After this call, you may change these properties at either the color map
  21761. or the color scale, and the setting will be applied to both.
  21762. Pass 0 as \a colorScale to disconnect the color scale from this color map again.
  21763. */
  21764. void QCPColorMap::setColorScale(QCPColorScale *colorScale)
  21765. {
  21766. if (mColorScale) // unconnect signals from old color scale
  21767. {
  21768. disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
  21769. disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
  21770. disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
  21771. disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  21772. disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
  21773. disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  21774. }
  21775. mColorScale = colorScale;
  21776. if (mColorScale) // connect signals to new color scale
  21777. {
  21778. setGradient(mColorScale.data()->gradient());
  21779. setDataRange(mColorScale.data()->dataRange());
  21780. setDataScaleType(mColorScale.data()->dataScaleType());
  21781. connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
  21782. connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
  21783. connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
  21784. connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  21785. connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
  21786. connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  21787. }
  21788. }
  21789. /*!
  21790. Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the
  21791. current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods,
  21792. only for the third data dimension of the color map.
  21793. The minimum and maximum values of the data set are buffered in the internal QCPColorMapData
  21794. instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref
  21795. QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For
  21796. performance reasons, however, they are only updated in an expanding fashion. So the buffered
  21797. maximum can only increase and the buffered minimum can only decrease. In consequence, changes to
  21798. the data that actually lower the maximum of the data set (by overwriting the cell holding the
  21799. current maximum with a smaller value), aren't recognized and the buffered maximum overestimates
  21800. the true maximum of the data set. The same happens for the buffered minimum. To recalculate the
  21801. true minimum and maximum by explicitly looking at each cell, the method
  21802. QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a
  21803. recalculateDataBounds calls this method before setting the data range to the buffered minimum and
  21804. maximum.
  21805. \see setDataRange
  21806. */
  21807. void QCPColorMap::rescaleDataRange(bool recalculateDataBounds)
  21808. {
  21809. if (recalculateDataBounds)
  21810. mMapData->recalculateDataBounds();
  21811. setDataRange(mMapData->dataBounds());
  21812. }
  21813. /*!
  21814. Takes the current appearance of the color map and updates the legend icon, which is used to
  21815. represent this color map in the legend (see \ref QCPLegend).
  21816. The \a transformMode specifies whether the rescaling is done by a faster, low quality image
  21817. scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm
  21818. (Qt::SmoothTransformation).
  21819. The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to
  21820. the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured
  21821. legend icon size, the thumb will be rescaled during drawing of the legend item.
  21822. \see setDataRange
  21823. */
  21824. void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize)
  21825. {
  21826. if (mMapImage.isNull() && !data()->isEmpty())
  21827. updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet)
  21828. if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again
  21829. {
  21830. bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
  21831. bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
  21832. mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode);
  21833. }
  21834. }
  21835. /* inherits documentation from base class */
  21836. double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  21837. {
  21838. Q_UNUSED(details)
  21839. if ((onlySelectable && mSelectable == QCP::stNone) || mMapData->isEmpty())
  21840. return -1;
  21841. if (!mKeyAxis || !mValueAxis)
  21842. return -1;
  21843. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
  21844. {
  21845. double posKey, posValue;
  21846. pixelsToCoords(pos, posKey, posValue);
  21847. if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue))
  21848. {
  21849. if (details)
  21850. details->setValue(QCPDataSelection(QCPDataRange(0, 1))); // temporary solution, to facilitate whole-plottable selection. Replace in future version with segmented 2D selection.
  21851. return mParentPlot->selectionTolerance()*0.99;
  21852. }
  21853. }
  21854. return -1;
  21855. }
  21856. /* inherits documentation from base class */
  21857. QCPRange QCPColorMap::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  21858. {
  21859. foundRange = true;
  21860. QCPRange result = mMapData->keyRange();
  21861. result.normalize();
  21862. if (inSignDomain == QCP::sdPositive)
  21863. {
  21864. if (result.lower <= 0 && result.upper > 0)
  21865. result.lower = result.upper*1e-3;
  21866. else if (result.lower <= 0 && result.upper <= 0)
  21867. foundRange = false;
  21868. } else if (inSignDomain == QCP::sdNegative)
  21869. {
  21870. if (result.upper >= 0 && result.lower < 0)
  21871. result.upper = result.lower*1e-3;
  21872. else if (result.upper >= 0 && result.lower >= 0)
  21873. foundRange = false;
  21874. }
  21875. return result;
  21876. }
  21877. /* inherits documentation from base class */
  21878. QCPRange QCPColorMap::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  21879. {
  21880. if (inKeyRange != QCPRange())
  21881. {
  21882. if (mMapData->keyRange().upper < inKeyRange.lower || mMapData->keyRange().lower > inKeyRange.upper)
  21883. {
  21884. foundRange = false;
  21885. return QCPRange();
  21886. }
  21887. }
  21888. foundRange = true;
  21889. QCPRange result = mMapData->valueRange();
  21890. result.normalize();
  21891. if (inSignDomain == QCP::sdPositive)
  21892. {
  21893. if (result.lower <= 0 && result.upper > 0)
  21894. result.lower = result.upper*1e-3;
  21895. else if (result.lower <= 0 && result.upper <= 0)
  21896. foundRange = false;
  21897. } else if (inSignDomain == QCP::sdNegative)
  21898. {
  21899. if (result.upper >= 0 && result.lower < 0)
  21900. result.upper = result.lower*1e-3;
  21901. else if (result.upper >= 0 && result.lower >= 0)
  21902. foundRange = false;
  21903. }
  21904. return result;
  21905. }
  21906. /*! \internal
  21907. Updates the internal map image buffer by going through the internal \ref QCPColorMapData and
  21908. turning the data values into color pixels with \ref QCPColorGradient::colorize.
  21909. This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image
  21910. has been invalidated for a different reason (e.g. a change of the data range with \ref
  21911. setDataRange).
  21912. If the map cell count is low, the image created will be oversampled in order to avoid a
  21913. QPainter::drawImage bug which makes inner pixel boundaries jitter when stretch-drawing images
  21914. without smooth transform enabled. Accordingly, oversampling isn't performed if \ref
  21915. setInterpolate is true.
  21916. */
  21917. void QCPColorMap::updateMapImage()
  21918. {
  21919. QCPAxis *keyAxis = mKeyAxis.data();
  21920. if (!keyAxis) return;
  21921. if (mMapData->isEmpty()) return;
  21922. const QImage::Format format = QImage::Format_ARGB32_Premultiplied;
  21923. const int keySize = mMapData->keySize();
  21924. const int valueSize = mMapData->valueSize();
  21925. 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
  21926. 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
  21927. // resize mMapImage to correct dimensions including possible oversampling factors, according to key/value axes orientation:
  21928. if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.width() != keySize*keyOversamplingFactor || mMapImage.height() != valueSize*valueOversamplingFactor))
  21929. mMapImage = QImage(QSize(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor), format);
  21930. else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize*valueOversamplingFactor || mMapImage.height() != keySize*keyOversamplingFactor))
  21931. mMapImage = QImage(QSize(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor), format);
  21932. if (mMapImage.isNull())
  21933. {
  21934. qDebug() << Q_FUNC_INFO << "Couldn't create map image (possibly too large for memory)";
  21935. mMapImage = QImage(QSize(10, 10), format);
  21936. mMapImage.fill(Qt::black);
  21937. } else
  21938. {
  21939. QImage *localMapImage = &mMapImage; // this is the image on which the colorization operates. Either the final mMapImage, or if we need oversampling, mUndersampledMapImage
  21940. if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1)
  21941. {
  21942. // resize undersampled map image to actual key/value cell sizes:
  21943. if (keyAxis->orientation() == Qt::Horizontal && (mUndersampledMapImage.width() != keySize || mUndersampledMapImage.height() != valueSize))
  21944. mUndersampledMapImage = QImage(QSize(keySize, valueSize), format);
  21945. else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize))
  21946. mUndersampledMapImage = QImage(QSize(valueSize, keySize), format);
  21947. localMapImage = &mUndersampledMapImage; // make the colorization run on the undersampled image
  21948. } else if (!mUndersampledMapImage.isNull())
  21949. mUndersampledMapImage = QImage(); // don't need oversampling mechanism anymore (map size has changed) but mUndersampledMapImage still has nonzero size, free it
  21950. const double *rawData = mMapData->mData;
  21951. const unsigned char *rawAlpha = mMapData->mAlpha;
  21952. if (keyAxis->orientation() == Qt::Horizontal)
  21953. {
  21954. const int lineCount = valueSize;
  21955. const int rowCount = keySize;
  21956. for (int line=0; line<lineCount; ++line)
  21957. {
  21958. 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)
  21959. if (rawAlpha)
  21960. mGradient.colorize(rawData+line*rowCount, rawAlpha+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic);
  21961. else
  21962. mGradient.colorize(rawData+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic);
  21963. }
  21964. } else // keyAxis->orientation() == Qt::Vertical
  21965. {
  21966. const int lineCount = keySize;
  21967. const int rowCount = valueSize;
  21968. for (int line=0; line<lineCount; ++line)
  21969. {
  21970. 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)
  21971. if (rawAlpha)
  21972. mGradient.colorize(rawData+line, rawAlpha+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic);
  21973. else
  21974. mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic);
  21975. }
  21976. }
  21977. if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1)
  21978. {
  21979. if (keyAxis->orientation() == Qt::Horizontal)
  21980. mMapImage = mUndersampledMapImage.scaled(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation);
  21981. else
  21982. mMapImage = mUndersampledMapImage.scaled(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation);
  21983. }
  21984. }
  21985. mMapData->mDataModified = false;
  21986. mMapImageInvalidated = false;
  21987. }
  21988. /* inherits documentation from base class */
  21989. void QCPColorMap::draw(QCPPainter *painter)
  21990. {
  21991. if (mMapData->isEmpty()) return;
  21992. if (!mKeyAxis || !mValueAxis) return;
  21993. applyDefaultAntialiasingHint(painter);
  21994. if (mMapData->mDataModified || mMapImageInvalidated)
  21995. updateMapImage();
  21996. // use buffer if painting vectorized (PDF):
  21997. const bool useBuffer = painter->modes().testFlag(QCPPainter::pmVectorized);
  21998. QCPPainter *localPainter = painter; // will be redirected to paint on mapBuffer if painting vectorized
  21999. QRectF mapBufferTarget; // the rect in absolute widget coordinates where the visible map portion/buffer will end up in
  22000. QPixmap mapBuffer;
  22001. if (useBuffer)
  22002. {
  22003. const double mapBufferPixelRatio = 3; // factor by which DPI is increased in embedded bitmaps
  22004. mapBufferTarget = painter->clipRegion().boundingRect();
  22005. mapBuffer = QPixmap((mapBufferTarget.size()*mapBufferPixelRatio).toSize());
  22006. mapBuffer.fill(Qt::transparent);
  22007. localPainter = new QCPPainter(&mapBuffer);
  22008. localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio);
  22009. localPainter->translate(-mapBufferTarget.topLeft());
  22010. }
  22011. QRectF imageRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
  22012. coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized();
  22013. // extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are centered on map range boundary):
  22014. double halfCellWidth = 0; // in pixels
  22015. double halfCellHeight = 0; // in pixels
  22016. if (keyAxis()->orientation() == Qt::Horizontal)
  22017. {
  22018. if (mMapData->keySize() > 1)
  22019. halfCellWidth = 0.5*imageRect.width()/(double)(mMapData->keySize()-1);
  22020. if (mMapData->valueSize() > 1)
  22021. halfCellHeight = 0.5*imageRect.height()/(double)(mMapData->valueSize()-1);
  22022. } else // keyAxis orientation is Qt::Vertical
  22023. {
  22024. if (mMapData->keySize() > 1)
  22025. halfCellHeight = 0.5*imageRect.height()/(double)(mMapData->keySize()-1);
  22026. if (mMapData->valueSize() > 1)
  22027. halfCellWidth = 0.5*imageRect.width()/(double)(mMapData->valueSize()-1);
  22028. }
  22029. imageRect.adjust(-halfCellWidth, -halfCellHeight, halfCellWidth, halfCellHeight);
  22030. const bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
  22031. const bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
  22032. const bool smoothBackup = localPainter->renderHints().testFlag(QPainter::SmoothPixmapTransform);
  22033. localPainter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate);
  22034. QRegion clipBackup;
  22035. if (mTightBoundary)
  22036. {
  22037. clipBackup = localPainter->clipRegion();
  22038. QRectF tightClipRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
  22039. coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized();
  22040. localPainter->setClipRect(tightClipRect, Qt::IntersectClip);
  22041. }
  22042. localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY));
  22043. if (mTightBoundary)
  22044. localPainter->setClipRegion(clipBackup);
  22045. localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup);
  22046. if (useBuffer) // localPainter painted to mapBuffer, so now draw buffer with original painter
  22047. {
  22048. delete localPainter;
  22049. painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer);
  22050. }
  22051. }
  22052. /* inherits documentation from base class */
  22053. void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  22054. {
  22055. applyDefaultAntialiasingHint(painter);
  22056. // draw map thumbnail:
  22057. if (!mLegendIcon.isNull())
  22058. {
  22059. QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation);
  22060. QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height());
  22061. iconRect.moveCenter(rect.center());
  22062. painter->drawPixmap(iconRect.topLeft(), scaledIcon);
  22063. }
  22064. /*
  22065. // draw frame:
  22066. painter->setBrush(Qt::NoBrush);
  22067. painter->setPen(Qt::black);
  22068. painter->drawRect(rect.adjusted(1, 1, 0, 0));
  22069. */
  22070. }
  22071. /* end of 'src/plottables/plottable-colormap.cpp' */
  22072. /* including file 'src/plottables/plottable-financial.cpp', size 42610 */
  22073. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  22074. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22075. //////////////////// QCPFinancialData
  22076. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22077. /*! \class QCPFinancialData
  22078. \brief Holds the data of one single data point for QCPFinancial.
  22079. The stored data is:
  22080. \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
  22081. \li \a open: The opening value at the data point (this is the \a mainValue)
  22082. \li \a high: The high/maximum value at the data point
  22083. \li \a low: The low/minimum value at the data point
  22084. \li \a close: The closing value at the data point
  22085. The container for storing multiple data points is \ref QCPFinancialDataContainer. It is a typedef
  22086. for \ref QCPDataContainer with \ref QCPFinancialData as the DataType template parameter. See the
  22087. documentation there for an explanation regarding the data type's generic methods.
  22088. \see QCPFinancialDataContainer
  22089. */
  22090. /* start documentation of inline functions */
  22091. /*! \fn double QCPFinancialData::sortKey() const
  22092. Returns the \a key member of this data point.
  22093. For a general explanation of what this method is good for in the context of the data container,
  22094. see the documentation of \ref QCPDataContainer.
  22095. */
  22096. /*! \fn static QCPFinancialData QCPFinancialData::fromSortKey(double sortKey)
  22097. Returns a data point with the specified \a sortKey. All other members are set to zero.
  22098. For a general explanation of what this method is good for in the context of the data container,
  22099. see the documentation of \ref QCPDataContainer.
  22100. */
  22101. /*! \fn static static bool QCPFinancialData::sortKeyIsMainKey()
  22102. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  22103. this method returns true.
  22104. For a general explanation of what this method is good for in the context of the data container,
  22105. see the documentation of \ref QCPDataContainer.
  22106. */
  22107. /*! \fn double QCPFinancialData::mainKey() const
  22108. Returns the \a key member of this data point.
  22109. For a general explanation of what this method is good for in the context of the data container,
  22110. see the documentation of \ref QCPDataContainer.
  22111. */
  22112. /*! \fn double QCPFinancialData::mainValue() const
  22113. Returns the \a open member of this data point.
  22114. For a general explanation of what this method is good for in the context of the data container,
  22115. see the documentation of \ref QCPDataContainer.
  22116. */
  22117. /*! \fn QCPRange QCPFinancialData::valueRange() const
  22118. Returns a QCPRange spanning from the \a low to the \a high value of this data point.
  22119. For a general explanation of what this method is good for in the context of the data container,
  22120. see the documentation of \ref QCPDataContainer.
  22121. */
  22122. /* end documentation of inline functions */
  22123. /*!
  22124. Constructs a data point with key and all values set to zero.
  22125. */
  22126. QCPFinancialData::QCPFinancialData() :
  22127. key(0),
  22128. open(0),
  22129. high(0),
  22130. low(0),
  22131. close(0)
  22132. {
  22133. }
  22134. /*!
  22135. Constructs a data point with the specified \a key and OHLC values.
  22136. */
  22137. QCPFinancialData::QCPFinancialData(double key, double open, double high, double low, double close) :
  22138. key(key),
  22139. open(open),
  22140. high(high),
  22141. low(low),
  22142. close(close)
  22143. {
  22144. }
  22145. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22146. //////////////////// QCPFinancial
  22147. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22148. /*! \class QCPFinancial
  22149. \brief A plottable representing a financial stock chart
  22150. \image html QCPFinancial.png
  22151. This plottable represents time series data binned to certain intervals, mainly used for stock
  22152. charts. The two common representations OHLC (Open-High-Low-Close) bars and Candlesticks can be
  22153. set via \ref setChartStyle.
  22154. The data is passed via \ref setData as a set of open/high/low/close values at certain keys
  22155. (typically times). This means the data must be already binned appropriately. If data is only
  22156. available as a series of values (e.g. \a price against \a time), you can use the static
  22157. convenience function \ref timeSeriesToOhlc to generate binned OHLC-data which can then be passed
  22158. to \ref setData.
  22159. The width of the OHLC bars/candlesticks can be controlled with \ref setWidth and \ref
  22160. setWidthType. A typical choice is to set the width type to \ref wtPlotCoords (the default) and
  22161. the width to (or slightly less than) one time bin interval width.
  22162. \section qcpfinancial-appearance Changing the appearance
  22163. Charts can be either single- or two-colored (\ref setTwoColored). If set to be single-colored,
  22164. lines are drawn with the plottable's pen (\ref setPen) and fills with the brush (\ref setBrush).
  22165. If set to two-colored, positive changes of the value during an interval (\a close >= \a open) are
  22166. represented with a different pen and brush than negative changes (\a close < \a open). These can
  22167. be configured with \ref setPenPositive, \ref setPenNegative, \ref setBrushPositive, and \ref
  22168. setBrushNegative. In two-colored mode, the normal plottable pen/brush is ignored. Upon selection
  22169. however, the normal selected pen/brush (provided by the \ref selectionDecorator) is used,
  22170. irrespective of whether the chart is single- or two-colored.
  22171. \section qcpfinancial-usage Usage
  22172. Like all data representing objects in QCustomPlot, the QCPFinancial is a plottable
  22173. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  22174. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  22175. Usually, you first create an instance:
  22176. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-creation-1
  22177. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot
  22178. instance takes ownership of the plottable, so do not delete it manually but use
  22179. QCustomPlot::removePlottable() instead. The newly created plottable can be modified, e.g.:
  22180. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-creation-2
  22181. Here we have used the static helper method \ref timeSeriesToOhlc, to turn a time-price data
  22182. series into a 24-hour binned open-high-low-close data series as QCPFinancial uses.
  22183. */
  22184. /* start of documentation of inline functions */
  22185. /*! \fn QCPFinancialDataContainer *QCPFinancial::data() const
  22186. Returns a pointer to the internal data storage of type \ref QCPFinancialDataContainer. You may
  22187. use it to directly manipulate the data, which may be more convenient and faster than using the
  22188. regular \ref setData or \ref addData methods, in certain situations.
  22189. */
  22190. /* end of documentation of inline functions */
  22191. /*!
  22192. Constructs a financial chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  22193. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  22194. the same orientation. If either of these restrictions is violated, a corresponding message is
  22195. printed to the debug output (qDebug), the construction is not aborted, though.
  22196. The created QCPFinancial is automatically registered with the QCustomPlot instance inferred from \a
  22197. keyAxis. This QCustomPlot instance takes ownership of the QCPFinancial, so do not delete it manually
  22198. but use QCustomPlot::removePlottable() instead.
  22199. */
  22200. QCPFinancial::QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  22201. QCPAbstractPlottable1D<QCPFinancialData>(keyAxis, valueAxis),
  22202. mChartStyle(csCandlestick),
  22203. mWidth(0.5),
  22204. mWidthType(wtPlotCoords),
  22205. mTwoColored(true),
  22206. mBrushPositive(QBrush(QColor(50, 160, 0))),
  22207. mBrushNegative(QBrush(QColor(180, 0, 15))),
  22208. mPenPositive(QPen(QColor(40, 150, 0))),
  22209. mPenNegative(QPen(QColor(170, 5, 5)))
  22210. {
  22211. mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255)));
  22212. }
  22213. QCPFinancial::~QCPFinancial()
  22214. {
  22215. }
  22216. /*! \overload
  22217. Replaces the current data container with the provided \a data container.
  22218. Since a QSharedPointer is used, multiple QCPFinancials may share the same data container safely.
  22219. Modifying the data in the container will then affect all financials that share the container.
  22220. Sharing can be achieved by simply exchanging the data containers wrapped in shared pointers:
  22221. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-datasharing-1
  22222. If you do not wish to share containers, but create a copy from an existing container, rather use
  22223. the \ref QCPDataContainer<DataType>::set method on the financial's data container directly:
  22224. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-datasharing-2
  22225. \see addData, timeSeriesToOhlc
  22226. */
  22227. void QCPFinancial::setData(QSharedPointer<QCPFinancialDataContainer> data)
  22228. {
  22229. mDataContainer = data;
  22230. }
  22231. /*! \overload
  22232. Replaces the current data with the provided points in \a keys, \a open, \a high, \a low and \a
  22233. close. The provided vectors should have equal length. Else, the number of added points will be
  22234. the size of the smallest vector.
  22235. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  22236. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  22237. \see addData, timeSeriesToOhlc
  22238. */
  22239. 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)
  22240. {
  22241. mDataContainer->clear();
  22242. addData(keys, open, high, low, close, alreadySorted);
  22243. }
  22244. /*!
  22245. Sets which representation style shall be used to display the OHLC data.
  22246. */
  22247. void QCPFinancial::setChartStyle(QCPFinancial::ChartStyle style)
  22248. {
  22249. mChartStyle = style;
  22250. }
  22251. /*!
  22252. Sets the width of the individual bars/candlesticks to \a width in plot key coordinates.
  22253. A typical choice is to set it to (or slightly less than) one bin interval width.
  22254. */
  22255. void QCPFinancial::setWidth(double width)
  22256. {
  22257. mWidth = width;
  22258. }
  22259. /*!
  22260. Sets how the width of the financial bars is defined. See the documentation of \ref WidthType for
  22261. an explanation of the possible values for \a widthType.
  22262. The default value is \ref wtPlotCoords.
  22263. \see setWidth
  22264. */
  22265. void QCPFinancial::setWidthType(QCPFinancial::WidthType widthType)
  22266. {
  22267. mWidthType = widthType;
  22268. }
  22269. /*!
  22270. Sets whether this chart shall contrast positive from negative trends per data point by using two
  22271. separate colors to draw the respective bars/candlesticks.
  22272. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  22273. setBrush).
  22274. \see setPenPositive, setPenNegative, setBrushPositive, setBrushNegative
  22275. */
  22276. void QCPFinancial::setTwoColored(bool twoColored)
  22277. {
  22278. mTwoColored = twoColored;
  22279. }
  22280. /*!
  22281. If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
  22282. of data points with a positive trend (i.e. bars/candlesticks with close >= open).
  22283. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  22284. setBrush).
  22285. \see setBrushNegative, setPenPositive, setPenNegative
  22286. */
  22287. void QCPFinancial::setBrushPositive(const QBrush &brush)
  22288. {
  22289. mBrushPositive = brush;
  22290. }
  22291. /*!
  22292. If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
  22293. of data points with a negative trend (i.e. bars/candlesticks with close < open).
  22294. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  22295. setBrush).
  22296. \see setBrushPositive, setPenNegative, setPenPositive
  22297. */
  22298. void QCPFinancial::setBrushNegative(const QBrush &brush)
  22299. {
  22300. mBrushNegative = brush;
  22301. }
  22302. /*!
  22303. If \ref setTwoColored is set to true, this function controls the pen that is used to draw
  22304. outlines of data points with a positive trend (i.e. bars/candlesticks with close >= open).
  22305. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  22306. setBrush).
  22307. \see setPenNegative, setBrushPositive, setBrushNegative
  22308. */
  22309. void QCPFinancial::setPenPositive(const QPen &pen)
  22310. {
  22311. mPenPositive = pen;
  22312. }
  22313. /*!
  22314. If \ref setTwoColored is set to true, this function controls the pen that is used to draw
  22315. outlines of data points with a negative trend (i.e. bars/candlesticks with close < open).
  22316. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  22317. setBrush).
  22318. \see setPenPositive, setBrushNegative, setBrushPositive
  22319. */
  22320. void QCPFinancial::setPenNegative(const QPen &pen)
  22321. {
  22322. mPenNegative = pen;
  22323. }
  22324. /*! \overload
  22325. Adds the provided points in \a keys, \a open, \a high, \a low and \a close to the current data.
  22326. The provided vectors should have equal length. Else, the number of added points will be the size
  22327. of the smallest vector.
  22328. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  22329. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  22330. Alternatively, you can also access and modify the data directly via the \ref data method, which
  22331. returns a pointer to the internal data container.
  22332. \see timeSeriesToOhlc
  22333. */
  22334. 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)
  22335. {
  22336. if (keys.size() != open.size() || open.size() != high.size() || high.size() != low.size() || low.size() != close.size() || close.size() != keys.size())
  22337. qDebug() << Q_FUNC_INFO << "keys, open, high, low, close have different sizes:" << keys.size() << open.size() << high.size() << low.size() << close.size();
  22338. const int n = qMin(keys.size(), qMin(open.size(), qMin(high.size(), qMin(low.size(), close.size()))));
  22339. QVector<QCPFinancialData> tempData(n);
  22340. QVector<QCPFinancialData>::iterator it = tempData.begin();
  22341. const QVector<QCPFinancialData>::iterator itEnd = tempData.end();
  22342. int i = 0;
  22343. while (it != itEnd)
  22344. {
  22345. it->key = keys[i];
  22346. it->open = open[i];
  22347. it->high = high[i];
  22348. it->low = low[i];
  22349. it->close = close[i];
  22350. ++it;
  22351. ++i;
  22352. }
  22353. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  22354. }
  22355. /*! \overload
  22356. Adds the provided data point as \a key, \a open, \a high, \a low and \a close to the current
  22357. data.
  22358. Alternatively, you can also access and modify the data directly via the \ref data method, which
  22359. returns a pointer to the internal data container.
  22360. \see timeSeriesToOhlc
  22361. */
  22362. void QCPFinancial::addData(double key, double open, double high, double low, double close)
  22363. {
  22364. mDataContainer->add(QCPFinancialData(key, open, high, low, close));
  22365. }
  22366. /*!
  22367. \copydoc QCPPlottableInterface1D::selectTestRect
  22368. */
  22369. QCPDataSelection QCPFinancial::selectTestRect(const QRectF &rect, bool onlySelectable) const
  22370. {
  22371. QCPDataSelection result;
  22372. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  22373. return result;
  22374. if (!mKeyAxis || !mValueAxis)
  22375. return result;
  22376. QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
  22377. getVisibleDataBounds(visibleBegin, visibleEnd);
  22378. for (QCPFinancialDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  22379. {
  22380. if (rect.intersects(selectionHitBox(it)))
  22381. result.addDataRange(QCPDataRange(it-mDataContainer->constBegin(), it-mDataContainer->constBegin()+1), false);
  22382. }
  22383. result.simplify();
  22384. return result;
  22385. }
  22386. /* inherits documentation from base class */
  22387. double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  22388. {
  22389. Q_UNUSED(details)
  22390. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  22391. return -1;
  22392. if (!mKeyAxis || !mValueAxis)
  22393. return -1;
  22394. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
  22395. {
  22396. // get visible data range:
  22397. QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
  22398. QCPFinancialDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  22399. getVisibleDataBounds(visibleBegin, visibleEnd);
  22400. // perform select test according to configured style:
  22401. double result = -1;
  22402. switch (mChartStyle)
  22403. {
  22404. case QCPFinancial::csOhlc:
  22405. result = ohlcSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break;
  22406. case QCPFinancial::csCandlestick:
  22407. result = candlestickSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break;
  22408. }
  22409. if (details)
  22410. {
  22411. int pointIndex = closestDataPoint-mDataContainer->constBegin();
  22412. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  22413. }
  22414. return result;
  22415. }
  22416. return -1;
  22417. }
  22418. /* inherits documentation from base class */
  22419. QCPRange QCPFinancial::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  22420. {
  22421. QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain);
  22422. // determine exact range by including width of bars/flags:
  22423. if (foundRange)
  22424. {
  22425. if (inSignDomain != QCP::sdPositive || range.lower-mWidth*0.5 > 0)
  22426. range.lower -= mWidth*0.5;
  22427. if (inSignDomain != QCP::sdNegative || range.upper+mWidth*0.5 < 0)
  22428. range.upper += mWidth*0.5;
  22429. }
  22430. return range;
  22431. }
  22432. /* inherits documentation from base class */
  22433. QCPRange QCPFinancial::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  22434. {
  22435. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  22436. }
  22437. /*!
  22438. A convenience function that converts time series data (\a value against \a time) to OHLC binned
  22439. data points. The return value can then be passed on to \ref QCPFinancialDataContainer::set(const
  22440. QCPFinancialDataContainer&).
  22441. The size of the bins can be controlled with \a timeBinSize in the same units as \a time is given.
  22442. For example, if the unit of \a time is seconds and single OHLC/Candlesticks should span an hour
  22443. each, set \a timeBinSize to 3600.
  22444. \a timeBinOffset allows to control precisely at what \a time coordinate a bin should start. The
  22445. value passed as \a timeBinOffset doesn't need to be in the range encompassed by the \a time keys.
  22446. It merely defines the mathematical offset/phase of the bins that will be used to process the
  22447. data.
  22448. */
  22449. QCPFinancialDataContainer QCPFinancial::timeSeriesToOhlc(const QVector<double> &time, const QVector<double> &value, double timeBinSize, double timeBinOffset)
  22450. {
  22451. QCPFinancialDataContainer data;
  22452. int count = qMin(time.size(), value.size());
  22453. if (count == 0)
  22454. return QCPFinancialDataContainer();
  22455. QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first());
  22456. int currentBinIndex = qFloor((time.first()-timeBinOffset)/timeBinSize+0.5);
  22457. for (int i=0; i<count; ++i)
  22458. {
  22459. int index = qFloor((time.at(i)-timeBinOffset)/timeBinSize+0.5);
  22460. if (currentBinIndex == index) // data point still in current bin, extend high/low:
  22461. {
  22462. if (value.at(i) < currentBinData.low) currentBinData.low = value.at(i);
  22463. if (value.at(i) > currentBinData.high) currentBinData.high = value.at(i);
  22464. if (i == count-1) // last data point is in current bin, finalize bin:
  22465. {
  22466. currentBinData.close = value.at(i);
  22467. currentBinData.key = timeBinOffset+(index)*timeBinSize;
  22468. data.add(currentBinData);
  22469. }
  22470. } else // data point not anymore in current bin, set close of old and open of new bin, and add old to map:
  22471. {
  22472. // finalize current bin:
  22473. currentBinData.close = value.at(i-1);
  22474. currentBinData.key = timeBinOffset+(index-1)*timeBinSize;
  22475. data.add(currentBinData);
  22476. // start next bin:
  22477. currentBinIndex = index;
  22478. currentBinData.open = value.at(i);
  22479. currentBinData.high = value.at(i);
  22480. currentBinData.low = value.at(i);
  22481. }
  22482. }
  22483. return data;
  22484. }
  22485. /* inherits documentation from base class */
  22486. void QCPFinancial::draw(QCPPainter *painter)
  22487. {
  22488. // get visible data range:
  22489. QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
  22490. getVisibleDataBounds(visibleBegin, visibleEnd);
  22491. // loop over and draw segments of unselected/selected data:
  22492. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  22493. getDataSegments(selectedSegments, unselectedSegments);
  22494. allSegments << unselectedSegments << selectedSegments;
  22495. for (int i=0; i<allSegments.size(); ++i)
  22496. {
  22497. bool isSelectedSegment = i >= unselectedSegments.size();
  22498. QCPFinancialDataContainer::const_iterator begin = visibleBegin;
  22499. QCPFinancialDataContainer::const_iterator end = visibleEnd;
  22500. mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
  22501. if (begin == end)
  22502. continue;
  22503. // draw data segment according to configured style:
  22504. switch (mChartStyle)
  22505. {
  22506. case QCPFinancial::csOhlc:
  22507. drawOhlcPlot(painter, begin, end, isSelectedSegment); break;
  22508. case QCPFinancial::csCandlestick:
  22509. drawCandlestickPlot(painter, begin, end, isSelectedSegment); break;
  22510. }
  22511. }
  22512. // draw other selection decoration that isn't just line/scatter pens and brushes:
  22513. if (mSelectionDecorator)
  22514. mSelectionDecorator->drawDecoration(painter, selection());
  22515. }
  22516. /* inherits documentation from base class */
  22517. void QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  22518. {
  22519. painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing
  22520. if (mChartStyle == csOhlc)
  22521. {
  22522. if (mTwoColored)
  22523. {
  22524. // draw upper left half icon with positive color:
  22525. painter->setBrush(mBrushPositive);
  22526. painter->setPen(mPenPositive);
  22527. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint()));
  22528. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  22529. painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
  22530. painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
  22531. // draw bottom right half icon with negative color:
  22532. painter->setBrush(mBrushNegative);
  22533. painter->setPen(mPenNegative);
  22534. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint()));
  22535. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  22536. painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
  22537. painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
  22538. } else
  22539. {
  22540. painter->setBrush(mBrush);
  22541. painter->setPen(mPen);
  22542. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  22543. painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
  22544. painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
  22545. }
  22546. } else if (mChartStyle == csCandlestick)
  22547. {
  22548. if (mTwoColored)
  22549. {
  22550. // draw upper left half icon with positive color:
  22551. painter->setBrush(mBrushPositive);
  22552. painter->setPen(mPenPositive);
  22553. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint()));
  22554. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
  22555. painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  22556. painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
  22557. // draw bottom right half icon with negative color:
  22558. painter->setBrush(mBrushNegative);
  22559. painter->setPen(mPenNegative);
  22560. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint()));
  22561. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
  22562. painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  22563. painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
  22564. } else
  22565. {
  22566. painter->setBrush(mBrush);
  22567. painter->setPen(mPen);
  22568. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
  22569. painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  22570. painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
  22571. }
  22572. }
  22573. }
  22574. /*! \internal
  22575. Draws the data from \a begin to \a end-1 as OHLC bars with the provided \a painter.
  22576. This method is a helper function for \ref draw. It is used when the chart style is \ref csOhlc.
  22577. */
  22578. void QCPFinancial::drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected)
  22579. {
  22580. QCPAxis *keyAxis = mKeyAxis.data();
  22581. QCPAxis *valueAxis = mValueAxis.data();
  22582. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  22583. if (keyAxis->orientation() == Qt::Horizontal)
  22584. {
  22585. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  22586. {
  22587. if (isSelected && mSelectionDecorator)
  22588. mSelectionDecorator->applyPen(painter);
  22589. else if (mTwoColored)
  22590. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  22591. else
  22592. painter->setPen(mPen);
  22593. double keyPixel = keyAxis->coordToPixel(it->key);
  22594. double openPixel = valueAxis->coordToPixel(it->open);
  22595. double closePixel = valueAxis->coordToPixel(it->close);
  22596. // draw backbone:
  22597. painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(it->low)));
  22598. // draw open:
  22599. double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides
  22600. painter->drawLine(QPointF(keyPixel-pixelWidth, openPixel), QPointF(keyPixel, openPixel));
  22601. // draw close:
  22602. painter->drawLine(QPointF(keyPixel, closePixel), QPointF(keyPixel+pixelWidth, closePixel));
  22603. }
  22604. } else
  22605. {
  22606. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  22607. {
  22608. if (isSelected && mSelectionDecorator)
  22609. mSelectionDecorator->applyPen(painter);
  22610. else if (mTwoColored)
  22611. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  22612. else
  22613. painter->setPen(mPen);
  22614. double keyPixel = keyAxis->coordToPixel(it->key);
  22615. double openPixel = valueAxis->coordToPixel(it->open);
  22616. double closePixel = valueAxis->coordToPixel(it->close);
  22617. // draw backbone:
  22618. painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(it->low), keyPixel));
  22619. // draw open:
  22620. double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides
  22621. painter->drawLine(QPointF(openPixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel));
  22622. // draw close:
  22623. painter->drawLine(QPointF(closePixel, keyPixel), QPointF(closePixel, keyPixel+pixelWidth));
  22624. }
  22625. }
  22626. }
  22627. /*! \internal
  22628. Draws the data from \a begin to \a end-1 as Candlesticks with the provided \a painter.
  22629. This method is a helper function for \ref draw. It is used when the chart style is \ref csCandlestick.
  22630. */
  22631. void QCPFinancial::drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected)
  22632. {
  22633. QCPAxis *keyAxis = mKeyAxis.data();
  22634. QCPAxis *valueAxis = mValueAxis.data();
  22635. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  22636. if (keyAxis->orientation() == Qt::Horizontal)
  22637. {
  22638. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  22639. {
  22640. if (isSelected && mSelectionDecorator)
  22641. {
  22642. mSelectionDecorator->applyPen(painter);
  22643. mSelectionDecorator->applyBrush(painter);
  22644. } else if (mTwoColored)
  22645. {
  22646. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  22647. painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative);
  22648. } else
  22649. {
  22650. painter->setPen(mPen);
  22651. painter->setBrush(mBrush);
  22652. }
  22653. double keyPixel = keyAxis->coordToPixel(it->key);
  22654. double openPixel = valueAxis->coordToPixel(it->open);
  22655. double closePixel = valueAxis->coordToPixel(it->close);
  22656. // draw high:
  22657. painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close))));
  22658. // draw low:
  22659. painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close))));
  22660. // draw open-close box:
  22661. double pixelWidth = getPixelWidth(it->key, keyPixel);
  22662. painter->drawRect(QRectF(QPointF(keyPixel-pixelWidth, closePixel), QPointF(keyPixel+pixelWidth, openPixel)));
  22663. }
  22664. } else // keyAxis->orientation() == Qt::Vertical
  22665. {
  22666. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  22667. {
  22668. if (isSelected && mSelectionDecorator)
  22669. {
  22670. mSelectionDecorator->applyPen(painter);
  22671. mSelectionDecorator->applyBrush(painter);
  22672. } else if (mTwoColored)
  22673. {
  22674. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  22675. painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative);
  22676. } else
  22677. {
  22678. painter->setPen(mPen);
  22679. painter->setBrush(mBrush);
  22680. }
  22681. double keyPixel = keyAxis->coordToPixel(it->key);
  22682. double openPixel = valueAxis->coordToPixel(it->open);
  22683. double closePixel = valueAxis->coordToPixel(it->close);
  22684. // draw high:
  22685. painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel));
  22686. // draw low:
  22687. painter->drawLine(QPointF(valueAxis->coordToPixel(it->low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel));
  22688. // draw open-close box:
  22689. double pixelWidth = getPixelWidth(it->key, keyPixel);
  22690. painter->drawRect(QRectF(QPointF(closePixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel+pixelWidth)));
  22691. }
  22692. }
  22693. }
  22694. /*! \internal
  22695. This function is used to determine the width of the bar at coordinate \a key, according to the
  22696. specified width (\ref setWidth) and width type (\ref setWidthType). Provide the pixel position of
  22697. \a key in \a keyPixel (because usually this was already calculated via \ref QCPAxis::coordToPixel
  22698. when this function is called).
  22699. It returns the number of pixels the bar extends to higher keys, relative to the \a key
  22700. coordinate. So with a non-reversed horizontal axis, the return value is positive. With a reversed
  22701. horizontal axis, the return value is negative. This is important so the open/close flags on the
  22702. \ref csOhlc bar are drawn to the correct side.
  22703. */
  22704. double QCPFinancial::getPixelWidth(double key, double keyPixel) const
  22705. {
  22706. double result = 0;
  22707. switch (mWidthType)
  22708. {
  22709. case wtAbsolute:
  22710. {
  22711. if (mKeyAxis)
  22712. result = mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  22713. break;
  22714. }
  22715. case wtAxisRectRatio:
  22716. {
  22717. if (mKeyAxis && mKeyAxis.data()->axisRect())
  22718. {
  22719. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  22720. result = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  22721. else
  22722. result = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  22723. } else
  22724. qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined";
  22725. break;
  22726. }
  22727. case wtPlotCoords:
  22728. {
  22729. if (mKeyAxis)
  22730. result = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel;
  22731. else
  22732. qDebug() << Q_FUNC_INFO << "No key axis defined";
  22733. break;
  22734. }
  22735. }
  22736. return result;
  22737. }
  22738. /*! \internal
  22739. This method is a helper function for \ref selectTest. It is used to test for selection when the
  22740. chart style is \ref csOhlc. It only tests against the data points between \a begin and \a end.
  22741. Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical
  22742. representation of the plottable, and \a closestDataPoint will point to the respective data point.
  22743. */
  22744. double QCPFinancial::ohlcSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const
  22745. {
  22746. closestDataPoint = mDataContainer->constEnd();
  22747. QCPAxis *keyAxis = mKeyAxis.data();
  22748. QCPAxis *valueAxis = mValueAxis.data();
  22749. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  22750. double minDistSqr = std::numeric_limits<double>::max();
  22751. if (keyAxis->orientation() == Qt::Horizontal)
  22752. {
  22753. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  22754. {
  22755. double keyPixel = keyAxis->coordToPixel(it->key);
  22756. // calculate distance to backbone:
  22757. double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low)));
  22758. if (currentDistSqr < minDistSqr)
  22759. {
  22760. minDistSqr = currentDistSqr;
  22761. closestDataPoint = it;
  22762. }
  22763. }
  22764. } else // keyAxis->orientation() == Qt::Vertical
  22765. {
  22766. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  22767. {
  22768. double keyPixel = keyAxis->coordToPixel(it->key);
  22769. // calculate distance to backbone:
  22770. double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel));
  22771. if (currentDistSqr < minDistSqr)
  22772. {
  22773. minDistSqr = currentDistSqr;
  22774. closestDataPoint = it;
  22775. }
  22776. }
  22777. }
  22778. return qSqrt(minDistSqr);
  22779. }
  22780. /*! \internal
  22781. This method is a helper function for \ref selectTest. It is used to test for selection when the
  22782. chart style is \ref csCandlestick. It only tests against the data points between \a begin and \a
  22783. end.
  22784. Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical
  22785. representation of the plottable, and \a closestDataPoint will point to the respective data point.
  22786. */
  22787. double QCPFinancial::candlestickSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const
  22788. {
  22789. closestDataPoint = mDataContainer->constEnd();
  22790. QCPAxis *keyAxis = mKeyAxis.data();
  22791. QCPAxis *valueAxis = mValueAxis.data();
  22792. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  22793. double minDistSqr = std::numeric_limits<double>::max();
  22794. if (keyAxis->orientation() == Qt::Horizontal)
  22795. {
  22796. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  22797. {
  22798. double currentDistSqr;
  22799. // determine whether pos is in open-close-box:
  22800. QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5);
  22801. QCPRange boxValueRange(it->close, it->open);
  22802. double posKey, posValue;
  22803. pixelsToCoords(pos, posKey, posValue);
  22804. if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box
  22805. {
  22806. currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
  22807. } else
  22808. {
  22809. // calculate distance to high/low lines:
  22810. double keyPixel = keyAxis->coordToPixel(it->key);
  22811. double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close))));
  22812. double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close))));
  22813. currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
  22814. }
  22815. if (currentDistSqr < minDistSqr)
  22816. {
  22817. minDistSqr = currentDistSqr;
  22818. closestDataPoint = it;
  22819. }
  22820. }
  22821. } else // keyAxis->orientation() == Qt::Vertical
  22822. {
  22823. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  22824. {
  22825. double currentDistSqr;
  22826. // determine whether pos is in open-close-box:
  22827. QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5);
  22828. QCPRange boxValueRange(it->close, it->open);
  22829. double posKey, posValue;
  22830. pixelsToCoords(pos, posKey, posValue);
  22831. if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box
  22832. {
  22833. currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
  22834. } else
  22835. {
  22836. // calculate distance to high/low lines:
  22837. double keyPixel = keyAxis->coordToPixel(it->key);
  22838. double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel));
  22839. double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel));
  22840. currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
  22841. }
  22842. if (currentDistSqr < minDistSqr)
  22843. {
  22844. minDistSqr = currentDistSqr;
  22845. closestDataPoint = it;
  22846. }
  22847. }
  22848. }
  22849. return qSqrt(minDistSqr);
  22850. }
  22851. /*! \internal
  22852. called by the drawing methods to determine which data (key) range is visible at the current key
  22853. axis range setting, so only that needs to be processed.
  22854. \a begin returns an iterator to the lowest data point that needs to be taken into account when
  22855. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  22856. begin may still be just outside the visible range.
  22857. \a end returns the iterator just above the highest data point that needs to be taken into
  22858. account. Same as before, \a end may also lie just outside of the visible range
  22859. if the plottable contains no data, both \a begin and \a end point to \c constEnd.
  22860. */
  22861. void QCPFinancial::getVisibleDataBounds(QCPFinancialDataContainer::const_iterator &begin, QCPFinancialDataContainer::const_iterator &end) const
  22862. {
  22863. if (!mKeyAxis)
  22864. {
  22865. qDebug() << Q_FUNC_INFO << "invalid key axis";
  22866. begin = mDataContainer->constEnd();
  22867. end = mDataContainer->constEnd();
  22868. return;
  22869. }
  22870. begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of ohlc/candlestick to include partially visible data points
  22871. end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of ohlc/candlestick to include partially visible data points
  22872. }
  22873. /*! \internal
  22874. Returns the hit box in pixel coordinates that will be used for data selection with the selection
  22875. rect (\ref selectTestRect), of the data point given by \a it.
  22876. */
  22877. QRectF QCPFinancial::selectionHitBox(QCPFinancialDataContainer::const_iterator it) const
  22878. {
  22879. QCPAxis *keyAxis = mKeyAxis.data();
  22880. QCPAxis *valueAxis = mValueAxis.data();
  22881. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QRectF(); }
  22882. double keyPixel = keyAxis->coordToPixel(it->key);
  22883. double highPixel = valueAxis->coordToPixel(it->high);
  22884. double lowPixel = valueAxis->coordToPixel(it->low);
  22885. double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it->key-mWidth*0.5);
  22886. if (keyAxis->orientation() == Qt::Horizontal)
  22887. return QRectF(keyPixel-keyWidthPixels, highPixel, keyWidthPixels*2, lowPixel-highPixel).normalized();
  22888. else
  22889. return QRectF(highPixel, keyPixel-keyWidthPixels, lowPixel-highPixel, keyWidthPixels*2).normalized();
  22890. }
  22891. /* end of 'src/plottables/plottable-financial.cpp' */
  22892. /* including file 'src/plottables/plottable-errorbar.cpp', size 37355 */
  22893. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  22894. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22895. //////////////////// QCPErrorBarsData
  22896. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22897. /*! \class QCPErrorBarsData
  22898. \brief Holds the data of one single error bar for QCPErrorBars.
  22899. The stored data is:
  22900. \li \a errorMinus: how much the error bar extends towards negative coordinates from the data
  22901. point position
  22902. \li \a errorPlus: how much the error bar extends towards positive coordinates from the data point
  22903. position
  22904. The container for storing the error bar information is \ref QCPErrorBarsDataContainer. It is a
  22905. typedef for <tt>QVector<\ref QCPErrorBarsData></tt>.
  22906. \see QCPErrorBarsDataContainer
  22907. */
  22908. /*!
  22909. Constructs an error bar with errors set to zero.
  22910. */
  22911. QCPErrorBarsData::QCPErrorBarsData() :
  22912. errorMinus(0),
  22913. errorPlus(0)
  22914. {
  22915. }
  22916. /*!
  22917. Constructs an error bar with equal \a error in both negative and positive direction.
  22918. */
  22919. QCPErrorBarsData::QCPErrorBarsData(double error) :
  22920. errorMinus(error),
  22921. errorPlus(error)
  22922. {
  22923. }
  22924. /*!
  22925. Constructs an error bar with negative and positive errors set to \a errorMinus and \a errorPlus,
  22926. respectively.
  22927. */
  22928. QCPErrorBarsData::QCPErrorBarsData(double errorMinus, double errorPlus) :
  22929. errorMinus(errorMinus),
  22930. errorPlus(errorPlus)
  22931. {
  22932. }
  22933. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22934. //////////////////// QCPErrorBars
  22935. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22936. /*! \class QCPErrorBars
  22937. \brief A plottable that adds a set of error bars to other plottables.
  22938. \image html QCPErrorBars.png
  22939. The \ref QCPErrorBars plottable can be attached to other one-dimensional plottables (e.g. \ref
  22940. QCPGraph, \ref QCPCurve, \ref QCPBars, etc.) and equips them with error bars.
  22941. Use \ref setDataPlottable to define for which plottable the \ref QCPErrorBars shall display the
  22942. error bars. The orientation of the error bars can be controlled with \ref setErrorType.
  22943. By using \ref setData, you can supply the actual error data, either as symmetric error or
  22944. plus/minus asymmetric errors. \ref QCPErrorBars only stores the error data. The absolute
  22945. key/value position of each error bar will be adopted from the configured data plottable. The
  22946. error data of the \ref QCPErrorBars are associated one-to-one via their index to the data points
  22947. of the data plottable. You can directly access and manipulate the error bar data via \ref data.
  22948. Set either of the plus/minus errors to NaN (<tt>qQNaN()</tt> or
  22949. <tt>std::numeric_limits<double>::quiet_NaN()</tt>) to not show the respective error bar on the data point at
  22950. that index.
  22951. \section qcperrorbars-appearance Changing the appearance
  22952. The appearance of the error bars is defined by the pen (\ref setPen), and the width of the
  22953. whiskers (\ref setWhiskerWidth). Further, the error bar backbones may leave a gap around the data
  22954. point center to prevent that error bars are drawn too close to or even through scatter points.
  22955. This gap size can be controlled via \ref setSymbolGap.
  22956. */
  22957. /* start of documentation of inline functions */
  22958. /*! \fn QSharedPointer<QCPErrorBarsDataContainer> QCPErrorBars::data() const
  22959. Returns a shared pointer to the internal data storage of type \ref QCPErrorBarsDataContainer. You
  22960. may use it to directly manipulate the error values, which may be more convenient and faster than
  22961. using the regular \ref setData methods.
  22962. */
  22963. /* end of documentation of inline functions */
  22964. /*!
  22965. Constructs an error bars plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  22966. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  22967. the same orientation. If either of these restrictions is violated, a corresponding message is
  22968. printed to the debug output (qDebug), the construction is not aborted, though.
  22969. It is also important that the \a keyAxis and \a valueAxis are the same for the error bars
  22970. plottable and the data plottable that the error bars shall be drawn on (\ref setDataPlottable).
  22971. The created \ref QCPErrorBars is automatically registered with the QCustomPlot instance inferred
  22972. from \a keyAxis. This QCustomPlot instance takes ownership of the \ref QCPErrorBars, so do not
  22973. delete it manually but use \ref QCustomPlot::removePlottable() instead.
  22974. */
  22975. QCPErrorBars::QCPErrorBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  22976. QCPAbstractPlottable(keyAxis, valueAxis),
  22977. mDataContainer(new QVector<QCPErrorBarsData>),
  22978. mErrorType(etValueError),
  22979. mWhiskerWidth(9),
  22980. mSymbolGap(10)
  22981. {
  22982. setPen(QPen(Qt::black, 0));
  22983. setBrush(Qt::NoBrush);
  22984. }
  22985. QCPErrorBars::~QCPErrorBars()
  22986. {
  22987. }
  22988. /*! \overload
  22989. Replaces the current data container with the provided \a data container.
  22990. Since a QSharedPointer is used, multiple \ref QCPErrorBars instances may share the same data
  22991. container safely. Modifying the data in the container will then affect all \ref QCPErrorBars
  22992. instances that share the container. Sharing can be achieved by simply exchanging the data
  22993. containers wrapped in shared pointers:
  22994. \snippet documentation/doc-code-snippets/mainwindow.cpp qcperrorbars-datasharing-1
  22995. If you do not wish to share containers, but create a copy from an existing container, assign the
  22996. data containers directly:
  22997. \snippet documentation/doc-code-snippets/mainwindow.cpp qcperrorbars-datasharing-2
  22998. (This uses different notation compared with other plottables, because the \ref QCPErrorBars
  22999. uses a \c QVector<QCPErrorBarsData> as its data container, instead of a \ref QCPDataContainer.)
  23000. \see addData
  23001. */
  23002. void QCPErrorBars::setData(QSharedPointer<QCPErrorBarsDataContainer> data)
  23003. {
  23004. mDataContainer = data;
  23005. }
  23006. /*! \overload
  23007. Sets symmetrical error values as specified in \a error. The errors will be associated one-to-one
  23008. by the data point index to the associated data plottable (\ref setDataPlottable).
  23009. You can directly access and manipulate the error bar data via \ref data.
  23010. \see addData
  23011. */
  23012. void QCPErrorBars::setData(const QVector<double> &error)
  23013. {
  23014. mDataContainer->clear();
  23015. addData(error);
  23016. }
  23017. /*! \overload
  23018. Sets asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be
  23019. associated one-to-one by the data point index to the associated data plottable (\ref
  23020. setDataPlottable).
  23021. You can directly access and manipulate the error bar data via \ref data.
  23022. \see addData
  23023. */
  23024. void QCPErrorBars::setData(const QVector<double> &errorMinus, const QVector<double> &errorPlus)
  23025. {
  23026. mDataContainer->clear();
  23027. addData(errorMinus, errorPlus);
  23028. }
  23029. /*!
  23030. Sets the data plottable to which the error bars will be applied. The error values specified e.g.
  23031. via \ref setData will be associated one-to-one by the data point index to the data points of \a
  23032. plottable. This means that the error bars will adopt the key/value coordinates of the data point
  23033. with the same index.
  23034. The passed \a plottable must be a one-dimensional plottable, i.e. it must implement the \ref
  23035. QCPPlottableInterface1D. Further, it must not be a \ref QCPErrorBars instance itself. If either
  23036. of these restrictions is violated, a corresponding qDebug output is generated, and the data
  23037. plottable of this \ref QCPErrorBars instance is set to zero.
  23038. For proper display, care must also be taken that the key and value axes of the \a plottable match
  23039. those configured for this \ref QCPErrorBars instance.
  23040. */
  23041. void QCPErrorBars::setDataPlottable(QCPAbstractPlottable *plottable)
  23042. {
  23043. if (plottable && qobject_cast<QCPErrorBars*>(plottable))
  23044. {
  23045. mDataPlottable = 0;
  23046. qDebug() << Q_FUNC_INFO << "can't set another QCPErrorBars instance as data plottable";
  23047. return;
  23048. }
  23049. if (plottable && !plottable->interface1D())
  23050. {
  23051. mDataPlottable = 0;
  23052. qDebug() << Q_FUNC_INFO << "passed plottable doesn't implement 1d interface, can't associate with QCPErrorBars";
  23053. return;
  23054. }
  23055. mDataPlottable = plottable;
  23056. }
  23057. /*!
  23058. Sets in which orientation the error bars shall appear on the data points. If your data needs both
  23059. error dimensions, create two \ref QCPErrorBars with different \a type.
  23060. */
  23061. void QCPErrorBars::setErrorType(ErrorType type)
  23062. {
  23063. mErrorType = type;
  23064. }
  23065. /*!
  23066. Sets the width of the whiskers (the short bars at the end of the actual error bar backbones) to
  23067. \a pixels.
  23068. */
  23069. void QCPErrorBars::setWhiskerWidth(double pixels)
  23070. {
  23071. mWhiskerWidth = pixels;
  23072. }
  23073. /*!
  23074. Sets the gap diameter around the data points that will be left out when drawing the error bar
  23075. backbones. This gap prevents that error bars are drawn too close to or even through scatter
  23076. points.
  23077. */
  23078. void QCPErrorBars::setSymbolGap(double pixels)
  23079. {
  23080. mSymbolGap = pixels;
  23081. }
  23082. /*! \overload
  23083. Adds symmetrical error values as specified in \a error. The errors will be associated one-to-one
  23084. by the data point index to the associated data plottable (\ref setDataPlottable).
  23085. You can directly access and manipulate the error bar data via \ref data.
  23086. \see setData
  23087. */
  23088. void QCPErrorBars::addData(const QVector<double> &error)
  23089. {
  23090. addData(error, error);
  23091. }
  23092. /*! \overload
  23093. Adds asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be
  23094. associated one-to-one by the data point index to the associated data plottable (\ref
  23095. setDataPlottable).
  23096. You can directly access and manipulate the error bar data via \ref data.
  23097. \see setData
  23098. */
  23099. void QCPErrorBars::addData(const QVector<double> &errorMinus, const QVector<double> &errorPlus)
  23100. {
  23101. if (errorMinus.size() != errorPlus.size())
  23102. qDebug() << Q_FUNC_INFO << "minus and plus error vectors have different sizes:" << errorMinus.size() << errorPlus.size();
  23103. const int n = qMin(errorMinus.size(), errorPlus.size());
  23104. mDataContainer->reserve(n);
  23105. for (int i=0; i<n; ++i)
  23106. mDataContainer->append(QCPErrorBarsData(errorMinus.at(i), errorPlus.at(i)));
  23107. }
  23108. /*! \overload
  23109. Adds a single symmetrical error bar as specified in \a error. The errors will be associated
  23110. one-to-one by the data point index to the associated data plottable (\ref setDataPlottable).
  23111. You can directly access and manipulate the error bar data via \ref data.
  23112. \see setData
  23113. */
  23114. void QCPErrorBars::addData(double error)
  23115. {
  23116. mDataContainer->append(QCPErrorBarsData(error));
  23117. }
  23118. /*! \overload
  23119. Adds a single asymmetrical error bar as specified in \a errorMinus and \a errorPlus. The errors
  23120. will be associated one-to-one by the data point index to the associated data plottable (\ref
  23121. setDataPlottable).
  23122. You can directly access and manipulate the error bar data via \ref data.
  23123. \see setData
  23124. */
  23125. void QCPErrorBars::addData(double errorMinus, double errorPlus)
  23126. {
  23127. mDataContainer->append(QCPErrorBarsData(errorMinus, errorPlus));
  23128. }
  23129. /* inherits documentation from base class */
  23130. int QCPErrorBars::dataCount() const
  23131. {
  23132. return mDataContainer->size();
  23133. }
  23134. /* inherits documentation from base class */
  23135. double QCPErrorBars::dataMainKey(int index) const
  23136. {
  23137. if (mDataPlottable)
  23138. return mDataPlottable->interface1D()->dataMainKey(index);
  23139. else
  23140. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23141. return 0;
  23142. }
  23143. /* inherits documentation from base class */
  23144. double QCPErrorBars::dataSortKey(int index) const
  23145. {
  23146. if (mDataPlottable)
  23147. return mDataPlottable->interface1D()->dataSortKey(index);
  23148. else
  23149. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23150. return 0;
  23151. }
  23152. /* inherits documentation from base class */
  23153. double QCPErrorBars::dataMainValue(int index) const
  23154. {
  23155. if (mDataPlottable)
  23156. return mDataPlottable->interface1D()->dataMainValue(index);
  23157. else
  23158. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23159. return 0;
  23160. }
  23161. /* inherits documentation from base class */
  23162. QCPRange QCPErrorBars::dataValueRange(int index) const
  23163. {
  23164. if (mDataPlottable)
  23165. {
  23166. const double value = mDataPlottable->interface1D()->dataMainValue(index);
  23167. if (index >= 0 && index < mDataContainer->size() && mErrorType == etValueError)
  23168. return QCPRange(value-mDataContainer->at(index).errorMinus, value+mDataContainer->at(index).errorPlus);
  23169. else
  23170. return QCPRange(value, value);
  23171. } else
  23172. {
  23173. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23174. return QCPRange();
  23175. }
  23176. }
  23177. /* inherits documentation from base class */
  23178. QPointF QCPErrorBars::dataPixelPosition(int index) const
  23179. {
  23180. if (mDataPlottable)
  23181. return mDataPlottable->interface1D()->dataPixelPosition(index);
  23182. else
  23183. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23184. return QPointF();
  23185. }
  23186. /* inherits documentation from base class */
  23187. bool QCPErrorBars::sortKeyIsMainKey() const
  23188. {
  23189. if (mDataPlottable)
  23190. {
  23191. return mDataPlottable->interface1D()->sortKeyIsMainKey();
  23192. } else
  23193. {
  23194. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23195. return true;
  23196. }
  23197. }
  23198. /*!
  23199. \copydoc QCPPlottableInterface1D::selectTestRect
  23200. */
  23201. QCPDataSelection QCPErrorBars::selectTestRect(const QRectF &rect, bool onlySelectable) const
  23202. {
  23203. QCPDataSelection result;
  23204. if (!mDataPlottable)
  23205. return result;
  23206. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  23207. return result;
  23208. if (!mKeyAxis || !mValueAxis)
  23209. return result;
  23210. QCPErrorBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  23211. getVisibleDataBounds(visibleBegin, visibleEnd, QCPDataRange(0, dataCount()));
  23212. QVector<QLineF> backbones, whiskers;
  23213. for (QCPErrorBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  23214. {
  23215. backbones.clear();
  23216. whiskers.clear();
  23217. getErrorBarLines(it, backbones, whiskers);
  23218. for (int i=0; i<backbones.size(); ++i)
  23219. {
  23220. if (rectIntersectsLine(rect, backbones.at(i)))
  23221. {
  23222. result.addDataRange(QCPDataRange(it-mDataContainer->constBegin(), it-mDataContainer->constBegin()+1), false);
  23223. break;
  23224. }
  23225. }
  23226. }
  23227. result.simplify();
  23228. return result;
  23229. }
  23230. /* inherits documentation from base class */
  23231. int QCPErrorBars::findBegin(double sortKey, bool expandedRange) const
  23232. {
  23233. if (mDataPlottable)
  23234. {
  23235. if (mDataContainer->isEmpty())
  23236. return 0;
  23237. int beginIndex = mDataPlottable->interface1D()->findBegin(sortKey, expandedRange);
  23238. if (beginIndex >= mDataContainer->size())
  23239. beginIndex = mDataContainer->size()-1;
  23240. return beginIndex;
  23241. } else
  23242. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23243. return 0;
  23244. }
  23245. /* inherits documentation from base class */
  23246. int QCPErrorBars::findEnd(double sortKey, bool expandedRange) const
  23247. {
  23248. if (mDataPlottable)
  23249. {
  23250. if (mDataContainer->isEmpty())
  23251. return 0;
  23252. int endIndex = mDataPlottable->interface1D()->findEnd(sortKey, expandedRange);
  23253. if (endIndex > mDataContainer->size())
  23254. endIndex = mDataContainer->size();
  23255. return endIndex;
  23256. } else
  23257. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23258. return 0;
  23259. }
  23260. /* inherits documentation from base class */
  23261. double QCPErrorBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  23262. {
  23263. if (!mDataPlottable) return -1;
  23264. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  23265. return -1;
  23266. if (!mKeyAxis || !mValueAxis)
  23267. return -1;
  23268. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
  23269. {
  23270. QCPErrorBarsDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  23271. double result = pointDistance(pos, closestDataPoint);
  23272. if (details)
  23273. {
  23274. int pointIndex = closestDataPoint-mDataContainer->constBegin();
  23275. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  23276. }
  23277. return result;
  23278. } else
  23279. return -1;
  23280. }
  23281. /* inherits documentation from base class */
  23282. void QCPErrorBars::draw(QCPPainter *painter)
  23283. {
  23284. if (!mDataPlottable) return;
  23285. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  23286. if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
  23287. // if the sort key isn't the main key, we must check the visibility for each data point/error bar individually
  23288. // (getVisibleDataBounds applies range restriction, but otherwise can only return full data range):
  23289. bool checkPointVisibility = !mDataPlottable->interface1D()->sortKeyIsMainKey();
  23290. // check data validity if flag set:
  23291. #ifdef QCUSTOMPLOT_CHECK_DATA
  23292. QCPErrorBarsDataContainer::const_iterator it;
  23293. for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  23294. {
  23295. if (QCP::isInvalidData(it->errorMinus, it->errorPlus))
  23296. qDebug() << Q_FUNC_INFO << "Data point at index" << it-mDataContainer->constBegin() << "invalid." << "Plottable name:" << name();
  23297. }
  23298. #endif
  23299. applyDefaultAntialiasingHint(painter);
  23300. painter->setBrush(Qt::NoBrush);
  23301. // loop over and draw segments of unselected/selected data:
  23302. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  23303. getDataSegments(selectedSegments, unselectedSegments);
  23304. allSegments << unselectedSegments << selectedSegments;
  23305. QVector<QLineF> backbones, whiskers;
  23306. for (int i=0; i<allSegments.size(); ++i)
  23307. {
  23308. QCPErrorBarsDataContainer::const_iterator begin, end;
  23309. getVisibleDataBounds(begin, end, allSegments.at(i));
  23310. if (begin == end)
  23311. continue;
  23312. bool isSelectedSegment = i >= unselectedSegments.size();
  23313. if (isSelectedSegment && mSelectionDecorator)
  23314. mSelectionDecorator->applyPen(painter);
  23315. else
  23316. painter->setPen(mPen);
  23317. if (painter->pen().capStyle() == Qt::SquareCap)
  23318. {
  23319. QPen capFixPen(painter->pen());
  23320. capFixPen.setCapStyle(Qt::FlatCap);
  23321. painter->setPen(capFixPen);
  23322. }
  23323. backbones.clear();
  23324. whiskers.clear();
  23325. for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it)
  23326. {
  23327. if (!checkPointVisibility || errorBarVisible(it-mDataContainer->constBegin()))
  23328. getErrorBarLines(it, backbones, whiskers);
  23329. }
  23330. painter->drawLines(backbones);
  23331. painter->drawLines(whiskers);
  23332. }
  23333. // draw other selection decoration that isn't just line/scatter pens and brushes:
  23334. if (mSelectionDecorator)
  23335. mSelectionDecorator->drawDecoration(painter, selection());
  23336. }
  23337. /* inherits documentation from base class */
  23338. void QCPErrorBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  23339. {
  23340. applyDefaultAntialiasingHint(painter);
  23341. painter->setPen(mPen);
  23342. if (mErrorType == etValueError && mValueAxis && mValueAxis->orientation() == Qt::Vertical)
  23343. {
  23344. painter->drawLine(QLineF(rect.center().x(), rect.top()+2, rect.center().x(), rect.bottom()-1));
  23345. painter->drawLine(QLineF(rect.center().x()-4, rect.top()+2, rect.center().x()+4, rect.top()+2));
  23346. painter->drawLine(QLineF(rect.center().x()-4, rect.bottom()-1, rect.center().x()+4, rect.bottom()-1));
  23347. } else
  23348. {
  23349. painter->drawLine(QLineF(rect.left()+2, rect.center().y(), rect.right()-2, rect.center().y()));
  23350. painter->drawLine(QLineF(rect.left()+2, rect.center().y()-4, rect.left()+2, rect.center().y()+4));
  23351. painter->drawLine(QLineF(rect.right()-2, rect.center().y()-4, rect.right()-2, rect.center().y()+4));
  23352. }
  23353. }
  23354. /* inherits documentation from base class */
  23355. QCPRange QCPErrorBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  23356. {
  23357. if (!mDataPlottable)
  23358. {
  23359. foundRange = false;
  23360. return QCPRange();
  23361. }
  23362. QCPRange range;
  23363. bool haveLower = false;
  23364. bool haveUpper = false;
  23365. QCPErrorBarsDataContainer::const_iterator it;
  23366. for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  23367. {
  23368. if (mErrorType == etValueError)
  23369. {
  23370. // error bar doesn't extend in key dimension (except whisker but we ignore that here), so only use data point center
  23371. const double current = mDataPlottable->interface1D()->dataMainKey(it-mDataContainer->constBegin());
  23372. if (qIsNaN(current)) continue;
  23373. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  23374. {
  23375. if (current < range.lower || !haveLower)
  23376. {
  23377. range.lower = current;
  23378. haveLower = true;
  23379. }
  23380. if (current > range.upper || !haveUpper)
  23381. {
  23382. range.upper = current;
  23383. haveUpper = true;
  23384. }
  23385. }
  23386. } else // mErrorType == etKeyError
  23387. {
  23388. const double dataKey = mDataPlottable->interface1D()->dataMainKey(it-mDataContainer->constBegin());
  23389. if (qIsNaN(dataKey)) continue;
  23390. // plus error:
  23391. double current = dataKey + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus);
  23392. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  23393. {
  23394. if (current > range.upper || !haveUpper)
  23395. {
  23396. range.upper = current;
  23397. haveUpper = true;
  23398. }
  23399. }
  23400. // minus error:
  23401. current = dataKey - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus);
  23402. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  23403. {
  23404. if (current < range.lower || !haveLower)
  23405. {
  23406. range.lower = current;
  23407. haveLower = true;
  23408. }
  23409. }
  23410. }
  23411. }
  23412. if (haveUpper && !haveLower)
  23413. {
  23414. range.lower = range.upper;
  23415. haveLower = true;
  23416. } else if (haveLower && !haveUpper)
  23417. {
  23418. range.upper = range.lower;
  23419. haveUpper = true;
  23420. }
  23421. foundRange = haveLower && haveUpper;
  23422. return range;
  23423. }
  23424. /* inherits documentation from base class */
  23425. QCPRange QCPErrorBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  23426. {
  23427. if (!mDataPlottable)
  23428. {
  23429. foundRange = false;
  23430. return QCPRange();
  23431. }
  23432. QCPRange range;
  23433. const bool restrictKeyRange = inKeyRange != QCPRange();
  23434. bool haveLower = false;
  23435. bool haveUpper = false;
  23436. QCPErrorBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin();
  23437. QCPErrorBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd();
  23438. if (mDataPlottable->interface1D()->sortKeyIsMainKey() && restrictKeyRange)
  23439. {
  23440. itBegin = mDataContainer->constBegin()+findBegin(inKeyRange.lower);
  23441. itEnd = mDataContainer->constBegin()+findEnd(inKeyRange.upper);
  23442. }
  23443. for (QCPErrorBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it)
  23444. {
  23445. if (restrictKeyRange)
  23446. {
  23447. const double dataKey = mDataPlottable->interface1D()->dataMainKey(it-mDataContainer->constBegin());
  23448. if (dataKey < inKeyRange.lower || dataKey > inKeyRange.upper)
  23449. continue;
  23450. }
  23451. if (mErrorType == etValueError)
  23452. {
  23453. const double dataValue = mDataPlottable->interface1D()->dataMainValue(it-mDataContainer->constBegin());
  23454. if (qIsNaN(dataValue)) continue;
  23455. // plus error:
  23456. double current = dataValue + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus);
  23457. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  23458. {
  23459. if (current > range.upper || !haveUpper)
  23460. {
  23461. range.upper = current;
  23462. haveUpper = true;
  23463. }
  23464. }
  23465. // minus error:
  23466. current = dataValue - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus);
  23467. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  23468. {
  23469. if (current < range.lower || !haveLower)
  23470. {
  23471. range.lower = current;
  23472. haveLower = true;
  23473. }
  23474. }
  23475. } else // mErrorType == etKeyError
  23476. {
  23477. // error bar doesn't extend in value dimension (except whisker but we ignore that here), so only use data point center
  23478. const double current = mDataPlottable->interface1D()->dataMainValue(it-mDataContainer->constBegin());
  23479. if (qIsNaN(current)) continue;
  23480. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  23481. {
  23482. if (current < range.lower || !haveLower)
  23483. {
  23484. range.lower = current;
  23485. haveLower = true;
  23486. }
  23487. if (current > range.upper || !haveUpper)
  23488. {
  23489. range.upper = current;
  23490. haveUpper = true;
  23491. }
  23492. }
  23493. }
  23494. }
  23495. if (haveUpper && !haveLower)
  23496. {
  23497. range.lower = range.upper;
  23498. haveLower = true;
  23499. } else if (haveLower && !haveUpper)
  23500. {
  23501. range.upper = range.lower;
  23502. haveUpper = true;
  23503. }
  23504. foundRange = haveLower && haveUpper;
  23505. return range;
  23506. }
  23507. /*! \internal
  23508. Calculates the lines that make up the error bar belonging to the data point \a it.
  23509. The resulting lines are added to \a backbones and \a whiskers. The vectors are not cleared, so
  23510. calling this method with different \a it but the same \a backbones and \a whiskers allows to
  23511. accumulate lines for multiple data points.
  23512. This method assumes that \a it is a valid iterator within the bounds of this \ref QCPErrorBars
  23513. instance and within the bounds of the associated data plottable.
  23514. */
  23515. void QCPErrorBars::getErrorBarLines(QCPErrorBarsDataContainer::const_iterator it, QVector<QLineF> &backbones, QVector<QLineF> &whiskers) const
  23516. {
  23517. if (!mDataPlottable) return;
  23518. int index = it-mDataContainer->constBegin();
  23519. QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index);
  23520. if (qIsNaN(centerPixel.x()) || qIsNaN(centerPixel.y()))
  23521. return;
  23522. QCPAxis *errorAxis = mErrorType == etValueError ? mValueAxis.data() : mKeyAxis.data();
  23523. QCPAxis *orthoAxis = mErrorType == etValueError ? mKeyAxis.data() : mValueAxis.data();
  23524. const double centerErrorAxisPixel = errorAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
  23525. const double centerOrthoAxisPixel = orthoAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
  23526. const double centerErrorAxisCoord = errorAxis->pixelToCoord(centerErrorAxisPixel); // depending on plottable, this might be different from just mDataPlottable->interface1D()->dataMainKey/Value
  23527. const double symbolGap = mSymbolGap*0.5*errorAxis->pixelOrientation();
  23528. // plus error:
  23529. double errorStart, errorEnd;
  23530. if (!qIsNaN(it->errorPlus))
  23531. {
  23532. errorStart = centerErrorAxisPixel+symbolGap;
  23533. errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord+it->errorPlus);
  23534. if (errorAxis->orientation() == Qt::Vertical)
  23535. {
  23536. if ((errorStart > errorEnd) != errorAxis->rangeReversed())
  23537. backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd));
  23538. whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd));
  23539. } else
  23540. {
  23541. if ((errorStart < errorEnd) != errorAxis->rangeReversed())
  23542. backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel));
  23543. whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5));
  23544. }
  23545. }
  23546. // minus error:
  23547. if (!qIsNaN(it->errorMinus))
  23548. {
  23549. errorStart = centerErrorAxisPixel-symbolGap;
  23550. errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord-it->errorMinus);
  23551. if (errorAxis->orientation() == Qt::Vertical)
  23552. {
  23553. if ((errorStart < errorEnd) != errorAxis->rangeReversed())
  23554. backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd));
  23555. whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd));
  23556. } else
  23557. {
  23558. if ((errorStart > errorEnd) != errorAxis->rangeReversed())
  23559. backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel));
  23560. whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5));
  23561. }
  23562. }
  23563. }
  23564. /*! \internal
  23565. This method outputs the currently visible data range via \a begin and \a end. The returned range
  23566. will also never exceed \a rangeRestriction.
  23567. Since error bars with type \ref etKeyError may extend to arbitrarily positive and negative key
  23568. coordinates relative to their data point key, this method checks all outer error bars whether
  23569. they truly don't reach into the visible portion of the axis rect, by calling \ref
  23570. errorBarVisible. On the other hand error bars with type \ref etValueError that are associated
  23571. with data plottables whose sort key is equal to the main key (see \ref qcpdatacontainer-datatype
  23572. "QCPDataContainer DataType") can be handled very efficiently by finding the visible range of
  23573. error bars through binary search (\ref QCPPlottableInterface1D::findBegin and \ref
  23574. QCPPlottableInterface1D::findEnd).
  23575. If the plottable's sort key is not equal to the main key, this method returns the full data
  23576. range, only restricted by \a rangeRestriction. Drawing optimization then has to be done on a
  23577. point-by-point basis in the \ref draw method.
  23578. */
  23579. void QCPErrorBars::getVisibleDataBounds(QCPErrorBarsDataContainer::const_iterator &begin, QCPErrorBarsDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
  23580. {
  23581. QCPAxis *keyAxis = mKeyAxis.data();
  23582. QCPAxis *valueAxis = mValueAxis.data();
  23583. if (!keyAxis || !valueAxis)
  23584. {
  23585. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  23586. end = mDataContainer->constEnd();
  23587. begin = end;
  23588. return;
  23589. }
  23590. if (!mDataPlottable || rangeRestriction.isEmpty())
  23591. {
  23592. end = mDataContainer->constEnd();
  23593. begin = end;
  23594. return;
  23595. }
  23596. if (!mDataPlottable->interface1D()->sortKeyIsMainKey())
  23597. {
  23598. // if the sort key isn't the main key, it's not possible to find a contiguous range of visible
  23599. // data points, so this method then only applies the range restriction and otherwise returns
  23600. // the full data range. Visibility checks must be done on a per-datapoin-basis during drawing
  23601. QCPDataRange dataRange(0, mDataContainer->size());
  23602. dataRange = dataRange.bounded(rangeRestriction);
  23603. begin = mDataContainer->constBegin()+dataRange.begin();
  23604. end = mDataContainer->constBegin()+dataRange.end();
  23605. return;
  23606. }
  23607. // get visible data range via interface from data plottable, and then restrict to available error data points:
  23608. const int n = qMin(mDataContainer->size(), mDataPlottable->interface1D()->dataCount());
  23609. int beginIndex = mDataPlottable->interface1D()->findBegin(keyAxis->range().lower);
  23610. int endIndex = mDataPlottable->interface1D()->findEnd(keyAxis->range().upper);
  23611. int i = beginIndex;
  23612. while (i > 0 && i < n && i > rangeRestriction.begin())
  23613. {
  23614. if (errorBarVisible(i))
  23615. beginIndex = i;
  23616. --i;
  23617. }
  23618. i = endIndex;
  23619. while (i >= 0 && i < n && i < rangeRestriction.end())
  23620. {
  23621. if (errorBarVisible(i))
  23622. endIndex = i+1;
  23623. ++i;
  23624. }
  23625. QCPDataRange dataRange(beginIndex, endIndex);
  23626. dataRange = dataRange.bounded(rangeRestriction.bounded(QCPDataRange(0, mDataContainer->size())));
  23627. begin = mDataContainer->constBegin()+dataRange.begin();
  23628. end = mDataContainer->constBegin()+dataRange.end();
  23629. }
  23630. /*! \internal
  23631. Calculates the minimum distance in pixels the error bars' representation has from the given \a
  23632. pixelPoint. This is used to determine whether the error bar was clicked or not, e.g. in \ref
  23633. selectTest. The closest data point to \a pixelPoint is returned in \a closestData.
  23634. */
  23635. double QCPErrorBars::pointDistance(const QPointF &pixelPoint, QCPErrorBarsDataContainer::const_iterator &closestData) const
  23636. {
  23637. closestData = mDataContainer->constEnd();
  23638. if (!mDataPlottable || mDataContainer->isEmpty())
  23639. return -1.0;
  23640. if (!mKeyAxis || !mValueAxis)
  23641. {
  23642. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  23643. return -1.0;
  23644. }
  23645. QCPErrorBarsDataContainer::const_iterator begin, end;
  23646. getVisibleDataBounds(begin, end, QCPDataRange(0, dataCount()));
  23647. // calculate minimum distances to error backbones (whiskers are ignored for speed) and find closestData iterator:
  23648. double minDistSqr = std::numeric_limits<double>::max();
  23649. QVector<QLineF> backbones, whiskers;
  23650. for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it)
  23651. {
  23652. getErrorBarLines(it, backbones, whiskers);
  23653. for (int i=0; i<backbones.size(); ++i)
  23654. {
  23655. const double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(backbones.at(i));
  23656. if (currentDistSqr < minDistSqr)
  23657. {
  23658. minDistSqr = currentDistSqr;
  23659. closestData = it;
  23660. }
  23661. }
  23662. }
  23663. return qSqrt(minDistSqr);
  23664. }
  23665. /*! \internal
  23666. \note This method is identical to \ref QCPAbstractPlottable1D::getDataSegments but needs to be
  23667. reproduced here since the \ref QCPErrorBars plottable, as a special case that doesn't have its
  23668. own key/value data coordinates, doesn't derive from \ref QCPAbstractPlottable1D. See the
  23669. documentation there for details.
  23670. */
  23671. void QCPErrorBars::getDataSegments(QList<QCPDataRange> &selectedSegments, QList<QCPDataRange> &unselectedSegments) const
  23672. {
  23673. selectedSegments.clear();
  23674. unselectedSegments.clear();
  23675. if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty
  23676. {
  23677. if (selected())
  23678. selectedSegments << QCPDataRange(0, dataCount());
  23679. else
  23680. unselectedSegments << QCPDataRange(0, dataCount());
  23681. } else
  23682. {
  23683. QCPDataSelection sel(selection());
  23684. sel.simplify();
  23685. selectedSegments = sel.dataRanges();
  23686. unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges();
  23687. }
  23688. }
  23689. /*! \internal
  23690. Returns whether the error bar at the specified \a index is visible within the current key axis
  23691. range.
  23692. This method assumes for performance reasons without checking that the key axis, the value axis,
  23693. and the data plottable (\ref setDataPlottable) are not zero and that \a index is within valid
  23694. bounds of this \ref QCPErrorBars instance and the bounds of the data plottable.
  23695. */
  23696. bool QCPErrorBars::errorBarVisible(int index) const
  23697. {
  23698. QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index);
  23699. const double centerKeyPixel = mKeyAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
  23700. if (qIsNaN(centerKeyPixel))
  23701. return false;
  23702. double keyMin, keyMax;
  23703. if (mErrorType == etKeyError)
  23704. {
  23705. const double centerKey = mKeyAxis->pixelToCoord(centerKeyPixel);
  23706. const double errorPlus = mDataContainer->at(index).errorPlus;
  23707. const double errorMinus = mDataContainer->at(index).errorMinus;
  23708. keyMax = centerKey+(qIsNaN(errorPlus) ? 0 : errorPlus);
  23709. keyMin = centerKey-(qIsNaN(errorMinus) ? 0 : errorMinus);
  23710. } else // mErrorType == etValueError
  23711. {
  23712. keyMax = mKeyAxis->pixelToCoord(centerKeyPixel+mWhiskerWidth*0.5*mKeyAxis->pixelOrientation());
  23713. keyMin = mKeyAxis->pixelToCoord(centerKeyPixel-mWhiskerWidth*0.5*mKeyAxis->pixelOrientation());
  23714. }
  23715. return ((keyMax > mKeyAxis->range().lower) && (keyMin < mKeyAxis->range().upper));
  23716. }
  23717. /*! \internal
  23718. Returns whether \a line intersects (or is contained in) \a pixelRect.
  23719. \a line is assumed to be either perfectly horizontal or perfectly vertical, as is the case for
  23720. error bar lines.
  23721. */
  23722. bool QCPErrorBars::rectIntersectsLine(const QRectF &pixelRect, const QLineF &line) const
  23723. {
  23724. if (pixelRect.left() > line.x1() && pixelRect.left() > line.x2())
  23725. return false;
  23726. else if (pixelRect.right() < line.x1() && pixelRect.right() < line.x2())
  23727. return false;
  23728. else if (pixelRect.top() > line.y1() && pixelRect.top() > line.y2())
  23729. return false;
  23730. else if (pixelRect.bottom() < line.y1() && pixelRect.bottom() < line.y2())
  23731. return false;
  23732. else
  23733. return true;
  23734. }
  23735. /* end of 'src/plottables/plottable-errorbar.cpp' */
  23736. /* including file 'src/items/item-straightline.cpp', size 7592 */
  23737. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  23738. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23739. //////////////////// QCPItemStraightLine
  23740. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23741. /*! \class QCPItemStraightLine
  23742. \brief A straight line that spans infinitely in both directions
  23743. \image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid blue discs are positions."
  23744. It has two positions, \a point1 and \a point2, which define the straight line.
  23745. */
  23746. /*!
  23747. Creates a straight line item and sets default values.
  23748. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  23749. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  23750. */
  23751. QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) :
  23752. QCPAbstractItem(parentPlot),
  23753. point1(createPosition(QLatin1String("point1"))),
  23754. point2(createPosition(QLatin1String("point2")))
  23755. {
  23756. point1->setCoords(0, 0);
  23757. point2->setCoords(1, 1);
  23758. setPen(QPen(Qt::black));
  23759. setSelectedPen(QPen(Qt::blue,2));
  23760. }
  23761. QCPItemStraightLine::~QCPItemStraightLine()
  23762. {
  23763. }
  23764. /*!
  23765. Sets the pen that will be used to draw the line
  23766. \see setSelectedPen
  23767. */
  23768. void QCPItemStraightLine::setPen(const QPen &pen)
  23769. {
  23770. mPen = pen;
  23771. }
  23772. /*!
  23773. Sets the pen that will be used to draw the line when selected
  23774. \see setPen, setSelected
  23775. */
  23776. void QCPItemStraightLine::setSelectedPen(const QPen &pen)
  23777. {
  23778. mSelectedPen = pen;
  23779. }
  23780. /* inherits documentation from base class */
  23781. double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  23782. {
  23783. Q_UNUSED(details)
  23784. if (onlySelectable && !mSelectable)
  23785. return -1;
  23786. return QCPVector2D(pos).distanceToStraightLine(point1->pixelPosition(), point2->pixelPosition()-point1->pixelPosition());
  23787. }
  23788. /* inherits documentation from base class */
  23789. void QCPItemStraightLine::draw(QCPPainter *painter)
  23790. {
  23791. QCPVector2D start(point1->pixelPosition());
  23792. QCPVector2D end(point2->pixelPosition());
  23793. // get visible segment of straight line inside clipRect:
  23794. double clipPad = mainPen().widthF();
  23795. QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
  23796. // paint visible segment, if existent:
  23797. if (!line.isNull())
  23798. {
  23799. painter->setPen(mainPen());
  23800. painter->drawLine(line);
  23801. }
  23802. }
  23803. /*! \internal
  23804. Returns the section of the straight line defined by \a base and direction vector \a
  23805. vec, that is visible in the specified \a rect.
  23806. This is a helper function for \ref draw.
  23807. */
  23808. QLineF QCPItemStraightLine::getRectClippedStraightLine(const QCPVector2D &base, const QCPVector2D &vec, const QRect &rect) const
  23809. {
  23810. double bx, by;
  23811. double gamma;
  23812. QLineF result;
  23813. if (vec.x() == 0 && vec.y() == 0)
  23814. return result;
  23815. if (qFuzzyIsNull(vec.x())) // line is vertical
  23816. {
  23817. // check top of rect:
  23818. bx = rect.left();
  23819. by = rect.top();
  23820. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  23821. if (gamma >= 0 && gamma <= rect.width())
  23822. result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical
  23823. } else if (qFuzzyIsNull(vec.y())) // line is horizontal
  23824. {
  23825. // check left of rect:
  23826. bx = rect.left();
  23827. by = rect.top();
  23828. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  23829. if (gamma >= 0 && gamma <= rect.height())
  23830. result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal
  23831. } else // line is skewed
  23832. {
  23833. QList<QCPVector2D> pointVectors;
  23834. // check top of rect:
  23835. bx = rect.left();
  23836. by = rect.top();
  23837. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  23838. if (gamma >= 0 && gamma <= rect.width())
  23839. pointVectors.append(QCPVector2D(bx+gamma, by));
  23840. // check bottom of rect:
  23841. bx = rect.left();
  23842. by = rect.bottom();
  23843. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  23844. if (gamma >= 0 && gamma <= rect.width())
  23845. pointVectors.append(QCPVector2D(bx+gamma, by));
  23846. // check left of rect:
  23847. bx = rect.left();
  23848. by = rect.top();
  23849. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  23850. if (gamma >= 0 && gamma <= rect.height())
  23851. pointVectors.append(QCPVector2D(bx, by+gamma));
  23852. // check right of rect:
  23853. bx = rect.right();
  23854. by = rect.top();
  23855. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  23856. if (gamma >= 0 && gamma <= rect.height())
  23857. pointVectors.append(QCPVector2D(bx, by+gamma));
  23858. // evaluate points:
  23859. if (pointVectors.size() == 2)
  23860. {
  23861. result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
  23862. } else if (pointVectors.size() > 2)
  23863. {
  23864. // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
  23865. double distSqrMax = 0;
  23866. QCPVector2D pv1, pv2;
  23867. for (int i=0; i<pointVectors.size()-1; ++i)
  23868. {
  23869. for (int k=i+1; k<pointVectors.size(); ++k)
  23870. {
  23871. double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
  23872. if (distSqr > distSqrMax)
  23873. {
  23874. pv1 = pointVectors.at(i);
  23875. pv2 = pointVectors.at(k);
  23876. distSqrMax = distSqr;
  23877. }
  23878. }
  23879. }
  23880. result.setPoints(pv1.toPointF(), pv2.toPointF());
  23881. }
  23882. }
  23883. return result;
  23884. }
  23885. /*! \internal
  23886. Returns the pen that should be used for drawing lines. Returns mPen when the
  23887. item is not selected and mSelectedPen when it is.
  23888. */
  23889. QPen QCPItemStraightLine::mainPen() const
  23890. {
  23891. return mSelected ? mSelectedPen : mPen;
  23892. }
  23893. /* end of 'src/items/item-straightline.cpp' */
  23894. /* including file 'src/items/item-line.cpp', size 8498 */
  23895. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  23896. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23897. //////////////////// QCPItemLine
  23898. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23899. /*! \class QCPItemLine
  23900. \brief A line from one point to another
  23901. \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions."
  23902. It has two positions, \a start and \a end, which define the end points of the line.
  23903. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow.
  23904. */
  23905. /*!
  23906. Creates a line item and sets default values.
  23907. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  23908. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  23909. */
  23910. QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) :
  23911. QCPAbstractItem(parentPlot),
  23912. start(createPosition(QLatin1String("start"))),
  23913. end(createPosition(QLatin1String("end")))
  23914. {
  23915. start->setCoords(0, 0);
  23916. end->setCoords(1, 1);
  23917. setPen(QPen(Qt::black));
  23918. setSelectedPen(QPen(Qt::blue,2));
  23919. }
  23920. QCPItemLine::~QCPItemLine()
  23921. {
  23922. }
  23923. /*!
  23924. Sets the pen that will be used to draw the line
  23925. \see setSelectedPen
  23926. */
  23927. void QCPItemLine::setPen(const QPen &pen)
  23928. {
  23929. mPen = pen;
  23930. }
  23931. /*!
  23932. Sets the pen that will be used to draw the line when selected
  23933. \see setPen, setSelected
  23934. */
  23935. void QCPItemLine::setSelectedPen(const QPen &pen)
  23936. {
  23937. mSelectedPen = pen;
  23938. }
  23939. /*!
  23940. Sets the line ending style of the head. The head corresponds to the \a end position.
  23941. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  23942. a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
  23943. \see setTail
  23944. */
  23945. void QCPItemLine::setHead(const QCPLineEnding &head)
  23946. {
  23947. mHead = head;
  23948. }
  23949. /*!
  23950. Sets the line ending style of the tail. The tail corresponds to the \a start position.
  23951. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  23952. a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
  23953. \see setHead
  23954. */
  23955. void QCPItemLine::setTail(const QCPLineEnding &tail)
  23956. {
  23957. mTail = tail;
  23958. }
  23959. /* inherits documentation from base class */
  23960. double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  23961. {
  23962. Q_UNUSED(details)
  23963. if (onlySelectable && !mSelectable)
  23964. return -1;
  23965. return qSqrt(QCPVector2D(pos).distanceSquaredToLine(start->pixelPosition(), end->pixelPosition()));
  23966. }
  23967. /* inherits documentation from base class */
  23968. void QCPItemLine::draw(QCPPainter *painter)
  23969. {
  23970. QCPVector2D startVec(start->pixelPosition());
  23971. QCPVector2D endVec(end->pixelPosition());
  23972. if (qFuzzyIsNull((startVec-endVec).lengthSquared()))
  23973. return;
  23974. // get visible segment of straight line inside clipRect:
  23975. double clipPad = qMax(mHead.boundingDistance(), mTail.boundingDistance());
  23976. clipPad = qMax(clipPad, (double)mainPen().widthF());
  23977. QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
  23978. // paint visible segment, if existent:
  23979. if (!line.isNull())
  23980. {
  23981. painter->setPen(mainPen());
  23982. painter->drawLine(line);
  23983. painter->setBrush(Qt::SolidPattern);
  23984. if (mTail.style() != QCPLineEnding::esNone)
  23985. mTail.draw(painter, startVec, startVec-endVec);
  23986. if (mHead.style() != QCPLineEnding::esNone)
  23987. mHead.draw(painter, endVec, endVec-startVec);
  23988. }
  23989. }
  23990. /*! \internal
  23991. Returns the section of the line defined by \a start and \a end, that is visible in the specified
  23992. \a rect.
  23993. This is a helper function for \ref draw.
  23994. */
  23995. QLineF QCPItemLine::getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRect &rect) const
  23996. {
  23997. bool containsStart = rect.contains(start.x(), start.y());
  23998. bool containsEnd = rect.contains(end.x(), end.y());
  23999. if (containsStart && containsEnd)
  24000. return QLineF(start.toPointF(), end.toPointF());
  24001. QCPVector2D base = start;
  24002. QCPVector2D vec = end-start;
  24003. double bx, by;
  24004. double gamma, mu;
  24005. QLineF result;
  24006. QList<QCPVector2D> pointVectors;
  24007. if (!qFuzzyIsNull(vec.y())) // line is not horizontal
  24008. {
  24009. // check top of rect:
  24010. bx = rect.left();
  24011. by = rect.top();
  24012. mu = (by-base.y())/vec.y();
  24013. if (mu >= 0 && mu <= 1)
  24014. {
  24015. gamma = base.x()-bx + mu*vec.x();
  24016. if (gamma >= 0 && gamma <= rect.width())
  24017. pointVectors.append(QCPVector2D(bx+gamma, by));
  24018. }
  24019. // check bottom of rect:
  24020. bx = rect.left();
  24021. by = rect.bottom();
  24022. mu = (by-base.y())/vec.y();
  24023. if (mu >= 0 && mu <= 1)
  24024. {
  24025. gamma = base.x()-bx + mu*vec.x();
  24026. if (gamma >= 0 && gamma <= rect.width())
  24027. pointVectors.append(QCPVector2D(bx+gamma, by));
  24028. }
  24029. }
  24030. if (!qFuzzyIsNull(vec.x())) // line is not vertical
  24031. {
  24032. // check left of rect:
  24033. bx = rect.left();
  24034. by = rect.top();
  24035. mu = (bx-base.x())/vec.x();
  24036. if (mu >= 0 && mu <= 1)
  24037. {
  24038. gamma = base.y()-by + mu*vec.y();
  24039. if (gamma >= 0 && gamma <= rect.height())
  24040. pointVectors.append(QCPVector2D(bx, by+gamma));
  24041. }
  24042. // check right of rect:
  24043. bx = rect.right();
  24044. by = rect.top();
  24045. mu = (bx-base.x())/vec.x();
  24046. if (mu >= 0 && mu <= 1)
  24047. {
  24048. gamma = base.y()-by + mu*vec.y();
  24049. if (gamma >= 0 && gamma <= rect.height())
  24050. pointVectors.append(QCPVector2D(bx, by+gamma));
  24051. }
  24052. }
  24053. if (containsStart)
  24054. pointVectors.append(start);
  24055. if (containsEnd)
  24056. pointVectors.append(end);
  24057. // evaluate points:
  24058. if (pointVectors.size() == 2)
  24059. {
  24060. result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
  24061. } else if (pointVectors.size() > 2)
  24062. {
  24063. // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
  24064. double distSqrMax = 0;
  24065. QCPVector2D pv1, pv2;
  24066. for (int i=0; i<pointVectors.size()-1; ++i)
  24067. {
  24068. for (int k=i+1; k<pointVectors.size(); ++k)
  24069. {
  24070. double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
  24071. if (distSqr > distSqrMax)
  24072. {
  24073. pv1 = pointVectors.at(i);
  24074. pv2 = pointVectors.at(k);
  24075. distSqrMax = distSqr;
  24076. }
  24077. }
  24078. }
  24079. result.setPoints(pv1.toPointF(), pv2.toPointF());
  24080. }
  24081. return result;
  24082. }
  24083. /*! \internal
  24084. Returns the pen that should be used for drawing lines. Returns mPen when the
  24085. item is not selected and mSelectedPen when it is.
  24086. */
  24087. QPen QCPItemLine::mainPen() const
  24088. {
  24089. return mSelected ? mSelectedPen : mPen;
  24090. }
  24091. /* end of 'src/items/item-line.cpp' */
  24092. /* including file 'src/items/item-curve.cpp', size 7159 */
  24093. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  24094. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24095. //////////////////// QCPItemCurve
  24096. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24097. /*! \class QCPItemCurve
  24098. \brief A curved line from one point to another
  24099. \image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are positions."
  24100. It has four positions, \a start and \a end, which define the end points of the line, and two
  24101. control points which define the direction the line exits from the start and the direction from
  24102. which it approaches the end: \a startDir and \a endDir.
  24103. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an
  24104. arrow.
  24105. Often it is desirable for the control points to stay at fixed relative positions to the start/end
  24106. point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start,
  24107. and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir.
  24108. */
  24109. /*!
  24110. Creates a curve item and sets default values.
  24111. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24112. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24113. */
  24114. QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) :
  24115. QCPAbstractItem(parentPlot),
  24116. start(createPosition(QLatin1String("start"))),
  24117. startDir(createPosition(QLatin1String("startDir"))),
  24118. endDir(createPosition(QLatin1String("endDir"))),
  24119. end(createPosition(QLatin1String("end")))
  24120. {
  24121. start->setCoords(0, 0);
  24122. startDir->setCoords(0.5, 0);
  24123. endDir->setCoords(0, 0.5);
  24124. end->setCoords(1, 1);
  24125. setPen(QPen(Qt::black));
  24126. setSelectedPen(QPen(Qt::blue,2));
  24127. }
  24128. QCPItemCurve::~QCPItemCurve()
  24129. {
  24130. }
  24131. /*!
  24132. Sets the pen that will be used to draw the line
  24133. \see setSelectedPen
  24134. */
  24135. void QCPItemCurve::setPen(const QPen &pen)
  24136. {
  24137. mPen = pen;
  24138. }
  24139. /*!
  24140. Sets the pen that will be used to draw the line when selected
  24141. \see setPen, setSelected
  24142. */
  24143. void QCPItemCurve::setSelectedPen(const QPen &pen)
  24144. {
  24145. mSelectedPen = pen;
  24146. }
  24147. /*!
  24148. Sets the line ending style of the head. The head corresponds to the \a end position.
  24149. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  24150. a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
  24151. \see setTail
  24152. */
  24153. void QCPItemCurve::setHead(const QCPLineEnding &head)
  24154. {
  24155. mHead = head;
  24156. }
  24157. /*!
  24158. Sets the line ending style of the tail. The tail corresponds to the \a start position.
  24159. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  24160. a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
  24161. \see setHead
  24162. */
  24163. void QCPItemCurve::setTail(const QCPLineEnding &tail)
  24164. {
  24165. mTail = tail;
  24166. }
  24167. /* inherits documentation from base class */
  24168. double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  24169. {
  24170. Q_UNUSED(details)
  24171. if (onlySelectable && !mSelectable)
  24172. return -1;
  24173. QPointF startVec(start->pixelPosition());
  24174. QPointF startDirVec(startDir->pixelPosition());
  24175. QPointF endDirVec(endDir->pixelPosition());
  24176. QPointF endVec(end->pixelPosition());
  24177. QPainterPath cubicPath(startVec);
  24178. cubicPath.cubicTo(startDirVec, endDirVec, endVec);
  24179. QPolygonF polygon = cubicPath.toSubpathPolygons().first();
  24180. QCPVector2D p(pos);
  24181. double minDistSqr = std::numeric_limits<double>::max();
  24182. for (int i=1; i<polygon.size(); ++i)
  24183. {
  24184. double distSqr = p.distanceSquaredToLine(polygon.at(i-1), polygon.at(i));
  24185. if (distSqr < minDistSqr)
  24186. minDistSqr = distSqr;
  24187. }
  24188. return qSqrt(minDistSqr);
  24189. }
  24190. /* inherits documentation from base class */
  24191. void QCPItemCurve::draw(QCPPainter *painter)
  24192. {
  24193. QCPVector2D startVec(start->pixelPosition());
  24194. QCPVector2D startDirVec(startDir->pixelPosition());
  24195. QCPVector2D endDirVec(endDir->pixelPosition());
  24196. QCPVector2D endVec(end->pixelPosition());
  24197. if ((endVec-startVec).length() > 1e10) // too large curves cause crash
  24198. return;
  24199. QPainterPath cubicPath(startVec.toPointF());
  24200. cubicPath.cubicTo(startDirVec.toPointF(), endDirVec.toPointF(), endVec.toPointF());
  24201. // paint visible segment, if existent:
  24202. QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
  24203. QRect cubicRect = cubicPath.controlPointRect().toRect();
  24204. if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position
  24205. cubicRect.adjust(0, 0, 1, 1);
  24206. if (clip.intersects(cubicRect))
  24207. {
  24208. painter->setPen(mainPen());
  24209. painter->drawPath(cubicPath);
  24210. painter->setBrush(Qt::SolidPattern);
  24211. if (mTail.style() != QCPLineEnding::esNone)
  24212. mTail.draw(painter, startVec, M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI);
  24213. if (mHead.style() != QCPLineEnding::esNone)
  24214. mHead.draw(painter, endVec, -cubicPath.angleAtPercent(1)/180.0*M_PI);
  24215. }
  24216. }
  24217. /*! \internal
  24218. Returns the pen that should be used for drawing lines. Returns mPen when the
  24219. item is not selected and mSelectedPen when it is.
  24220. */
  24221. QPen QCPItemCurve::mainPen() const
  24222. {
  24223. return mSelected ? mSelectedPen : mPen;
  24224. }
  24225. /* end of 'src/items/item-curve.cpp' */
  24226. /* including file 'src/items/item-rect.cpp', size 6479 */
  24227. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  24228. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24229. //////////////////// QCPItemRect
  24230. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24231. /*! \class QCPItemRect
  24232. \brief A rectangle
  24233. \image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions."
  24234. It has two positions, \a topLeft and \a bottomRight, which define the rectangle.
  24235. */
  24236. /*!
  24237. Creates a rectangle item and sets default values.
  24238. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24239. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24240. */
  24241. QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) :
  24242. QCPAbstractItem(parentPlot),
  24243. topLeft(createPosition(QLatin1String("topLeft"))),
  24244. bottomRight(createPosition(QLatin1String("bottomRight"))),
  24245. top(createAnchor(QLatin1String("top"), aiTop)),
  24246. topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
  24247. right(createAnchor(QLatin1String("right"), aiRight)),
  24248. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  24249. bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
  24250. left(createAnchor(QLatin1String("left"), aiLeft))
  24251. {
  24252. topLeft->setCoords(0, 1);
  24253. bottomRight->setCoords(1, 0);
  24254. setPen(QPen(Qt::black));
  24255. setSelectedPen(QPen(Qt::blue,2));
  24256. setBrush(Qt::NoBrush);
  24257. setSelectedBrush(Qt::NoBrush);
  24258. }
  24259. QCPItemRect::~QCPItemRect()
  24260. {
  24261. }
  24262. /*!
  24263. Sets the pen that will be used to draw the line of the rectangle
  24264. \see setSelectedPen, setBrush
  24265. */
  24266. void QCPItemRect::setPen(const QPen &pen)
  24267. {
  24268. mPen = pen;
  24269. }
  24270. /*!
  24271. Sets the pen that will be used to draw the line of the rectangle when selected
  24272. \see setPen, setSelected
  24273. */
  24274. void QCPItemRect::setSelectedPen(const QPen &pen)
  24275. {
  24276. mSelectedPen = pen;
  24277. }
  24278. /*!
  24279. Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to
  24280. Qt::NoBrush.
  24281. \see setSelectedBrush, setPen
  24282. */
  24283. void QCPItemRect::setBrush(const QBrush &brush)
  24284. {
  24285. mBrush = brush;
  24286. }
  24287. /*!
  24288. Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a
  24289. brush to Qt::NoBrush.
  24290. \see setBrush
  24291. */
  24292. void QCPItemRect::setSelectedBrush(const QBrush &brush)
  24293. {
  24294. mSelectedBrush = brush;
  24295. }
  24296. /* inherits documentation from base class */
  24297. double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  24298. {
  24299. Q_UNUSED(details)
  24300. if (onlySelectable && !mSelectable)
  24301. return -1;
  24302. QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()).normalized();
  24303. bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
  24304. return rectDistance(rect, pos, filledRect);
  24305. }
  24306. /* inherits documentation from base class */
  24307. void QCPItemRect::draw(QCPPainter *painter)
  24308. {
  24309. QPointF p1 = topLeft->pixelPosition();
  24310. QPointF p2 = bottomRight->pixelPosition();
  24311. if (p1.toPoint() == p2.toPoint())
  24312. return;
  24313. QRectF rect = QRectF(p1, p2).normalized();
  24314. double clipPad = mainPen().widthF();
  24315. QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  24316. if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect
  24317. {
  24318. painter->setPen(mainPen());
  24319. painter->setBrush(mainBrush());
  24320. painter->drawRect(rect);
  24321. }
  24322. }
  24323. /* inherits documentation from base class */
  24324. QPointF QCPItemRect::anchorPixelPosition(int anchorId) const
  24325. {
  24326. QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition());
  24327. switch (anchorId)
  24328. {
  24329. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  24330. case aiTopRight: return rect.topRight();
  24331. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  24332. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  24333. case aiBottomLeft: return rect.bottomLeft();
  24334. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
  24335. }
  24336. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  24337. return QPointF();
  24338. }
  24339. /*! \internal
  24340. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  24341. and mSelectedPen when it is.
  24342. */
  24343. QPen QCPItemRect::mainPen() const
  24344. {
  24345. return mSelected ? mSelectedPen : mPen;
  24346. }
  24347. /*! \internal
  24348. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  24349. is not selected and mSelectedBrush when it is.
  24350. */
  24351. QBrush QCPItemRect::mainBrush() const
  24352. {
  24353. return mSelected ? mSelectedBrush : mBrush;
  24354. }
  24355. /* end of 'src/items/item-rect.cpp' */
  24356. /* including file 'src/items/item-text.cpp', size 13338 */
  24357. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  24358. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24359. //////////////////// QCPItemText
  24360. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24361. /*! \class QCPItemText
  24362. \brief A text label
  24363. \image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions."
  24364. Its position is defined by the member \a position and the setting of \ref setPositionAlignment.
  24365. The latter controls which part of the text rect shall be aligned with \a position.
  24366. The text alignment itself (i.e. left, center, right) can be controlled with \ref
  24367. setTextAlignment.
  24368. The text may be rotated around the \a position point with \ref setRotation.
  24369. */
  24370. /*!
  24371. Creates a text item and sets default values.
  24372. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24373. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24374. */
  24375. QCPItemText::QCPItemText(QCustomPlot *parentPlot) :
  24376. QCPAbstractItem(parentPlot),
  24377. position(createPosition(QLatin1String("position"))),
  24378. topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft)),
  24379. top(createAnchor(QLatin1String("top"), aiTop)),
  24380. topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
  24381. right(createAnchor(QLatin1String("right"), aiRight)),
  24382. bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)),
  24383. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  24384. bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
  24385. left(createAnchor(QLatin1String("left"), aiLeft)),
  24386. mText(QLatin1String("text")),
  24387. mPositionAlignment(Qt::AlignCenter),
  24388. mTextAlignment(Qt::AlignTop|Qt::AlignHCenter),
  24389. mRotation(0)
  24390. {
  24391. position->setCoords(0, 0);
  24392. setPen(Qt::NoPen);
  24393. setSelectedPen(Qt::NoPen);
  24394. setBrush(Qt::NoBrush);
  24395. setSelectedBrush(Qt::NoBrush);
  24396. setColor(Qt::black);
  24397. setSelectedColor(Qt::blue);
  24398. }
  24399. QCPItemText::~QCPItemText()
  24400. {
  24401. }
  24402. /*!
  24403. Sets the color of the text.
  24404. */
  24405. void QCPItemText::setColor(const QColor &color)
  24406. {
  24407. mColor = color;
  24408. }
  24409. /*!
  24410. Sets the color of the text that will be used when the item is selected.
  24411. */
  24412. void QCPItemText::setSelectedColor(const QColor &color)
  24413. {
  24414. mSelectedColor = color;
  24415. }
  24416. /*!
  24417. Sets the pen that will be used do draw a rectangular border around the text. To disable the
  24418. border, set \a pen to Qt::NoPen.
  24419. \see setSelectedPen, setBrush, setPadding
  24420. */
  24421. void QCPItemText::setPen(const QPen &pen)
  24422. {
  24423. mPen = pen;
  24424. }
  24425. /*!
  24426. Sets the pen that will be used do draw a rectangular border around the text, when the item is
  24427. selected. To disable the border, set \a pen to Qt::NoPen.
  24428. \see setPen
  24429. */
  24430. void QCPItemText::setSelectedPen(const QPen &pen)
  24431. {
  24432. mSelectedPen = pen;
  24433. }
  24434. /*!
  24435. Sets the brush that will be used do fill the background of the text. To disable the
  24436. background, set \a brush to Qt::NoBrush.
  24437. \see setSelectedBrush, setPen, setPadding
  24438. */
  24439. void QCPItemText::setBrush(const QBrush &brush)
  24440. {
  24441. mBrush = brush;
  24442. }
  24443. /*!
  24444. Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the
  24445. background, set \a brush to Qt::NoBrush.
  24446. \see setBrush
  24447. */
  24448. void QCPItemText::setSelectedBrush(const QBrush &brush)
  24449. {
  24450. mSelectedBrush = brush;
  24451. }
  24452. /*!
  24453. Sets the font of the text.
  24454. \see setSelectedFont, setColor
  24455. */
  24456. void QCPItemText::setFont(const QFont &font)
  24457. {
  24458. mFont = font;
  24459. }
  24460. /*!
  24461. Sets the font of the text that will be used when the item is selected.
  24462. \see setFont
  24463. */
  24464. void QCPItemText::setSelectedFont(const QFont &font)
  24465. {
  24466. mSelectedFont = font;
  24467. }
  24468. /*!
  24469. Sets the text that will be displayed. Multi-line texts are supported by inserting a line break
  24470. character, e.g. '\n'.
  24471. \see setFont, setColor, setTextAlignment
  24472. */
  24473. void QCPItemText::setText(const QString &text)
  24474. {
  24475. mText = text;
  24476. }
  24477. /*!
  24478. Sets which point of the text rect shall be aligned with \a position.
  24479. Examples:
  24480. \li If \a alignment is <tt>Qt::AlignHCenter | Qt::AlignTop</tt>, the text will be positioned such
  24481. that the top of the text rect will be horizontally centered on \a position.
  24482. \li If \a alignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt>, \a position will indicate the
  24483. bottom left corner of the text rect.
  24484. If you want to control the alignment of (multi-lined) text within the text rect, use \ref
  24485. setTextAlignment.
  24486. */
  24487. void QCPItemText::setPositionAlignment(Qt::Alignment alignment)
  24488. {
  24489. mPositionAlignment = alignment;
  24490. }
  24491. /*!
  24492. Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or Qt::AlignRight).
  24493. */
  24494. void QCPItemText::setTextAlignment(Qt::Alignment alignment)
  24495. {
  24496. mTextAlignment = alignment;
  24497. }
  24498. /*!
  24499. Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated
  24500. around \a position.
  24501. */
  24502. void QCPItemText::setRotation(double degrees)
  24503. {
  24504. mRotation = degrees;
  24505. }
  24506. /*!
  24507. Sets the distance between the border of the text rectangle and the text. The appearance (and
  24508. visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush.
  24509. */
  24510. void QCPItemText::setPadding(const QMargins &padding)
  24511. {
  24512. mPadding = padding;
  24513. }
  24514. /* inherits documentation from base class */
  24515. double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  24516. {
  24517. Q_UNUSED(details)
  24518. if (onlySelectable && !mSelectable)
  24519. return -1;
  24520. // The rect may be rotated, so we transform the actual clicked pos to the rotated
  24521. // coordinate system, so we can use the normal rectDistance function for non-rotated rects:
  24522. QPointF positionPixels(position->pixelPosition());
  24523. QTransform inputTransform;
  24524. inputTransform.translate(positionPixels.x(), positionPixels.y());
  24525. inputTransform.rotate(-mRotation);
  24526. inputTransform.translate(-positionPixels.x(), -positionPixels.y());
  24527. QPointF rotatedPos = inputTransform.map(pos);
  24528. QFontMetrics fontMetrics(mFont);
  24529. QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  24530. QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  24531. QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment);
  24532. textBoxRect.moveTopLeft(textPos.toPoint());
  24533. return rectDistance(textBoxRect, rotatedPos, true);
  24534. }
  24535. /* inherits documentation from base class */
  24536. void QCPItemText::draw(QCPPainter *painter)
  24537. {
  24538. QPointF pos(position->pixelPosition());
  24539. QTransform transform = painter->transform();
  24540. transform.translate(pos.x(), pos.y());
  24541. if (!qFuzzyIsNull(mRotation))
  24542. transform.rotate(mRotation);
  24543. painter->setFont(mainFont());
  24544. QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  24545. QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  24546. QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
  24547. textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top()));
  24548. textBoxRect.moveTopLeft(textPos.toPoint());
  24549. double clipPad = mainPen().widthF();
  24550. QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  24551. if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect())))
  24552. {
  24553. painter->setTransform(transform);
  24554. if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) ||
  24555. (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0))
  24556. {
  24557. painter->setPen(mainPen());
  24558. painter->setBrush(mainBrush());
  24559. painter->drawRect(textBoxRect);
  24560. }
  24561. painter->setBrush(Qt::NoBrush);
  24562. painter->setPen(QPen(mainColor()));
  24563. painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText);
  24564. }
  24565. }
  24566. /* inherits documentation from base class */
  24567. QPointF QCPItemText::anchorPixelPosition(int anchorId) const
  24568. {
  24569. // get actual rect points (pretty much copied from draw function):
  24570. QPointF pos(position->pixelPosition());
  24571. QTransform transform;
  24572. transform.translate(pos.x(), pos.y());
  24573. if (!qFuzzyIsNull(mRotation))
  24574. transform.rotate(mRotation);
  24575. QFontMetrics fontMetrics(mainFont());
  24576. QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  24577. QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  24578. QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
  24579. textBoxRect.moveTopLeft(textPos.toPoint());
  24580. QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect));
  24581. switch (anchorId)
  24582. {
  24583. case aiTopLeft: return rectPoly.at(0);
  24584. case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5;
  24585. case aiTopRight: return rectPoly.at(1);
  24586. case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5;
  24587. case aiBottomRight: return rectPoly.at(2);
  24588. case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5;
  24589. case aiBottomLeft: return rectPoly.at(3);
  24590. case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5;
  24591. }
  24592. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  24593. return QPointF();
  24594. }
  24595. /*! \internal
  24596. Returns the point that must be given to the QPainter::drawText function (which expects the top
  24597. left point of the text rect), according to the position \a pos, the text bounding box \a rect and
  24598. the requested \a positionAlignment.
  24599. For example, if \a positionAlignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt> the returned point
  24600. will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally
  24601. drawn at that point, the lower left corner of the resulting text rect is at \a pos.
  24602. */
  24603. QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const
  24604. {
  24605. if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop))
  24606. return pos;
  24607. QPointF result = pos; // start at top left
  24608. if (positionAlignment.testFlag(Qt::AlignHCenter))
  24609. result.rx() -= rect.width()/2.0;
  24610. else if (positionAlignment.testFlag(Qt::AlignRight))
  24611. result.rx() -= rect.width();
  24612. if (positionAlignment.testFlag(Qt::AlignVCenter))
  24613. result.ry() -= rect.height()/2.0;
  24614. else if (positionAlignment.testFlag(Qt::AlignBottom))
  24615. result.ry() -= rect.height();
  24616. return result;
  24617. }
  24618. /*! \internal
  24619. Returns the font that should be used for drawing text. Returns mFont when the item is not selected
  24620. and mSelectedFont when it is.
  24621. */
  24622. QFont QCPItemText::mainFont() const
  24623. {
  24624. return mSelected ? mSelectedFont : mFont;
  24625. }
  24626. /*! \internal
  24627. Returns the color that should be used for drawing text. Returns mColor when the item is not
  24628. selected and mSelectedColor when it is.
  24629. */
  24630. QColor QCPItemText::mainColor() const
  24631. {
  24632. return mSelected ? mSelectedColor : mColor;
  24633. }
  24634. /*! \internal
  24635. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  24636. and mSelectedPen when it is.
  24637. */
  24638. QPen QCPItemText::mainPen() const
  24639. {
  24640. return mSelected ? mSelectedPen : mPen;
  24641. }
  24642. /*! \internal
  24643. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  24644. is not selected and mSelectedBrush when it is.
  24645. */
  24646. QBrush QCPItemText::mainBrush() const
  24647. {
  24648. return mSelected ? mSelectedBrush : mBrush;
  24649. }
  24650. /* end of 'src/items/item-text.cpp' */
  24651. /* including file 'src/items/item-ellipse.cpp', size 7863 */
  24652. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  24653. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24654. //////////////////// QCPItemEllipse
  24655. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24656. /*! \class QCPItemEllipse
  24657. \brief An ellipse
  24658. \image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions."
  24659. It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be drawn in.
  24660. */
  24661. /*!
  24662. Creates an ellipse item and sets default values.
  24663. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24664. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24665. */
  24666. QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) :
  24667. QCPAbstractItem(parentPlot),
  24668. topLeft(createPosition(QLatin1String("topLeft"))),
  24669. bottomRight(createPosition(QLatin1String("bottomRight"))),
  24670. topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim)),
  24671. top(createAnchor(QLatin1String("top"), aiTop)),
  24672. topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim)),
  24673. right(createAnchor(QLatin1String("right"), aiRight)),
  24674. bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim)),
  24675. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  24676. bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim)),
  24677. left(createAnchor(QLatin1String("left"), aiLeft)),
  24678. center(createAnchor(QLatin1String("center"), aiCenter))
  24679. {
  24680. topLeft->setCoords(0, 1);
  24681. bottomRight->setCoords(1, 0);
  24682. setPen(QPen(Qt::black));
  24683. setSelectedPen(QPen(Qt::blue, 2));
  24684. setBrush(Qt::NoBrush);
  24685. setSelectedBrush(Qt::NoBrush);
  24686. }
  24687. QCPItemEllipse::~QCPItemEllipse()
  24688. {
  24689. }
  24690. /*!
  24691. Sets the pen that will be used to draw the line of the ellipse
  24692. \see setSelectedPen, setBrush
  24693. */
  24694. void QCPItemEllipse::setPen(const QPen &pen)
  24695. {
  24696. mPen = pen;
  24697. }
  24698. /*!
  24699. Sets the pen that will be used to draw the line of the ellipse when selected
  24700. \see setPen, setSelected
  24701. */
  24702. void QCPItemEllipse::setSelectedPen(const QPen &pen)
  24703. {
  24704. mSelectedPen = pen;
  24705. }
  24706. /*!
  24707. Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to
  24708. Qt::NoBrush.
  24709. \see setSelectedBrush, setPen
  24710. */
  24711. void QCPItemEllipse::setBrush(const QBrush &brush)
  24712. {
  24713. mBrush = brush;
  24714. }
  24715. /*!
  24716. Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a
  24717. brush to Qt::NoBrush.
  24718. \see setBrush
  24719. */
  24720. void QCPItemEllipse::setSelectedBrush(const QBrush &brush)
  24721. {
  24722. mSelectedBrush = brush;
  24723. }
  24724. /* inherits documentation from base class */
  24725. double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  24726. {
  24727. Q_UNUSED(details)
  24728. if (onlySelectable && !mSelectable)
  24729. return -1;
  24730. QPointF p1 = topLeft->pixelPosition();
  24731. QPointF p2 = bottomRight->pixelPosition();
  24732. QPointF center((p1+p2)/2.0);
  24733. double a = qAbs(p1.x()-p2.x())/2.0;
  24734. double b = qAbs(p1.y()-p2.y())/2.0;
  24735. double x = pos.x()-center.x();
  24736. double y = pos.y()-center.y();
  24737. // distance to border:
  24738. double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b));
  24739. double result = qAbs(c-1)*qSqrt(x*x+y*y);
  24740. // filled ellipse, allow click inside to count as hit:
  24741. if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
  24742. {
  24743. if (x*x/(a*a) + y*y/(b*b) <= 1)
  24744. result = mParentPlot->selectionTolerance()*0.99;
  24745. }
  24746. return result;
  24747. }
  24748. /* inherits documentation from base class */
  24749. void QCPItemEllipse::draw(QCPPainter *painter)
  24750. {
  24751. QPointF p1 = topLeft->pixelPosition();
  24752. QPointF p2 = bottomRight->pixelPosition();
  24753. if (p1.toPoint() == p2.toPoint())
  24754. return;
  24755. QRectF ellipseRect = QRectF(p1, p2).normalized();
  24756. QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
  24757. if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect
  24758. {
  24759. painter->setPen(mainPen());
  24760. painter->setBrush(mainBrush());
  24761. #ifdef __EXCEPTIONS
  24762. try // drawEllipse sometimes throws exceptions if ellipse is too big
  24763. {
  24764. #endif
  24765. painter->drawEllipse(ellipseRect);
  24766. #ifdef __EXCEPTIONS
  24767. } catch (...)
  24768. {
  24769. qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible";
  24770. setVisible(false);
  24771. }
  24772. #endif
  24773. }
  24774. }
  24775. /* inherits documentation from base class */
  24776. QPointF QCPItemEllipse::anchorPixelPosition(int anchorId) const
  24777. {
  24778. QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition());
  24779. switch (anchorId)
  24780. {
  24781. case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2);
  24782. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  24783. case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2);
  24784. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  24785. case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2);
  24786. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  24787. case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2);
  24788. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
  24789. case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5;
  24790. }
  24791. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  24792. return QPointF();
  24793. }
  24794. /*! \internal
  24795. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  24796. and mSelectedPen when it is.
  24797. */
  24798. QPen QCPItemEllipse::mainPen() const
  24799. {
  24800. return mSelected ? mSelectedPen : mPen;
  24801. }
  24802. /*! \internal
  24803. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  24804. is not selected and mSelectedBrush when it is.
  24805. */
  24806. QBrush QCPItemEllipse::mainBrush() const
  24807. {
  24808. return mSelected ? mSelectedBrush : mBrush;
  24809. }
  24810. /* end of 'src/items/item-ellipse.cpp' */
  24811. /* including file 'src/items/item-pixmap.cpp', size 10615 */
  24812. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  24813. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24814. //////////////////// QCPItemPixmap
  24815. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24816. /*! \class QCPItemPixmap
  24817. \brief An arbitrary pixmap
  24818. \image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions."
  24819. It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will
  24820. be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to
  24821. fit the rectangle or be drawn aligned to the topLeft position.
  24822. If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown
  24823. on the right side of the example image), the pixmap will be flipped in the respective
  24824. orientations.
  24825. */
  24826. /*!
  24827. Creates a rectangle item and sets default values.
  24828. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24829. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24830. */
  24831. QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) :
  24832. QCPAbstractItem(parentPlot),
  24833. topLeft(createPosition(QLatin1String("topLeft"))),
  24834. bottomRight(createPosition(QLatin1String("bottomRight"))),
  24835. top(createAnchor(QLatin1String("top"), aiTop)),
  24836. topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
  24837. right(createAnchor(QLatin1String("right"), aiRight)),
  24838. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  24839. bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
  24840. left(createAnchor(QLatin1String("left"), aiLeft)),
  24841. mScaled(false),
  24842. mScaledPixmapInvalidated(true),
  24843. mAspectRatioMode(Qt::KeepAspectRatio),
  24844. mTransformationMode(Qt::SmoothTransformation)
  24845. {
  24846. topLeft->setCoords(0, 1);
  24847. bottomRight->setCoords(1, 0);
  24848. setPen(Qt::NoPen);
  24849. setSelectedPen(QPen(Qt::blue));
  24850. }
  24851. QCPItemPixmap::~QCPItemPixmap()
  24852. {
  24853. }
  24854. /*!
  24855. Sets the pixmap that will be displayed.
  24856. */
  24857. void QCPItemPixmap::setPixmap(const QPixmap &pixmap)
  24858. {
  24859. mPixmap = pixmap;
  24860. mScaledPixmapInvalidated = true;
  24861. if (mPixmap.isNull())
  24862. qDebug() << Q_FUNC_INFO << "pixmap is null";
  24863. }
  24864. /*!
  24865. Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a
  24866. bottomRight positions.
  24867. */
  24868. void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformationMode)
  24869. {
  24870. mScaled = scaled;
  24871. mAspectRatioMode = aspectRatioMode;
  24872. mTransformationMode = transformationMode;
  24873. mScaledPixmapInvalidated = true;
  24874. }
  24875. /*!
  24876. Sets the pen that will be used to draw a border around the pixmap.
  24877. \see setSelectedPen, setBrush
  24878. */
  24879. void QCPItemPixmap::setPen(const QPen &pen)
  24880. {
  24881. mPen = pen;
  24882. }
  24883. /*!
  24884. Sets the pen that will be used to draw a border around the pixmap when selected
  24885. \see setPen, setSelected
  24886. */
  24887. void QCPItemPixmap::setSelectedPen(const QPen &pen)
  24888. {
  24889. mSelectedPen = pen;
  24890. }
  24891. /* inherits documentation from base class */
  24892. double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  24893. {
  24894. Q_UNUSED(details)
  24895. if (onlySelectable && !mSelectable)
  24896. return -1;
  24897. return rectDistance(getFinalRect(), pos, true);
  24898. }
  24899. /* inherits documentation from base class */
  24900. void QCPItemPixmap::draw(QCPPainter *painter)
  24901. {
  24902. bool flipHorz = false;
  24903. bool flipVert = false;
  24904. QRect rect = getFinalRect(&flipHorz, &flipVert);
  24905. double clipPad = mainPen().style() == Qt::NoPen ? 0 : mainPen().widthF();
  24906. QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  24907. if (boundingRect.intersects(clipRect()))
  24908. {
  24909. updateScaledPixmap(rect, flipHorz, flipVert);
  24910. painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap);
  24911. QPen pen = mainPen();
  24912. if (pen.style() != Qt::NoPen)
  24913. {
  24914. painter->setPen(pen);
  24915. painter->setBrush(Qt::NoBrush);
  24916. painter->drawRect(rect);
  24917. }
  24918. }
  24919. }
  24920. /* inherits documentation from base class */
  24921. QPointF QCPItemPixmap::anchorPixelPosition(int anchorId) const
  24922. {
  24923. bool flipHorz;
  24924. bool flipVert;
  24925. QRect rect = getFinalRect(&flipHorz, &flipVert);
  24926. // we actually want denormal rects (negative width/height) here, so restore
  24927. // the flipped state:
  24928. if (flipHorz)
  24929. rect.adjust(rect.width(), 0, -rect.width(), 0);
  24930. if (flipVert)
  24931. rect.adjust(0, rect.height(), 0, -rect.height());
  24932. switch (anchorId)
  24933. {
  24934. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  24935. case aiTopRight: return rect.topRight();
  24936. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  24937. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  24938. case aiBottomLeft: return rect.bottomLeft();
  24939. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;;
  24940. }
  24941. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  24942. return QPointF();
  24943. }
  24944. /*! \internal
  24945. Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The
  24946. parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped
  24947. horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a
  24948. bottomRight.)
  24949. This function only creates the scaled pixmap when the buffered pixmap has a different size than
  24950. the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does
  24951. not cause expensive rescaling every time.
  24952. If scaling is disabled, sets mScaledPixmap to a null QPixmap.
  24953. */
  24954. void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert)
  24955. {
  24956. if (mPixmap.isNull())
  24957. return;
  24958. if (mScaled)
  24959. {
  24960. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  24961. double devicePixelRatio = mPixmap.devicePixelRatio();
  24962. #else
  24963. double devicePixelRatio = 1.0;
  24964. #endif
  24965. if (finalRect.isNull())
  24966. finalRect = getFinalRect(&flipHorz, &flipVert);
  24967. if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size()/devicePixelRatio)
  24968. {
  24969. mScaledPixmap = mPixmap.scaled(finalRect.size()*devicePixelRatio, mAspectRatioMode, mTransformationMode);
  24970. if (flipHorz || flipVert)
  24971. mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert));
  24972. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  24973. mScaledPixmap.setDevicePixelRatio(devicePixelRatio);
  24974. #endif
  24975. }
  24976. } else if (!mScaledPixmap.isNull())
  24977. mScaledPixmap = QPixmap();
  24978. mScaledPixmapInvalidated = false;
  24979. }
  24980. /*! \internal
  24981. Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions
  24982. and scaling settings.
  24983. The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn
  24984. flipped horizontally or vertically in the returned rect. (The returned rect itself is always
  24985. normalized, i.e. the top left corner of the rect is actually further to the top/left than the
  24986. bottom right corner). This is the case when the item position \a topLeft is further to the
  24987. bottom/right than \a bottomRight.
  24988. If scaling is disabled, returns a rect with size of the original pixmap and the top left corner
  24989. aligned with the item position \a topLeft. The position \a bottomRight is ignored.
  24990. */
  24991. QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const
  24992. {
  24993. QRect result;
  24994. bool flipHorz = false;
  24995. bool flipVert = false;
  24996. QPoint p1 = topLeft->pixelPosition().toPoint();
  24997. QPoint p2 = bottomRight->pixelPosition().toPoint();
  24998. if (p1 == p2)
  24999. return QRect(p1, QSize(0, 0));
  25000. if (mScaled)
  25001. {
  25002. QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y());
  25003. QPoint topLeft = p1;
  25004. if (newSize.width() < 0)
  25005. {
  25006. flipHorz = true;
  25007. newSize.rwidth() *= -1;
  25008. topLeft.setX(p2.x());
  25009. }
  25010. if (newSize.height() < 0)
  25011. {
  25012. flipVert = true;
  25013. newSize.rheight() *= -1;
  25014. topLeft.setY(p2.y());
  25015. }
  25016. QSize scaledSize = mPixmap.size();
  25017. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  25018. scaledSize /= mPixmap.devicePixelRatio();
  25019. scaledSize.scale(newSize*mPixmap.devicePixelRatio(), mAspectRatioMode);
  25020. #else
  25021. scaledSize.scale(newSize, mAspectRatioMode);
  25022. #endif
  25023. result = QRect(topLeft, scaledSize);
  25024. } else
  25025. {
  25026. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  25027. result = QRect(p1, mPixmap.size()/mPixmap.devicePixelRatio());
  25028. #else
  25029. result = QRect(p1, mPixmap.size());
  25030. #endif
  25031. }
  25032. if (flippedHorz)
  25033. *flippedHorz = flipHorz;
  25034. if (flippedVert)
  25035. *flippedVert = flipVert;
  25036. return result;
  25037. }
  25038. /*! \internal
  25039. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  25040. and mSelectedPen when it is.
  25041. */
  25042. QPen QCPItemPixmap::mainPen() const
  25043. {
  25044. return mSelected ? mSelectedPen : mPen;
  25045. }
  25046. /* end of 'src/items/item-pixmap.cpp' */
  25047. /* including file 'src/items/item-tracer.cpp', size 14624 */
  25048. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  25049. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25050. //////////////////// QCPItemTracer
  25051. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25052. /*! \class QCPItemTracer
  25053. \brief Item that sticks to QCPGraph data points
  25054. \image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs are positions."
  25055. The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt
  25056. the coordinate axes of the graph and update its \a position to be on the graph's data. This means
  25057. the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a
  25058. QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a
  25059. position will have no effect because they will be overriden in the next redraw (this is when the
  25060. coordinate update happens).
  25061. If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will
  25062. stay at the corresponding end of the graph.
  25063. With \ref setInterpolating you may specify whether the tracer may only stay exactly on data
  25064. points or whether it interpolates data points linearly, if given a key that lies between two data
  25065. points of the graph.
  25066. The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer
  25067. have no own visual appearance (set the style to \ref tsNone), and just connect other item
  25068. positions to the tracer \a position (used as an anchor) via \ref
  25069. QCPItemPosition::setParentAnchor.
  25070. \note The tracer position is only automatically updated upon redraws. So when the data of the
  25071. graph changes and immediately afterwards (without a redraw) the position coordinates of the
  25072. tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref
  25073. updatePosition must be called manually, prior to reading the tracer coordinates.
  25074. */
  25075. /*!
  25076. Creates a tracer item and sets default values.
  25077. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  25078. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  25079. */
  25080. QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) :
  25081. QCPAbstractItem(parentPlot),
  25082. position(createPosition(QLatin1String("position"))),
  25083. mSize(6),
  25084. mStyle(tsCrosshair),
  25085. mGraph(0),
  25086. mGraphKey(0),
  25087. mInterpolating(false)
  25088. {
  25089. position->setCoords(0, 0);
  25090. setBrush(Qt::NoBrush);
  25091. setSelectedBrush(Qt::NoBrush);
  25092. setPen(QPen(Qt::black));
  25093. setSelectedPen(QPen(Qt::blue, 2));
  25094. }
  25095. QCPItemTracer::~QCPItemTracer()
  25096. {
  25097. }
  25098. /*!
  25099. Sets the pen that will be used to draw the line of the tracer
  25100. \see setSelectedPen, setBrush
  25101. */
  25102. void QCPItemTracer::setPen(const QPen &pen)
  25103. {
  25104. mPen = pen;
  25105. }
  25106. /*!
  25107. Sets the pen that will be used to draw the line of the tracer when selected
  25108. \see setPen, setSelected
  25109. */
  25110. void QCPItemTracer::setSelectedPen(const QPen &pen)
  25111. {
  25112. mSelectedPen = pen;
  25113. }
  25114. /*!
  25115. Sets the brush that will be used to draw any fills of the tracer
  25116. \see setSelectedBrush, setPen
  25117. */
  25118. void QCPItemTracer::setBrush(const QBrush &brush)
  25119. {
  25120. mBrush = brush;
  25121. }
  25122. /*!
  25123. Sets the brush that will be used to draw any fills of the tracer, when selected.
  25124. \see setBrush, setSelected
  25125. */
  25126. void QCPItemTracer::setSelectedBrush(const QBrush &brush)
  25127. {
  25128. mSelectedBrush = brush;
  25129. }
  25130. /*!
  25131. Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare
  25132. does, \ref tsCrosshair does not).
  25133. */
  25134. void QCPItemTracer::setSize(double size)
  25135. {
  25136. mSize = size;
  25137. }
  25138. /*!
  25139. Sets the style/visual appearance of the tracer.
  25140. If you only want to use the tracer \a position as an anchor for other items, set \a style to
  25141. \ref tsNone.
  25142. */
  25143. void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style)
  25144. {
  25145. mStyle = style;
  25146. }
  25147. /*!
  25148. Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type
  25149. QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph.
  25150. To free the tracer from any graph, set \a graph to 0. The tracer \a position can then be placed
  25151. freely like any other item position. This is the state the tracer will assume when its graph gets
  25152. deleted while still attached to it.
  25153. \see setGraphKey
  25154. */
  25155. void QCPItemTracer::setGraph(QCPGraph *graph)
  25156. {
  25157. if (graph)
  25158. {
  25159. if (graph->parentPlot() == mParentPlot)
  25160. {
  25161. position->setType(QCPItemPosition::ptPlotCoords);
  25162. position->setAxes(graph->keyAxis(), graph->valueAxis());
  25163. mGraph = graph;
  25164. updatePosition();
  25165. } else
  25166. qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item";
  25167. } else
  25168. {
  25169. mGraph = 0;
  25170. }
  25171. }
  25172. /*!
  25173. Sets the key of the graph's data point the tracer will be positioned at. This is the only free
  25174. coordinate of a tracer when attached to a graph.
  25175. Depending on \ref setInterpolating, the tracer will be either positioned on the data point
  25176. closest to \a key, or will stay exactly at \a key and interpolate the value linearly.
  25177. \see setGraph, setInterpolating
  25178. */
  25179. void QCPItemTracer::setGraphKey(double key)
  25180. {
  25181. mGraphKey = key;
  25182. }
  25183. /*!
  25184. Sets whether the value of the graph's data points shall be interpolated, when positioning the
  25185. tracer.
  25186. If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on
  25187. the data point of the graph which is closest to the key, but which is not necessarily exactly
  25188. there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and
  25189. the appropriate value will be interpolated from the graph's data points linearly.
  25190. \see setGraph, setGraphKey
  25191. */
  25192. void QCPItemTracer::setInterpolating(bool enabled)
  25193. {
  25194. mInterpolating = enabled;
  25195. }
  25196. /* inherits documentation from base class */
  25197. double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25198. {
  25199. Q_UNUSED(details)
  25200. if (onlySelectable && !mSelectable)
  25201. return -1;
  25202. QPointF center(position->pixelPosition());
  25203. double w = mSize/2.0;
  25204. QRect clip = clipRect();
  25205. switch (mStyle)
  25206. {
  25207. case tsNone: return -1;
  25208. case tsPlus:
  25209. {
  25210. if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  25211. return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(center+QPointF(-w, 0), center+QPointF(w, 0)),
  25212. QCPVector2D(pos).distanceSquaredToLine(center+QPointF(0, -w), center+QPointF(0, w))));
  25213. break;
  25214. }
  25215. case tsCrosshair:
  25216. {
  25217. return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(clip.left(), center.y()), QCPVector2D(clip.right(), center.y())),
  25218. QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(center.x(), clip.top()), QCPVector2D(center.x(), clip.bottom()))));
  25219. }
  25220. case tsCircle:
  25221. {
  25222. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  25223. {
  25224. // distance to border:
  25225. double centerDist = QCPVector2D(center-pos).length();
  25226. double circleLine = w;
  25227. double result = qAbs(centerDist-circleLine);
  25228. // filled ellipse, allow click inside to count as hit:
  25229. if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
  25230. {
  25231. if (centerDist <= circleLine)
  25232. result = mParentPlot->selectionTolerance()*0.99;
  25233. }
  25234. return result;
  25235. }
  25236. break;
  25237. }
  25238. case tsSquare:
  25239. {
  25240. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  25241. {
  25242. QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w));
  25243. bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
  25244. return rectDistance(rect, pos, filledRect);
  25245. }
  25246. break;
  25247. }
  25248. }
  25249. return -1;
  25250. }
  25251. /* inherits documentation from base class */
  25252. void QCPItemTracer::draw(QCPPainter *painter)
  25253. {
  25254. updatePosition();
  25255. if (mStyle == tsNone)
  25256. return;
  25257. painter->setPen(mainPen());
  25258. painter->setBrush(mainBrush());
  25259. QPointF center(position->pixelPosition());
  25260. double w = mSize/2.0;
  25261. QRect clip = clipRect();
  25262. switch (mStyle)
  25263. {
  25264. case tsNone: return;
  25265. case tsPlus:
  25266. {
  25267. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  25268. {
  25269. painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0)));
  25270. painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w)));
  25271. }
  25272. break;
  25273. }
  25274. case tsCrosshair:
  25275. {
  25276. if (center.y() > clip.top() && center.y() < clip.bottom())
  25277. painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y()));
  25278. if (center.x() > clip.left() && center.x() < clip.right())
  25279. painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom()));
  25280. break;
  25281. }
  25282. case tsCircle:
  25283. {
  25284. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  25285. painter->drawEllipse(center, w, w);
  25286. break;
  25287. }
  25288. case tsSquare:
  25289. {
  25290. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  25291. painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w)));
  25292. break;
  25293. }
  25294. }
  25295. }
  25296. /*!
  25297. If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a
  25298. position to reside on the graph data, depending on the configured key (\ref setGraphKey).
  25299. It is called automatically on every redraw and normally doesn't need to be called manually. One
  25300. exception is when you want to read the tracer coordinates via \a position and are not sure that
  25301. the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw.
  25302. In that situation, call this function before accessing \a position, to make sure you don't get
  25303. out-of-date coordinates.
  25304. If there is no graph set on this tracer, this function does nothing.
  25305. */
  25306. void QCPItemTracer::updatePosition()
  25307. {
  25308. if (mGraph)
  25309. {
  25310. if (mParentPlot->hasPlottable(mGraph))
  25311. {
  25312. if (mGraph->data()->size() > 1)
  25313. {
  25314. QCPGraphDataContainer::const_iterator first = mGraph->data()->constBegin();
  25315. QCPGraphDataContainer::const_iterator last = mGraph->data()->constEnd()-1;
  25316. if (mGraphKey <= first->key)
  25317. position->setCoords(first->key, first->value);
  25318. else if (mGraphKey >= last->key)
  25319. position->setCoords(last->key, last->value);
  25320. else
  25321. {
  25322. QCPGraphDataContainer::const_iterator it = mGraph->data()->findBegin(mGraphKey);
  25323. if (it != mGraph->data()->constEnd()) // mGraphKey is not exactly on last iterator, but somewhere between iterators
  25324. {
  25325. QCPGraphDataContainer::const_iterator prevIt = it;
  25326. ++it; // won't advance to constEnd because we handled that case (mGraphKey >= last->key) before
  25327. if (mInterpolating)
  25328. {
  25329. // interpolate between iterators around mGraphKey:
  25330. double slope = 0;
  25331. if (!qFuzzyCompare((double)it->key, (double)prevIt->key))
  25332. slope = (it->value-prevIt->value)/(it->key-prevIt->key);
  25333. position->setCoords(mGraphKey, (mGraphKey-prevIt->key)*slope+prevIt->value);
  25334. } else
  25335. {
  25336. // find iterator with key closest to mGraphKey:
  25337. if (mGraphKey < (prevIt->key+it->key)*0.5)
  25338. position->setCoords(prevIt->key, prevIt->value);
  25339. else
  25340. position->setCoords(it->key, it->value);
  25341. }
  25342. } else // mGraphKey is exactly on last iterator (should actually be caught when comparing first/last keys, but this is a failsafe for fp uncertainty)
  25343. position->setCoords(it->key, it->value);
  25344. }
  25345. } else if (mGraph->data()->size() == 1)
  25346. {
  25347. QCPGraphDataContainer::const_iterator it = mGraph->data()->constBegin();
  25348. position->setCoords(it->key, it->value);
  25349. } else
  25350. qDebug() << Q_FUNC_INFO << "graph has no data";
  25351. } else
  25352. qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)";
  25353. }
  25354. }
  25355. /*! \internal
  25356. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  25357. and mSelectedPen when it is.
  25358. */
  25359. QPen QCPItemTracer::mainPen() const
  25360. {
  25361. return mSelected ? mSelectedPen : mPen;
  25362. }
  25363. /*! \internal
  25364. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  25365. is not selected and mSelectedBrush when it is.
  25366. */
  25367. QBrush QCPItemTracer::mainBrush() const
  25368. {
  25369. return mSelected ? mSelectedBrush : mBrush;
  25370. }
  25371. /* end of 'src/items/item-tracer.cpp' */
  25372. /* including file 'src/items/item-bracket.cpp', size 10687 */
  25373. /* commit 9868e55d3b412f2f89766bb482fcf299e93a0988 2017-09-04 01:56:22 +0200 */
  25374. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25375. //////////////////// QCPItemBracket
  25376. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25377. /*! \class QCPItemBracket
  25378. \brief A bracket for referencing/highlighting certain parts in the plot.
  25379. \image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs are positions."
  25380. It has two positions, \a left and \a right, which define the span of the bracket. If \a left is
  25381. actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the
  25382. example image.
  25383. The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket
  25384. stretches away from the embraced span, can be controlled with \ref setLength.
  25385. \image html QCPItemBracket-length.png
  25386. <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
  25387. bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
  25388. It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine
  25389. or QCPItemCurve) or a text label (QCPItemText), to the bracket.
  25390. */
  25391. /*!
  25392. Creates a bracket item and sets default values.
  25393. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  25394. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  25395. */
  25396. QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) :
  25397. QCPAbstractItem(parentPlot),
  25398. left(createPosition(QLatin1String("left"))),
  25399. right(createPosition(QLatin1String("right"))),
  25400. center(createAnchor(QLatin1String("center"), aiCenter)),
  25401. mLength(8),
  25402. mStyle(bsCalligraphic)
  25403. {
  25404. left->setCoords(0, 0);
  25405. right->setCoords(1, 1);
  25406. setPen(QPen(Qt::black));
  25407. setSelectedPen(QPen(Qt::blue, 2));
  25408. }
  25409. QCPItemBracket::~QCPItemBracket()
  25410. {
  25411. }
  25412. /*!
  25413. Sets the pen that will be used to draw the bracket.
  25414. Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the
  25415. stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use
  25416. \ref setLength, which has a similar effect.
  25417. \see setSelectedPen
  25418. */
  25419. void QCPItemBracket::setPen(const QPen &pen)
  25420. {
  25421. mPen = pen;
  25422. }
  25423. /*!
  25424. Sets the pen that will be used to draw the bracket when selected
  25425. \see setPen, setSelected
  25426. */
  25427. void QCPItemBracket::setSelectedPen(const QPen &pen)
  25428. {
  25429. mSelectedPen = pen;
  25430. }
  25431. /*!
  25432. Sets the \a length in pixels how far the bracket extends in the direction towards the embraced
  25433. span of the bracket (i.e. perpendicular to the <i>left</i>-<i>right</i>-direction)
  25434. \image html QCPItemBracket-length.png
  25435. <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
  25436. bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
  25437. */
  25438. void QCPItemBracket::setLength(double length)
  25439. {
  25440. mLength = length;
  25441. }
  25442. /*!
  25443. Sets the style of the bracket, i.e. the shape/visual appearance.
  25444. \see setPen
  25445. */
  25446. void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style)
  25447. {
  25448. mStyle = style;
  25449. }
  25450. /* inherits documentation from base class */
  25451. double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25452. {
  25453. Q_UNUSED(details)
  25454. if (onlySelectable && !mSelectable)
  25455. return -1;
  25456. QCPVector2D p(pos);
  25457. QCPVector2D leftVec(left->pixelPosition());
  25458. QCPVector2D rightVec(right->pixelPosition());
  25459. if (leftVec.toPoint() == rightVec.toPoint())
  25460. return -1;
  25461. QCPVector2D widthVec = (rightVec-leftVec)*0.5;
  25462. QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
  25463. QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
  25464. switch (mStyle)
  25465. {
  25466. case QCPItemBracket::bsSquare:
  25467. case QCPItemBracket::bsRound:
  25468. {
  25469. double a = p.distanceSquaredToLine(centerVec-widthVec, centerVec+widthVec);
  25470. double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec, centerVec-widthVec);
  25471. double c = p.distanceSquaredToLine(centerVec+widthVec+lengthVec, centerVec+widthVec);
  25472. return qSqrt(qMin(qMin(a, b), c));
  25473. }
  25474. case QCPItemBracket::bsCurly:
  25475. case QCPItemBracket::bsCalligraphic:
  25476. {
  25477. double a = p.distanceSquaredToLine(centerVec-widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3);
  25478. double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec*0.7, centerVec-widthVec*0.75+lengthVec*0.15);
  25479. double c = p.distanceSquaredToLine(centerVec+widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3);
  25480. double d = p.distanceSquaredToLine(centerVec+widthVec+lengthVec*0.7, centerVec+widthVec*0.75+lengthVec*0.15);
  25481. return qSqrt(qMin(qMin(a, b), qMin(c, d)));
  25482. }
  25483. }
  25484. return -1;
  25485. }
  25486. /* inherits documentation from base class */
  25487. void QCPItemBracket::draw(QCPPainter *painter)
  25488. {
  25489. QCPVector2D leftVec(left->pixelPosition());
  25490. QCPVector2D rightVec(right->pixelPosition());
  25491. if (leftVec.toPoint() == rightVec.toPoint())
  25492. return;
  25493. QCPVector2D widthVec = (rightVec-leftVec)*0.5;
  25494. QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
  25495. QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
  25496. QPolygon boundingPoly;
  25497. boundingPoly << leftVec.toPoint() << rightVec.toPoint()
  25498. << (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint();
  25499. QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
  25500. if (clip.intersects(boundingPoly.boundingRect()))
  25501. {
  25502. painter->setPen(mainPen());
  25503. switch (mStyle)
  25504. {
  25505. case bsSquare:
  25506. {
  25507. painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF());
  25508. painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
  25509. painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  25510. break;
  25511. }
  25512. case bsRound:
  25513. {
  25514. painter->setBrush(Qt::NoBrush);
  25515. QPainterPath path;
  25516. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  25517. path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF());
  25518. path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  25519. painter->drawPath(path);
  25520. break;
  25521. }
  25522. case bsCurly:
  25523. {
  25524. painter->setBrush(Qt::NoBrush);
  25525. QPainterPath path;
  25526. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  25527. path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+lengthVec).toPointF(), centerVec.toPointF());
  25528. path.cubicTo((centerVec-0.4*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  25529. painter->drawPath(path);
  25530. break;
  25531. }
  25532. case bsCalligraphic:
  25533. {
  25534. painter->setPen(Qt::NoPen);
  25535. painter->setBrush(QBrush(mainPen().color()));
  25536. QPainterPath path;
  25537. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  25538. path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+0.8*lengthVec).toPointF(), centerVec.toPointF());
  25539. path.cubicTo((centerVec-0.4*widthVec+0.8*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  25540. path.cubicTo((centerVec-widthVec-lengthVec*0.5).toPointF(), (centerVec-0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+lengthVec*0.2).toPointF());
  25541. path.cubicTo((centerVec+0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
  25542. painter->drawPath(path);
  25543. break;
  25544. }
  25545. }
  25546. }
  25547. }
  25548. /* inherits documentation from base class */
  25549. QPointF QCPItemBracket::anchorPixelPosition(int anchorId) const
  25550. {
  25551. QCPVector2D leftVec(left->pixelPosition());
  25552. QCPVector2D rightVec(right->pixelPosition());
  25553. if (leftVec.toPoint() == rightVec.toPoint())
  25554. return leftVec.toPointF();
  25555. QCPVector2D widthVec = (rightVec-leftVec)*0.5;
  25556. QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
  25557. QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
  25558. switch (anchorId)
  25559. {
  25560. case aiCenter:
  25561. return centerVec.toPointF();
  25562. }
  25563. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  25564. return QPointF();
  25565. }
  25566. /*! \internal
  25567. Returns the pen that should be used for drawing lines. Returns mPen when the
  25568. item is not selected and mSelectedPen when it is.
  25569. */
  25570. QPen QCPItemBracket::mainPen() const
  25571. {
  25572. return mSelected ? mSelectedPen : mPen;
  25573. }
  25574. /* end of 'src/items/item-bracket.cpp' */