1
1

qcustomplot.cpp 748 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370
  1. /***************************************************************************
  2. ** **
  3. ** QCustomPlot, an easy to use, modern plotting widget for Qt **
  4. ** Copyright (C) 2011, 2012, 2013, 2014 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: 07.04.14 **
  23. ** Version: 1.2.1 **
  24. ****************************************************************************/
  25. #include "stdafx.h"
  26. #include "qcustomplot.h"
  27. ////////////////////////////////////////////////////////////////////////////////////////////////////
  28. //////////////////// QCPPainter
  29. ////////////////////////////////////////////////////////////////////////////////////////////////////
  30. /*! \class QCPPainter
  31. \brief QPainter subclass used internally
  32. This QPainter subclass is used to provide some extended functionality e.g. for tweaking position
  33. consistency between antialiased and non-antialiased painting. Further it provides workarounds
  34. for QPainter quirks.
  35. \warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and
  36. restore. So while it is possible to pass a QCPPainter instance to a function that expects a
  37. QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because
  38. it will call the base class implementations of the functions actually hidden by QCPPainter).
  39. */
  40. /*!
  41. Creates a new QCPPainter instance and sets default values
  42. */
  43. QCPPainter::QCPPainter() :
  44. QPainter(),
  45. mModes(pmDefault),
  46. mIsAntialiasing(false)
  47. {
  48. // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and
  49. // a call to begin() will follow
  50. }
  51. /*!
  52. Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just
  53. like the analogous QPainter constructor, begins painting on \a device immediately.
  54. Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5.
  55. */
  56. QCPPainter::QCPPainter(QPaintDevice *device) :
  57. QPainter(device),
  58. mModes(pmDefault),
  59. mIsAntialiasing(false)
  60. {
  61. #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.
  62. if (isActive())
  63. setRenderHint(QPainter::NonCosmeticDefaultPen);
  64. #endif
  65. }
  66. QCPPainter::~QCPPainter()
  67. {
  68. }
  69. /*!
  70. Sets the pen of the painter and applies certain fixes to it, depending on the mode of this
  71. QCPPainter.
  72. \note this function hides the non-virtual base class implementation.
  73. */
  74. void QCPPainter::setPen(const QPen &pen)
  75. {
  76. QPainter::setPen(pen);
  77. if (mModes.testFlag(pmNonCosmetic))
  78. makeNonCosmetic();
  79. }
  80. /*! \overload
  81. Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of
  82. this QCPPainter.
  83. \note this function hides the non-virtual base class implementation.
  84. */
  85. void QCPPainter::setPen(const QColor &color)
  86. {
  87. QPainter::setPen(color);
  88. if (mModes.testFlag(pmNonCosmetic))
  89. makeNonCosmetic();
  90. }
  91. /*! \overload
  92. Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of
  93. this QCPPainter.
  94. \note this function hides the non-virtual base class implementation.
  95. */
  96. void QCPPainter::setPen(Qt::PenStyle penStyle)
  97. {
  98. QPainter::setPen(penStyle);
  99. if (mModes.testFlag(pmNonCosmetic))
  100. makeNonCosmetic();
  101. }
  102. /*! \overload
  103. Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when
  104. antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to
  105. integer coordinates and then passes it to the original drawLine.
  106. \note this function hides the non-virtual base class implementation.
  107. */
  108. void QCPPainter::drawLine(const QLineF &line)
  109. {
  110. if (mIsAntialiasing || mModes.testFlag(pmVectorized))
  111. QPainter::drawLine(line);
  112. else
  113. QPainter::drawLine(line.toLine());
  114. }
  115. /*!
  116. Sets whether painting uses antialiasing or not. Use this method instead of using setRenderHint
  117. with QPainter::Antialiasing directly, as it allows QCPPainter to regain pixel exactness between
  118. antialiased and non-antialiased painting (Since Qt < 5.0 uses slightly different coordinate systems for
  119. AA/Non-AA painting).
  120. */
  121. void QCPPainter::setAntialiasing(bool enabled)
  122. {
  123. setRenderHint(QPainter::Antialiasing, enabled);
  124. if (mIsAntialiasing != enabled)
  125. {
  126. mIsAntialiasing = enabled;
  127. if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs
  128. {
  129. if (mIsAntialiasing)
  130. translate(0.5, 0.5);
  131. else
  132. translate(-0.5, -0.5);
  133. }
  134. }
  135. }
  136. /*!
  137. Sets the mode of the painter. This controls whether the painter shall adjust its
  138. fixes/workarounds optimized for certain output devices.
  139. */
  140. void QCPPainter::setModes(QCPPainter::PainterModes modes)
  141. {
  142. mModes = modes;
  143. }
  144. /*!
  145. Sets the QPainter::NonCosmeticDefaultPen in Qt versions before Qt5 after beginning painting on \a
  146. device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5,
  147. all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that
  148. behaviour.
  149. The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets
  150. the render hint as appropriate.
  151. \note this function hides the non-virtual base class implementation.
  152. */
  153. bool QCPPainter::begin(QPaintDevice *device)
  154. {
  155. bool result = QPainter::begin(device);
  156. #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.
  157. if (result)
  158. setRenderHint(QPainter::NonCosmeticDefaultPen);
  159. #endif
  160. return result;
  161. }
  162. /*! \overload
  163. Sets the mode of the painter. This controls whether the painter shall adjust its
  164. fixes/workarounds optimized for certain output devices.
  165. */
  166. void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled)
  167. {
  168. if (!enabled && mModes.testFlag(mode))
  169. mModes &= ~mode;
  170. else if (enabled && !mModes.testFlag(mode))
  171. mModes |= mode;
  172. }
  173. /*!
  174. Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to
  175. QPainter, the save/restore functions are reimplemented to also save/restore those members.
  176. \note this function hides the non-virtual base class implementation.
  177. \see restore
  178. */
  179. void QCPPainter::save()
  180. {
  181. mAntialiasingStack.push(mIsAntialiasing);
  182. QPainter::save();
  183. }
  184. /*!
  185. Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to
  186. QPainter, the save/restore functions are reimplemented to also save/restore those members.
  187. \note this function hides the non-virtual base class implementation.
  188. \see save
  189. */
  190. void QCPPainter::restore()
  191. {
  192. if (!mAntialiasingStack.isEmpty())
  193. mIsAntialiasing = mAntialiasingStack.pop();
  194. else
  195. qDebug() << Q_FUNC_INFO << "Unbalanced save/restore";
  196. QPainter::restore();
  197. }
  198. /*!
  199. Changes the pen width to 1 if it currently is 0. This function is called in the \ref setPen
  200. overrides when the \ref pmNonCosmetic mode is set.
  201. */
  202. void QCPPainter::makeNonCosmetic()
  203. {
  204. if (qFuzzyIsNull(pen().widthF()))
  205. {
  206. QPen p = pen();
  207. p.setWidth(1);
  208. QPainter::setPen(p);
  209. }
  210. }
  211. ////////////////////////////////////////////////////////////////////////////////////////////////////
  212. //////////////////// QCPScatterStyle
  213. ////////////////////////////////////////////////////////////////////////////////////////////////////
  214. /*! \class QCPScatterStyle
  215. \brief Represents the visual appearance of scatter points
  216. This class holds information about shape, color and size of scatter points. In plottables like
  217. QCPGraph it is used to store how scatter points shall be drawn. For example, \ref
  218. QCPGraph::setScatterStyle takes a QCPScatterStyle instance.
  219. A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a
  220. fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can
  221. be controlled with \ref setSize.
  222. \section QCPScatterStyle-defining Specifying a scatter style
  223. You can set all these configurations either by calling the respective functions on an instance:
  224. \code
  225. QCPScatterStyle myScatter;
  226. myScatter.setShape(QCPScatterStyle::ssCircle);
  227. myScatter.setPen(Qt::blue);
  228. myScatter.setBrush(Qt::white);
  229. myScatter.setSize(5);
  230. customPlot->graph(0)->setScatterStyle(myScatter);
  231. \endcode
  232. Or you can use one of the various constructors that take different parameter combinations, making
  233. it easy to specify a scatter style in a single call, like so:
  234. \code
  235. customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, Qt::white, 5));
  236. \endcode
  237. \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable
  238. There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref
  239. QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref
  240. isPenDefined will return false. It leads to scatter points that inherit the pen from the
  241. plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line
  242. color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes
  243. it very convenient to set up typical scatter settings:
  244. \code
  245. customPlot->graph(0)->setScatterStyle(QCPScatterStyle::ssPlus);
  246. \endcode
  247. Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works
  248. because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly
  249. into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size)
  250. constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref
  251. ScatterShape, where actually a QCPScatterStyle is expected.
  252. \section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps
  253. QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points.
  254. For custom shapes, you can provide a QPainterPath with the desired shape to the \ref
  255. setCustomPath function or call the constructor that takes a painter path. The scatter shape will
  256. automatically be set to \ref ssCustom.
  257. For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the
  258. constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap.
  259. Note that \ref setSize does not influence the appearance of the pixmap.
  260. */
  261. /* start documentation of inline functions */
  262. /*! \fn bool QCPScatterStyle::isNone() const
  263. Returns whether the scatter shape is \ref ssNone.
  264. \see setShape
  265. */
  266. /*! \fn bool QCPScatterStyle::isPenDefined() const
  267. Returns whether a pen has been defined for this scatter style.
  268. The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those are
  269. \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen is
  270. left undefined, the scatter color will be inherited from the plottable that uses this scatter
  271. style.
  272. \see setPen
  273. */
  274. /* end documentation of inline functions */
  275. /*!
  276. Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined.
  277. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
  278. from the plottable that uses this scatter style.
  279. */
  280. QCPScatterStyle::QCPScatterStyle() :
  281. mSize(6),
  282. mShape(ssNone),
  283. mPen(Qt::NoPen),
  284. mBrush(Qt::NoBrush),
  285. mPenDefined(false)
  286. {
  287. }
  288. /*!
  289. Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or
  290. brush is defined.
  291. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
  292. from the plottable that uses this scatter style.
  293. */
  294. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) :
  295. mSize(size),
  296. mShape(shape),
  297. mPen(Qt::NoPen),
  298. mBrush(Qt::NoBrush),
  299. mPenDefined(false)
  300. {
  301. }
  302. /*!
  303. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
  304. and size to \a size. No brush is defined, i.e. the scatter point will not be filled.
  305. */
  306. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) :
  307. mSize(size),
  308. mShape(shape),
  309. mPen(QPen(color)),
  310. mBrush(Qt::NoBrush),
  311. mPenDefined(true)
  312. {
  313. }
  314. /*!
  315. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
  316. the brush color to \a fill (with a solid pattern), and size to \a size.
  317. */
  318. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) :
  319. mSize(size),
  320. mShape(shape),
  321. mPen(QPen(color)),
  322. mBrush(QBrush(fill)),
  323. mPenDefined(true)
  324. {
  325. }
  326. /*!
  327. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the
  328. brush to \a brush, and size to \a size.
  329. \warning In some cases it might be tempting to directly use a pen style like <tt>Qt::NoPen</tt> as \a pen
  330. and a color like <tt>Qt::blue</tt> as \a brush. Notice however, that the corresponding call\n
  331. <tt>QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)</tt>\n
  332. doesn't necessarily lead C++ to use this constructor in some cases, but might mistake
  333. <tt>Qt::NoPen</tt> for a QColor and use the
  334. \ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size)
  335. constructor instead (which will lead to an unexpected look of the scatter points). To prevent
  336. this, be more explicit with the parameter types. For example, use <tt>QBrush(Qt::blue)</tt>
  337. instead of just <tt>Qt::blue</tt>, to clearly point out to the compiler that this constructor is
  338. wanted.
  339. */
  340. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) :
  341. mSize(size),
  342. mShape(shape),
  343. mPen(pen),
  344. mBrush(brush),
  345. mPenDefined(pen.style() != Qt::NoPen)
  346. {
  347. }
  348. /*!
  349. Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape
  350. is set to \ref ssPixmap.
  351. */
  352. QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) :
  353. mSize(5),
  354. mShape(ssPixmap),
  355. mPen(Qt::NoPen),
  356. mBrush(Qt::NoBrush),
  357. mPixmap(pixmap),
  358. mPenDefined(false)
  359. {
  360. }
  361. /*!
  362. Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The
  363. scatter shape is set to \ref ssCustom.
  364. The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly
  365. different meaning than for built-in scatter points: The custom path will be drawn scaled by a
  366. factor of \a size/6.0. Since the default \a size is 6, the custom path will appear at a its
  367. natural size by default. To double the size of the path for example, set \a size to 12.
  368. */
  369. QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) :
  370. mSize(size),
  371. mShape(ssCustom),
  372. mPen(pen),
  373. mBrush(brush),
  374. mCustomPath(customPath),
  375. mPenDefined(false)
  376. {
  377. }
  378. /*!
  379. Sets the size (pixel diameter) of the drawn scatter points to \a size.
  380. \see setShape
  381. */
  382. void QCPScatterStyle::setSize(double size)
  383. {
  384. mSize = size;
  385. }
  386. /*!
  387. Sets the shape to \a shape.
  388. Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref
  389. ssPixmap and \ref ssCustom, respectively.
  390. \see setSize
  391. */
  392. void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape)
  393. {
  394. mShape = shape;
  395. }
  396. /*!
  397. Sets the pen that will be used to draw scatter points to \a pen.
  398. If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after
  399. a call to this function, even if \a pen is <tt>Qt::NoPen</tt>.
  400. \see setBrush
  401. */
  402. void QCPScatterStyle::setPen(const QPen &pen)
  403. {
  404. mPenDefined = true;
  405. mPen = pen;
  406. }
  407. /*!
  408. Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter
  409. shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does.
  410. \see setPen
  411. */
  412. void QCPScatterStyle::setBrush(const QBrush &brush)
  413. {
  414. mBrush = brush;
  415. }
  416. /*!
  417. Sets the pixmap that will be drawn as scatter point to \a pixmap.
  418. Note that \ref setSize does not influence the appearance of the pixmap.
  419. The scatter shape is automatically set to \ref ssPixmap.
  420. */
  421. void QCPScatterStyle::setPixmap(const QPixmap &pixmap)
  422. {
  423. setShape(ssPixmap);
  424. mPixmap = pixmap;
  425. }
  426. /*!
  427. Sets the custom shape that will be drawn as scatter point to \a customPath.
  428. The scatter shape is automatically set to \ref ssCustom.
  429. */
  430. void QCPScatterStyle::setCustomPath(const QPainterPath &customPath)
  431. {
  432. setShape(ssCustom);
  433. mCustomPath = customPath;
  434. }
  435. /*!
  436. Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an
  437. undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead.
  438. This function is used by plottables (or any class that wants to draw scatters) just before a
  439. number of scatters with this style shall be drawn with the \a painter.
  440. \see drawShape
  441. */
  442. void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const
  443. {
  444. painter->setPen(mPenDefined ? mPen : defaultPen);
  445. painter->setBrush(mBrush);
  446. }
  447. /*!
  448. Draws the scatter shape with \a painter at position \a pos.
  449. This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be
  450. called before scatter points are drawn with \ref drawShape.
  451. \see applyTo
  452. */
  453. void QCPScatterStyle::drawShape(QCPPainter *painter, QPointF pos) const
  454. {
  455. drawShape(painter, pos.x(), pos.y());
  456. }
  457. /*! \overload
  458. Draws the scatter shape with \a painter at position \a x and \a y.
  459. */
  460. void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const
  461. {
  462. double w = mSize/2.0;
  463. switch (mShape)
  464. {
  465. case ssNone: break;
  466. case ssDot:
  467. {
  468. painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y));
  469. break;
  470. }
  471. case ssCross:
  472. {
  473. painter->drawLine(QLineF(x-w, y-w, x+w, y+w));
  474. painter->drawLine(QLineF(x-w, y+w, x+w, y-w));
  475. break;
  476. }
  477. case ssPlus:
  478. {
  479. painter->drawLine(QLineF(x-w, y, x+w, y));
  480. painter->drawLine(QLineF( x, y+w, x, y-w));
  481. break;
  482. }
  483. case ssCircle:
  484. {
  485. painter->drawEllipse(QPointF(x , y), w, w);
  486. break;
  487. }
  488. case ssDisc:
  489. {
  490. QBrush b = painter->brush();
  491. painter->setBrush(painter->pen().color());
  492. painter->drawEllipse(QPointF(x , y), w, w);
  493. painter->setBrush(b);
  494. break;
  495. }
  496. case ssSquare:
  497. {
  498. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  499. break;
  500. }
  501. case ssDiamond:
  502. {
  503. painter->drawLine(QLineF(x-w, y, x, y-w));
  504. painter->drawLine(QLineF( x, y-w, x+w, y));
  505. painter->drawLine(QLineF(x+w, y, x, y+w));
  506. painter->drawLine(QLineF( x, y+w, x-w, y));
  507. break;
  508. }
  509. case ssStar:
  510. {
  511. painter->drawLine(QLineF(x-w, y, x+w, y));
  512. painter->drawLine(QLineF( x, y+w, x, y-w));
  513. painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707));
  514. painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707));
  515. break;
  516. }
  517. case ssTriangle:
  518. {
  519. painter->drawLine(QLineF(x-w, y+0.755*w, x+w, y+0.755*w));
  520. painter->drawLine(QLineF(x+w, y+0.755*w, x, y-0.977*w));
  521. painter->drawLine(QLineF( x, y-0.977*w, x-w, y+0.755*w));
  522. break;
  523. }
  524. case ssTriangleInverted:
  525. {
  526. painter->drawLine(QLineF(x-w, y-0.755*w, x+w, y-0.755*w));
  527. painter->drawLine(QLineF(x+w, y-0.755*w, x, y+0.977*w));
  528. painter->drawLine(QLineF( x, y+0.977*w, x-w, y-0.755*w));
  529. break;
  530. }
  531. case ssCrossSquare:
  532. {
  533. painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95));
  534. painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w));
  535. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  536. break;
  537. }
  538. case ssPlusSquare:
  539. {
  540. painter->drawLine(QLineF(x-w, y, x+w*0.95, y));
  541. painter->drawLine(QLineF( x, y+w, x, y-w));
  542. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  543. break;
  544. }
  545. case ssCrossCircle:
  546. {
  547. painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670));
  548. painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707));
  549. painter->drawEllipse(QPointF(x, y), w, w);
  550. break;
  551. }
  552. case ssPlusCircle:
  553. {
  554. painter->drawLine(QLineF(x-w, y, x+w, y));
  555. painter->drawLine(QLineF( x, y+w, x, y-w));
  556. painter->drawEllipse(QPointF(x, y), w, w);
  557. break;
  558. }
  559. case ssPeace:
  560. {
  561. painter->drawLine(QLineF(x, y-w, x, y+w));
  562. painter->drawLine(QLineF(x, y, x-w*0.707, y+w*0.707));
  563. painter->drawLine(QLineF(x, y, x+w*0.707, y+w*0.707));
  564. painter->drawEllipse(QPointF(x, y), w, w);
  565. break;
  566. }
  567. case ssPixmap:
  568. {
  569. painter->drawPixmap(x-mPixmap.width()*0.5, y-mPixmap.height()*0.5, mPixmap);
  570. break;
  571. }
  572. case ssCustom:
  573. {
  574. QTransform oldTransform = painter->transform();
  575. painter->translate(x, y);
  576. painter->scale(mSize/6.0, mSize/6.0);
  577. painter->drawPath(mCustomPath);
  578. painter->setTransform(oldTransform);
  579. break;
  580. }
  581. }
  582. }
  583. ////////////////////////////////////////////////////////////////////////////////////////////////////
  584. //////////////////// QCPLayer
  585. ////////////////////////////////////////////////////////////////////////////////////////////////////
  586. /*! \class QCPLayer
  587. \brief A layer that may contain objects, to control the rendering order
  588. The Layering system of QCustomPlot is the mechanism to control the rendering order of the
  589. elements inside the plot.
  590. It is based on the two classes QCPLayer and QCPLayerable. QCustomPlot holds an ordered list of
  591. one or more instances of QCPLayer (see QCustomPlot::addLayer, QCustomPlot::layer,
  592. QCustomPlot::moveLayer, etc.). When replotting, QCustomPlot goes through the list of layers
  593. bottom to top and successively draws the layerables of the layers.
  594. A QCPLayer contains an ordered list of QCPLayerable instances. QCPLayerable is an abstract base
  595. class from which almost all visible objects derive, like axes, grids, graphs, items, etc.
  596. Initially, QCustomPlot has five layers: "background", "grid", "main", "axes" and "legend" (in
  597. that order). The top two layers "axes" and "legend" contain the default axes and legend, so they
  598. will be drawn on top. In the middle, there is the "main" layer. It is initially empty and set as
  599. the current layer (see QCustomPlot::setCurrentLayer). This means, all new plottables, items etc.
  600. are created on this layer by default. Then comes the "grid" layer which contains the QCPGrid
  601. instances (which belong tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background
  602. shall be drawn behind everything else, thus the default QCPAxisRect instance is placed on the
  603. "background" layer. Of course, the layer affiliation of the individual objects can be changed as
  604. required (\ref QCPLayerable::setLayer).
  605. Controlling the ordering of objects is easy: Create a new layer in the position you want it to
  606. be, e.g. above "main", with QCustomPlot::addLayer. Then set the current layer with
  607. QCustomPlot::setCurrentLayer to that new layer and finally create the objects normally. They will
  608. be placed on the new layer automatically, due to the current layer setting. Alternatively you
  609. could have also ignored the current layer setting and just moved the objects with
  610. QCPLayerable::setLayer to the desired layer after creating them.
  611. It is also possible to move whole layers. For example, If you want the grid to be shown in front
  612. of all plottables/items on the "main" layer, just move it above "main" with
  613. QCustomPlot::moveLayer.
  614. The rendering order within one layer is simply by order of creation or insertion. The item
  615. created last (or added last to the layer), is drawn on top of all other objects on that layer.
  616. When a layer is deleted, the objects on it are not deleted with it, but fall on the layer below
  617. the deleted layer, see QCustomPlot::removeLayer.
  618. */
  619. /* start documentation of inline functions */
  620. /*! \fn QList<QCPLayerable*> QCPLayer::children() const
  621. Returns a list of all layerables on this layer. The order corresponds to the rendering order:
  622. layerables with higher indices are drawn above layerables with lower indices.
  623. */
  624. /*! \fn int QCPLayer::index() const
  625. Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be
  626. accessed via \ref QCustomPlot::layer.
  627. Layers with higher indices will be drawn above layers with lower indices.
  628. */
  629. /* end documentation of inline functions */
  630. /*!
  631. Creates a new QCPLayer instance.
  632. Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead.
  633. \warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot.
  634. This check is only performed by \ref QCustomPlot::addLayer.
  635. */
  636. QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) :
  637. QObject(parentPlot),
  638. mParentPlot(parentPlot),
  639. mName(layerName),
  640. mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function
  641. mVisible(true)
  642. {
  643. // Note: no need to make sure layerName is unique, because layer
  644. // management is done with QCustomPlot functions.
  645. }
  646. QCPLayer::~QCPLayer()
  647. {
  648. // If child layerables are still on this layer, detach them, so they don't try to reach back to this
  649. // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted
  650. // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to
  651. // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.)
  652. while (!mChildren.isEmpty())
  653. mChildren.last()->setLayer(0); // removes itself from mChildren via removeChild()
  654. if (mParentPlot->currentLayer() == this)
  655. 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.";
  656. }
  657. /*!
  658. Sets whether this layer is visible or not. If \a visible is set to false, all layerables on this
  659. layer will be invisible.
  660. This function doesn't change the visibility property of the layerables (\ref
  661. QCPLayerable::setVisible), but the \ref QCPLayerable::realVisibility of each layerable takes the
  662. visibility of the parent layer into account.
  663. */
  664. void QCPLayer::setVisible(bool visible)
  665. {
  666. mVisible = visible;
  667. }
  668. /*! \internal
  669. Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will
  670. be prepended to the list, i.e. be drawn beneath the other layerables already in the list.
  671. This function does not change the \a mLayer member of \a layerable to this layer. (Use
  672. QCPLayerable::setLayer to change the layer of an object, not this function.)
  673. \see removeChild
  674. */
  675. void QCPLayer::addChild(QCPLayerable *layerable, bool prepend)
  676. {
  677. if (!mChildren.contains(layerable))
  678. {
  679. if (prepend)
  680. mChildren.prepend(layerable);
  681. else
  682. mChildren.append(layerable);
  683. } else
  684. qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast<quintptr>(layerable);
  685. }
  686. /*! \internal
  687. Removes the \a layerable from the list of this layer.
  688. This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer
  689. to change the layer of an object, not this function.)
  690. \see addChild
  691. */
  692. void QCPLayer::removeChild(QCPLayerable *layerable)
  693. {
  694. if (!mChildren.removeOne(layerable))
  695. qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast<quintptr>(layerable);
  696. }
  697. ////////////////////////////////////////////////////////////////////////////////////////////////////
  698. //////////////////// QCPLayerable
  699. ////////////////////////////////////////////////////////////////////////////////////////////////////
  700. /*! \class QCPLayerable
  701. \brief Base class for all drawable objects
  702. This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid
  703. etc.
  704. Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking
  705. the layers accordingly.
  706. For details about the layering mechanism, see the QCPLayer documentation.
  707. */
  708. /* start documentation of inline functions */
  709. /*! \fn QCPLayerable *QCPLayerable::parentLayerable() const
  710. Returns the parent layerable of this layerable. The parent layerable is used to provide
  711. visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables
  712. only get drawn if their parent layerables are visible, too.
  713. Note that a parent layerable is not necessarily also the QObject parent for memory management.
  714. Further, a layerable doesn't always have a parent layerable, so this function may return 0.
  715. A parent layerable is set implicitly with when placed inside layout elements and doesn't need to be
  716. set manually by the user.
  717. */
  718. /* end documentation of inline functions */
  719. /* start documentation of pure virtual functions */
  720. /*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0
  721. \internal
  722. This function applies the default antialiasing setting to the specified \a painter, using the
  723. function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when
  724. \ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing
  725. setting may be specified individually, this function should set the antialiasing state of the
  726. most prominent entity. In this case however, the \ref draw function usually calls the specialized
  727. versions of this function before drawing each entity, effectively overriding the setting of the
  728. default antialiasing hint.
  729. <b>First example:</b> QCPGraph has multiple entities that have an antialiasing setting: The graph
  730. line, fills, scatters and error bars. Those can be configured via QCPGraph::setAntialiased,
  731. QCPGraph::setAntialiasedFill, QCPGraph::setAntialiasedScatters etc. Consequently, there isn't
  732. only the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's
  733. antialiasing), but specialized ones like QCPGraph::applyFillAntialiasingHint and
  734. QCPGraph::applyScattersAntialiasingHint. So before drawing one of those entities, QCPGraph::draw
  735. calls the respective specialized applyAntialiasingHint function.
  736. <b>Second example:</b> QCPItemLine consists only of a line so there is only one antialiasing
  737. setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by
  738. all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the
  739. respective layerable subclass.) Consequently it only has the normal
  740. QCPItemLine::applyDefaultAntialiasingHint. The \ref QCPItemLine::draw function doesn't need to
  741. care about setting any antialiasing states, because the default antialiasing hint is already set
  742. on the painter when the \ref draw function is called, and that's the state it wants to draw the
  743. line with.
  744. */
  745. /*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0
  746. \internal
  747. This function draws the layerable with the specified \a painter. It is only called by
  748. QCustomPlot, if the layerable is visible (\ref setVisible).
  749. Before this function is called, the painter's antialiasing state is set via \ref
  750. applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was
  751. set to \ref clipRect.
  752. */
  753. /* end documentation of pure virtual functions */
  754. /* start documentation of signals */
  755. /*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer);
  756. This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to
  757. a different layer.
  758. \see setLayer
  759. */
  760. /* end documentation of signals */
  761. /*!
  762. Creates a new QCPLayerable instance.
  763. Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the
  764. derived classes.
  765. If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a
  766. targetLayer is an empty string, it places itself on the current layer of the plot (see \ref
  767. QCustomPlot::setCurrentLayer).
  768. It is possible to provide 0 as \a plot. In that case, you should assign a parent plot at a later
  769. time with \ref initializeParentPlot.
  770. The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable parents
  771. are mainly used to control visibility in a hierarchy of layerables. This means a layerable is
  772. only drawn, if all its ancestor layerables are also visible. Note that \a parentLayerable does
  773. not become the QObject-parent (for memory management) of this layerable, \a plot does.
  774. */
  775. QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) :
  776. QObject(plot),
  777. mVisible(true),
  778. mParentPlot(plot),
  779. mParentLayerable(parentLayerable),
  780. mLayer(0),
  781. mAntialiased(true)
  782. {
  783. if (mParentPlot)
  784. {
  785. if (targetLayer.isEmpty())
  786. setLayer(mParentPlot->currentLayer());
  787. else if (!setLayer(targetLayer))
  788. qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed.";
  789. }
  790. }
  791. QCPLayerable::~QCPLayerable()
  792. {
  793. if (mLayer)
  794. {
  795. mLayer->removeChild(this);
  796. mLayer = 0;
  797. }
  798. }
  799. /*!
  800. Sets the visibility of this layerable object. If an object is not visible, it will not be drawn
  801. on the QCustomPlot surface, and user interaction with it (e.g. click and selection) is not
  802. possible.
  803. */
  804. void QCPLayerable::setVisible(bool on)
  805. {
  806. mVisible = on;
  807. }
  808. /*!
  809. Sets the \a layer of this layerable object. The object will be placed on top of the other objects
  810. already on \a layer.
  811. Returns true on success, i.e. if \a layer is a valid layer.
  812. */
  813. bool QCPLayerable::setLayer(QCPLayer *layer)
  814. {
  815. return moveToLayer(layer, false);
  816. }
  817. /*! \overload
  818. Sets the layer of this layerable object by name
  819. Returns true on success, i.e. if \a layerName is a valid layer name.
  820. */
  821. bool QCPLayerable::setLayer(const QString &layerName)
  822. {
  823. if (!mParentPlot)
  824. {
  825. qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
  826. return false;
  827. }
  828. if (QCPLayer *layer = mParentPlot->layer(layerName))
  829. {
  830. return setLayer(layer);
  831. } else
  832. {
  833. qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName;
  834. return false;
  835. }
  836. }
  837. /*!
  838. Sets whether this object will be drawn antialiased or not.
  839. Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and
  840. QCustomPlot::setNotAntialiasedElements.
  841. */
  842. void QCPLayerable::setAntialiased(bool enabled)
  843. {
  844. mAntialiased = enabled;
  845. }
  846. /*!
  847. Returns whether this layerable is visible, taking the visibility of the layerable parent and the
  848. visibility of the layer this layerable is on into account. This is the method that is consulted
  849. to decide whether a layerable shall be drawn or not.
  850. If this layerable has a direct layerable parent (usually set via hierarchies implemented in
  851. subclasses, like in the case of QCPLayoutElement), this function returns true only if this
  852. layerable has its visibility set to true and the parent layerable's \ref realVisibility returns
  853. true.
  854. If this layerable doesn't have a direct layerable parent, returns the state of this layerable's
  855. visibility.
  856. */
  857. bool QCPLayerable::realVisibility() const
  858. {
  859. return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility());
  860. }
  861. /*!
  862. This function is used to decide whether a click hits a layerable object or not.
  863. \a pos is a point in pixel coordinates on the QCustomPlot surface. This function returns the
  864. shortest pixel distance of this point to the object. If the object is either invisible or the
  865. distance couldn't be determined, -1.0 is returned. Further, if \a onlySelectable is true and the
  866. object is not selectable, -1.0 is returned, too.
  867. If the item is represented not by single lines but by an area like QCPItemRect or QCPItemText, a
  868. click inside the area returns a constant value greater zero (typically the selectionTolerance of
  869. the parent QCustomPlot multiplied by 0.99). If the click lies outside the area, this function
  870. returns -1.0.
  871. Providing a constant value for area objects allows selecting line objects even when they are
  872. obscured by such area objects, by clicking close to the lines (i.e. closer than
  873. 0.99*selectionTolerance).
  874. The actual setting of the selection state is not done by this function. This is handled by the
  875. parent QCustomPlot when the mouseReleaseEvent occurs, and the finally selected object is notified
  876. via the selectEvent/deselectEvent methods.
  877. \a details is an optional output parameter. Every layerable subclass may place any information
  878. in \a details. This information will be passed to \ref selectEvent when the parent QCustomPlot
  879. decides on the basis of this selectTest call, that the object was successfully selected. The
  880. subsequent call to \ref selectEvent will carry the \a details. This is useful for multi-part
  881. objects (like QCPAxis). This way, a possibly complex calculation to decide which part was clicked
  882. is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be
  883. placed in \a details. So in the subsequent \ref selectEvent, the decision which part was
  884. selected doesn't have to be done a second time for a single selection operation.
  885. You may pass 0 as \a details to indicate that you are not interested in those selection details.
  886. \see selectEvent, deselectEvent, QCustomPlot::setInteractions
  887. */
  888. double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  889. {
  890. Q_UNUSED(pos)
  891. Q_UNUSED(onlySelectable)
  892. Q_UNUSED(details)
  893. return -1.0;
  894. }
  895. /*! \internal
  896. Sets the parent plot of this layerable. Use this function once to set the parent plot if you have
  897. passed 0 in the constructor. It can not be used to move a layerable from one QCustomPlot to
  898. another one.
  899. Note that, unlike when passing a non-null parent plot in the constructor, this function does not
  900. make \a parentPlot the QObject-parent of this layerable. If you want this, call
  901. QObject::setParent(\a parentPlot) in addition to this function.
  902. Further, you will probably want to set a layer (\ref setLayer) after calling this function, to
  903. make the layerable appear on the QCustomPlot.
  904. The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized
  905. so they can react accordingly (e.g. also initialize the parent plot of child layerables, like
  906. QCPLayout does).
  907. */
  908. void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot)
  909. {
  910. if (mParentPlot)
  911. {
  912. qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized";
  913. return;
  914. }
  915. if (!parentPlot)
  916. qDebug() << Q_FUNC_INFO << "called with parentPlot zero";
  917. mParentPlot = parentPlot;
  918. parentPlotInitialized(mParentPlot);
  919. }
  920. /*! \internal
  921. Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not
  922. become the QObject-parent (for memory management) of this layerable.
  923. The parent layerable has influence on the return value of the \ref realVisibility method. Only
  924. layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be
  925. drawn.
  926. \see realVisibility
  927. */
  928. void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable)
  929. {
  930. mParentLayerable = parentLayerable;
  931. }
  932. /*! \internal
  933. Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to
  934. the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is
  935. false, the object will be appended.
  936. Returns true on success, i.e. if \a layer is a valid layer.
  937. */
  938. bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend)
  939. {
  940. if (layer && !mParentPlot)
  941. {
  942. qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
  943. return false;
  944. }
  945. if (layer && layer->parentPlot() != mParentPlot)
  946. {
  947. qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable";
  948. return false;
  949. }
  950. QCPLayer *oldLayer = mLayer;
  951. if (mLayer)
  952. mLayer->removeChild(this);
  953. mLayer = layer;
  954. if (mLayer)
  955. mLayer->addChild(this, prepend);
  956. if (mLayer != oldLayer)
  957. emit layerChanged(mLayer);
  958. return true;
  959. }
  960. /*! \internal
  961. Sets the QCPainter::setAntialiasing state on the provided \a painter, depending on the \a
  962. localAntialiased value as well as the overrides \ref QCustomPlot::setAntialiasedElements and \ref
  963. QCustomPlot::setNotAntialiasedElements. Which override enum this function takes into account is
  964. controlled via \a overrideElement.
  965. */
  966. void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const
  967. {
  968. if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement))
  969. painter->setAntialiasing(false);
  970. else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement))
  971. painter->setAntialiasing(true);
  972. else
  973. painter->setAntialiasing(localAntialiased);
  974. }
  975. /*! \internal
  976. This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting
  977. of a parent plot. This is the case when 0 was passed as parent plot in the constructor, and the
  978. parent plot is set at a later time.
  979. For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any
  980. QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level
  981. element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To
  982. propagate the parent plot to all the children of the hierarchy, the top level element then uses
  983. this function to pass the parent plot on to its child elements.
  984. The default implementation does nothing.
  985. \see initializeParentPlot
  986. */
  987. void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot)
  988. {
  989. Q_UNUSED(parentPlot)
  990. }
  991. /*! \internal
  992. Returns the selection category this layerable shall belong to. The selection category is used in
  993. conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and
  994. which aren't.
  995. Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref
  996. QCP::iSelectOther. This is what the default implementation returns.
  997. \see QCustomPlot::setInteractions
  998. */
  999. QCP::Interaction QCPLayerable::selectionCategory() const
  1000. {
  1001. return QCP::iSelectOther;
  1002. }
  1003. /*! \internal
  1004. Returns the clipping rectangle of this layerable object. By default, this is the viewport of the
  1005. parent QCustomPlot. Specific subclasses may reimplement this function to provide different
  1006. clipping rects.
  1007. The returned clipping rect is set on the painter before the draw function of the respective
  1008. object is called.
  1009. */
  1010. QRect QCPLayerable::clipRect() const
  1011. {
  1012. if (mParentPlot)
  1013. return mParentPlot->viewport();
  1014. else
  1015. return QRect();
  1016. }
  1017. /*! \internal
  1018. This event is called when the layerable shall be selected, as a consequence of a click by the
  1019. user. Subclasses should react to it by setting their selection state appropriately. The default
  1020. implementation does nothing.
  1021. \a event is the mouse event that caused the selection. \a additive indicates, whether the user
  1022. was holding the multi-select-modifier while performing the selection (see \ref
  1023. QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled
  1024. (i.e. become selected when unselected and unselected when selected).
  1025. Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e.
  1026. returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot).
  1027. The \a details data you output from \ref selectTest is fed back via \a details here. You may
  1028. use it to transport any kind of information from the selectTest to the possibly subsequent
  1029. selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable
  1030. that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need
  1031. to do the calculation again to find out which part was actually clicked.
  1032. \a selectionStateChanged is an output parameter. If the pointer is non-null, this function must
  1033. set the value either to true or false, depending on whether the selection state of this layerable
  1034. was actually changed. For layerables that only are selectable as a whole and not in parts, this
  1035. is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the
  1036. selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the
  1037. layerable was previously unselected and now is switched to the selected state.
  1038. \see selectTest, deselectEvent
  1039. */
  1040. void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  1041. {
  1042. Q_UNUSED(event)
  1043. Q_UNUSED(additive)
  1044. Q_UNUSED(details)
  1045. Q_UNUSED(selectionStateChanged)
  1046. }
  1047. /*! \internal
  1048. This event is called when the layerable shall be deselected, either as consequence of a user
  1049. interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by
  1050. unsetting their selection appropriately.
  1051. just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must
  1052. return true or false when the selection state of this layerable has changed or not changed,
  1053. respectively.
  1054. \see selectTest, selectEvent
  1055. */
  1056. void QCPLayerable::deselectEvent(bool *selectionStateChanged)
  1057. {
  1058. Q_UNUSED(selectionStateChanged)
  1059. }
  1060. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1061. //////////////////// QCPRange
  1062. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1063. /*! \class QCPRange
  1064. \brief Represents the range an axis is encompassing.
  1065. contains a \a lower and \a upper double value and provides convenience input, output and
  1066. modification functions.
  1067. \see QCPAxis::setRange
  1068. */
  1069. /*!
  1070. Minimum range size (\a upper - \a lower) the range changing functions will accept. Smaller
  1071. intervals would cause errors due to the 11-bit exponent of double precision numbers,
  1072. corresponding to a minimum magnitude of roughly 1e-308.
  1073. \see validRange, maxRange
  1074. */
  1075. const double QCPRange::minRange = 1e-280;
  1076. /*!
  1077. Maximum values (negative and positive) the range will accept in range-changing functions.
  1078. Larger absolute values would cause errors due to the 11-bit exponent of double precision numbers,
  1079. corresponding to a maximum magnitude of roughly 1e308.
  1080. Since the number of planck-volumes in the entire visible universe is only ~1e183, this should
  1081. be enough.
  1082. \see validRange, minRange
  1083. */
  1084. const double QCPRange::maxRange = 1e250;
  1085. /*!
  1086. Constructs a range with \a lower and \a upper set to zero.
  1087. */
  1088. QCPRange::QCPRange() :
  1089. lower(0),
  1090. upper(0)
  1091. {
  1092. }
  1093. /*! \overload
  1094. Constructs a range with the specified \a lower and \a upper values.
  1095. */
  1096. QCPRange::QCPRange(double lower, double upper) :
  1097. lower(lower),
  1098. upper(upper)
  1099. {
  1100. normalize();
  1101. }
  1102. /*!
  1103. Returns the size of the range, i.e. \a upper-\a lower
  1104. */
  1105. double QCPRange::size() const
  1106. {
  1107. return upper-lower;
  1108. }
  1109. /*!
  1110. Returns the center of the range, i.e. (\a upper+\a lower)*0.5
  1111. */
  1112. double QCPRange::center() const
  1113. {
  1114. return (upper+lower)*0.5;
  1115. }
  1116. /*!
  1117. Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values
  1118. are swapped.
  1119. */
  1120. void QCPRange::normalize()
  1121. {
  1122. if (lower > upper)
  1123. qSwap(lower, upper);
  1124. }
  1125. /*!
  1126. Expands this range such that \a otherRange is contained in the new range. It is assumed that both
  1127. this range and \a otherRange are normalized (see \ref normalize).
  1128. If \a otherRange is already inside the current range, this function does nothing.
  1129. \see expanded
  1130. */
  1131. void QCPRange::expand(const QCPRange &otherRange)
  1132. {
  1133. if (lower > otherRange.lower)
  1134. lower = otherRange.lower;
  1135. if (upper < otherRange.upper)
  1136. upper = otherRange.upper;
  1137. }
  1138. /*!
  1139. Returns an expanded range that contains this and \a otherRange. It is assumed that both this
  1140. range and \a otherRange are normalized (see \ref normalize).
  1141. \see expand
  1142. */
  1143. QCPRange QCPRange::expanded(const QCPRange &otherRange) const
  1144. {
  1145. QCPRange result = *this;
  1146. result.expand(otherRange);
  1147. return result;
  1148. }
  1149. /*!
  1150. Returns a sanitized version of the range. Sanitized means for logarithmic scales, that
  1151. the range won't span the positive and negative sign domain, i.e. contain zero. Further
  1152. \a lower will always be numerically smaller (or equal) to \a upper.
  1153. If the original range does span positive and negative sign domains or contains zero,
  1154. the returned range will try to approximate the original range as good as possible.
  1155. If the positive interval of the original range is wider than the negative interval, the
  1156. returned range will only contain the positive interval, with lower bound set to \a rangeFac or
  1157. \a rangeFac *\a upper, whichever is closer to zero. Same procedure is used if the negative interval
  1158. is wider than the positive interval, this time by changing the \a upper bound.
  1159. */
  1160. QCPRange QCPRange::sanitizedForLogScale() const
  1161. {
  1162. double rangeFac = 1e-3;
  1163. QCPRange sanitizedRange(lower, upper);
  1164. sanitizedRange.normalize();
  1165. // can't have range spanning negative and positive values in log plot, so change range to fix it
  1166. //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1))
  1167. if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0)
  1168. {
  1169. // case lower is 0
  1170. if (rangeFac < sanitizedRange.upper*rangeFac)
  1171. sanitizedRange.lower = rangeFac;
  1172. else
  1173. sanitizedRange.lower = sanitizedRange.upper*rangeFac;
  1174. } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1))
  1175. else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0)
  1176. {
  1177. // case upper is 0
  1178. if (-rangeFac > sanitizedRange.lower*rangeFac)
  1179. sanitizedRange.upper = -rangeFac;
  1180. else
  1181. sanitizedRange.upper = sanitizedRange.lower*rangeFac;
  1182. } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0)
  1183. {
  1184. // find out whether negative or positive interval is wider to decide which sign domain will be chosen
  1185. if (-sanitizedRange.lower > sanitizedRange.upper)
  1186. {
  1187. // negative is wider, do same as in case upper is 0
  1188. if (-rangeFac > sanitizedRange.lower*rangeFac)
  1189. sanitizedRange.upper = -rangeFac;
  1190. else
  1191. sanitizedRange.upper = sanitizedRange.lower*rangeFac;
  1192. } else
  1193. {
  1194. // positive is wider, do same as in case lower is 0
  1195. if (rangeFac < sanitizedRange.upper*rangeFac)
  1196. sanitizedRange.lower = rangeFac;
  1197. else
  1198. sanitizedRange.lower = sanitizedRange.upper*rangeFac;
  1199. }
  1200. }
  1201. // due to normalization, case lower>0 && upper<0 should never occur, because that implies upper<lower
  1202. return sanitizedRange;
  1203. }
  1204. /*!
  1205. Returns a sanitized version of the range. Sanitized means for linear scales, that
  1206. \a lower will always be numerically smaller (or equal) to \a upper.
  1207. */
  1208. QCPRange QCPRange::sanitizedForLinScale() const
  1209. {
  1210. QCPRange sanitizedRange(lower, upper);
  1211. sanitizedRange.normalize();
  1212. return sanitizedRange;
  1213. }
  1214. /*!
  1215. Returns true when \a value lies within or exactly on the borders of the range.
  1216. */
  1217. bool QCPRange::contains(double value) const
  1218. {
  1219. return value >= lower && value <= upper;
  1220. }
  1221. /*!
  1222. Checks, whether the specified range is within valid bounds, which are defined
  1223. as QCPRange::maxRange and QCPRange::minRange.
  1224. A valid range means:
  1225. \li range bounds within -maxRange and maxRange
  1226. \li range size above minRange
  1227. \li range size below maxRange
  1228. */
  1229. bool QCPRange::validRange(double lower, double upper)
  1230. {
  1231. /*
  1232. return (lower > -maxRange &&
  1233. upper < maxRange &&
  1234. qAbs(lower-upper) > minRange &&
  1235. (lower < -minRange || lower > minRange) &&
  1236. (upper < -minRange || upper > minRange));
  1237. */
  1238. return (lower > -maxRange &&
  1239. upper < maxRange &&
  1240. qAbs(lower-upper) > minRange &&
  1241. qAbs(lower-upper) < maxRange);
  1242. }
  1243. /*!
  1244. \overload
  1245. Checks, whether the specified range is within valid bounds, which are defined
  1246. as QCPRange::maxRange and QCPRange::minRange.
  1247. A valid range means:
  1248. \li range bounds within -maxRange and maxRange
  1249. \li range size above minRange
  1250. \li range size below maxRange
  1251. */
  1252. bool QCPRange::validRange(const QCPRange &range)
  1253. {
  1254. /*
  1255. return (range.lower > -maxRange &&
  1256. range.upper < maxRange &&
  1257. qAbs(range.lower-range.upper) > minRange &&
  1258. qAbs(range.lower-range.upper) < maxRange &&
  1259. (range.lower < -minRange || range.lower > minRange) &&
  1260. (range.upper < -minRange || range.upper > minRange));
  1261. */
  1262. return (range.lower > -maxRange &&
  1263. range.upper < maxRange &&
  1264. qAbs(range.lower-range.upper) > minRange &&
  1265. qAbs(range.lower-range.upper) < maxRange);
  1266. }
  1267. /*! \page thelayoutsystem The Layout System
  1268. The layout system is responsible for positioning and scaling layout elements such as axis rects,
  1269. legends and plot titles in a QCustomPlot.
  1270. \section layoutsystem-classesandmechanisms Classes and mechanisms
  1271. The layout system is based on the abstract base class \ref QCPLayoutElement. All objects that
  1272. take part in the layout system derive from this class, either directly or indirectly.
  1273. Since QCPLayoutElement itself derives from \ref QCPLayerable, a layout element may draw its own
  1274. content. However, it is perfectly possible for a layout element to only serve as a structuring
  1275. and/or positioning element, not drawing anything on its own.
  1276. \subsection layoutsystem-rects Rects of a layout element
  1277. A layout element is a rectangular object described by two rects: the inner rect (\ref
  1278. QCPLayoutElement::rect) and the outer rect (\ref QCPLayoutElement::setOuterRect). The inner rect
  1279. is calculated automatically by applying the margin (\ref QCPLayoutElement::setMargins) inward
  1280. from the outer rect. The inner rect is meant for main content while the margin area may either be
  1281. left blank or serve for displaying peripheral graphics. For example, \ref QCPAxisRect positions
  1282. the four main axes at the sides of the inner rect, so graphs end up inside it and the axis labels
  1283. and tick labels are in the margin area.
  1284. \subsection layoutsystem-margins Margins
  1285. Each layout element may provide a mechanism to automatically determine its margins. Internally,
  1286. this is realized with the \ref QCPLayoutElement::calculateAutoMargin function which takes a \ref
  1287. QCP::MarginSide and returns an integer value which represents the ideal margin for the specified
  1288. side. The automatic margin will be used on the sides specified in \ref
  1289. QCPLayoutElement::setAutoMargins. By default, it is set to \ref QCP::msAll meaning automatic
  1290. margin calculation is enabled for all four sides. In this case, a minimum margin may be set with
  1291. \ref QCPLayoutElement::setMinimumMargins, to prevent the automatic margin mechanism from setting
  1292. margins smaller than desired for a specific situation. If automatic margin calculation is unset
  1293. for a specific side, the margin of that side can be controlled directy via \ref
  1294. QCPLayoutElement::setMargins.
  1295. If multiple layout ements are arranged next to or beneath each other, it may be desirable to
  1296. align their inner rects on certain sides. Since they all might have different automatic margins,
  1297. this usually isn't the case. The class \ref QCPMarginGroup and \ref
  1298. QCPLayoutElement::setMarginGroup fix this by allowing to synchronize multiple margins. See the
  1299. documentation there for details.
  1300. \subsection layoutsystem-layout Layouts
  1301. As mentioned, a QCPLayoutElement may have an arbitrary number of child layout elements and in
  1302. princple can have the only purpose to manage/arrange those child elements. This is what the
  1303. subclass \ref QCPLayout specializes on. It is a QCPLayoutElement itself but has no visual
  1304. representation. It defines an interface to add, remove and manage child layout elements.
  1305. QCPLayout isn't a usable layout though, it's an abstract base class that concrete layouts derive
  1306. from, like \ref QCPLayoutGrid which arranges its child elements in a grid and \ref QCPLayoutInset
  1307. which allows placing child elements freely inside its rect.
  1308. Since a QCPLayout is a layout element itself, it may be placed inside other layouts. This way,
  1309. complex hierarchies may be created, offering very flexible arrangements.
  1310. \image html LayoutsystemSketch.png
  1311. Above is a sketch of the default \ref QCPLayoutGrid accessible via \ref QCustomPlot::plotLayout.
  1312. It shows how two child layout elements are placed inside the grid layout next to each other in
  1313. cells (0, 0) and (0, 1).
  1314. \subsection layoutsystem-plotlayout The top level plot layout
  1315. Every QCustomPlot has one top level layout of type \ref QCPLayoutGrid. It is accessible via \ref
  1316. QCustomPlot::plotLayout and contains (directly or indirectly via other sub-layouts) all layout
  1317. elements in the QCustomPlot. By default, this top level grid layout contains a single cell which
  1318. holds the main axis rect.
  1319. \subsection layoutsystem-examples Examples
  1320. <b>Adding a plot title</b> is a typical and simple case to demonstrate basic workings of the layout system.
  1321. \code
  1322. // first we create and prepare a plot title layout element:
  1323. QCPPlotTitle *title = new QCPPlotTitle(customPlot);
  1324. title->setText("Plot Title Example");
  1325. title->setFont(QFont("sans", 12, QFont::Bold));
  1326. // then we add it to the main plot layout:
  1327. customPlot->plotLayout()->insertRow(0); // insert an empty row above the axis rect
  1328. customPlot->plotLayout()->addElement(0, 0, title); // place the title in the empty cell we've just created
  1329. \endcode
  1330. \image html layoutsystem-addingplottitle.png
  1331. <b>Arranging multiple axis rects</b> actually is the central purpose of the layout system.
  1332. \code
  1333. customPlot->plotLayout()->clear(); // let's start from scratch and remove the default axis rect
  1334. // add the first axis rect in second row (row index 1):
  1335. QCPAxisRect *topAxisRect = new QCPAxisRect(customPlot);
  1336. customPlot->plotLayout()->addElement(1, 0, topAxisRect);
  1337. // create a sub layout that we'll place in first row:
  1338. QCPLayoutGrid *subLayout = new QCPLayoutGrid;
  1339. customPlot->plotLayout()->addElement(0, 0, subLayout);
  1340. // add two axis rects in the sub layout next to each other:
  1341. QCPAxisRect *leftAxisRect = new QCPAxisRect(customPlot);
  1342. QCPAxisRect *rightAxisRect = new QCPAxisRect(customPlot);
  1343. subLayout->addElement(0, 0, leftAxisRect);
  1344. subLayout->addElement(0, 1, rightAxisRect);
  1345. subLayout->setColumnStretchFactor(0, 3); // left axis rect shall have 60% of width
  1346. subLayout->setColumnStretchFactor(1, 2); // right one only 40% (3:2 = 60:40)
  1347. // since we've created the axis rects and axes from scratch, we need to place them on
  1348. // according layers, if we don't want the grid to be drawn above the axes etc.
  1349. // place the axis on "axes" layer and grids on the "grid" layer, which is below "axes":
  1350. QList<QCPAxis*> allAxes;
  1351. allAxes << topAxisRect->axes() << leftAxisRect->axes() << rightAxisRect->axes();
  1352. foreach (QCPAxis *axis, allAxes)
  1353. {
  1354. axis->setLayer("axes");
  1355. axis->grid()->setLayer("grid");
  1356. }
  1357. \endcode
  1358. \image html layoutsystem-multipleaxisrects.png
  1359. */
  1360. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1361. //////////////////// QCPMarginGroup
  1362. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1363. /*! \class QCPMarginGroup
  1364. \brief A margin group allows synchronization of margin sides if working with multiple layout elements.
  1365. QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that
  1366. they will all have the same size, based on the largest required margin in the group.
  1367. \n
  1368. \image html QCPMarginGroup.png "Demonstration of QCPMarginGroup"
  1369. \n
  1370. In certain situations it is desirable that margins at specific sides are synchronized across
  1371. layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will
  1372. provide a cleaner look to the user if the left and right margins of the two axis rects are of the
  1373. same size. The left axis of the top axis rect will then be at the same horizontal position as the
  1374. left axis of the lower axis rect, making them appear aligned. The same applies for the right
  1375. axes. This is what QCPMarginGroup makes possible.
  1376. To add/remove a specific side of a layout element to/from a margin group, use the \ref
  1377. QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call
  1378. \ref clear, or just delete the margin group.
  1379. \section QCPMarginGroup-example Example
  1380. First create a margin group:
  1381. \code
  1382. QCPMarginGroup *group = new QCPMarginGroup(customPlot);
  1383. \endcode
  1384. Then set this group on the layout element sides:
  1385. \code
  1386. customPlot->axisRect(0)->setMarginGroup(QCP::msLeft|QCP::msRight, group);
  1387. customPlot->axisRect(1)->setMarginGroup(QCP::msLeft|QCP::msRight, group);
  1388. \endcode
  1389. Here, we've used the first two axis rects of the plot and synchronized their left margins with
  1390. each other and their right margins with each other.
  1391. */
  1392. /* start documentation of inline functions */
  1393. /*! \fn QList<QCPLayoutElement*> QCPMarginGroup::elements(QCP::MarginSide side) const
  1394. Returns a list of all layout elements that have their margin \a side associated with this margin
  1395. group.
  1396. */
  1397. /* end documentation of inline functions */
  1398. /*!
  1399. Creates a new QCPMarginGroup instance in \a parentPlot.
  1400. */
  1401. QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) :
  1402. QObject(parentPlot),
  1403. mParentPlot(parentPlot)
  1404. {
  1405. mChildren.insert(QCP::msLeft, QList<QCPLayoutElement*>());
  1406. mChildren.insert(QCP::msRight, QList<QCPLayoutElement*>());
  1407. mChildren.insert(QCP::msTop, QList<QCPLayoutElement*>());
  1408. mChildren.insert(QCP::msBottom, QList<QCPLayoutElement*>());
  1409. }
  1410. QCPMarginGroup::~QCPMarginGroup()
  1411. {
  1412. clear();
  1413. }
  1414. /*!
  1415. Returns whether this margin group is empty. If this function returns true, no layout elements use
  1416. this margin group to synchronize margin sides.
  1417. */
  1418. bool QCPMarginGroup::isEmpty() const
  1419. {
  1420. QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
  1421. while (it.hasNext())
  1422. {
  1423. it.next();
  1424. if (!it.value().isEmpty())
  1425. return false;
  1426. }
  1427. return true;
  1428. }
  1429. /*!
  1430. Clears this margin group. The synchronization of the margin sides that use this margin group is
  1431. lifted and they will use their individual margin sizes again.
  1432. */
  1433. void QCPMarginGroup::clear()
  1434. {
  1435. // make all children remove themselves from this margin group:
  1436. QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
  1437. while (it.hasNext())
  1438. {
  1439. it.next();
  1440. const QList<QCPLayoutElement*> elements = it.value();
  1441. for (int i=elements.size()-1; i>=0; --i)
  1442. elements.at(i)->setMarginGroup(it.key(), 0); // removes itself from mChildren via removeChild
  1443. }
  1444. }
  1445. /*! \internal
  1446. Returns the synchronized common margin for \a side. This is the margin value that will be used by
  1447. the layout element on the respective side, if it is part of this margin group.
  1448. The common margin is calculated by requesting the automatic margin (\ref
  1449. QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin
  1450. group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into
  1451. account, too.)
  1452. */
  1453. int QCPMarginGroup::commonMargin(QCP::MarginSide side) const
  1454. {
  1455. // query all automatic margins of the layout elements in this margin group side and find maximum:
  1456. int result = 0;
  1457. const QList<QCPLayoutElement*> elements = mChildren.value(side);
  1458. for (int i=0; i<elements.size(); ++i)
  1459. {
  1460. if (!elements.at(i)->autoMargins().testFlag(side))
  1461. continue;
  1462. int m = qMax(elements.at(i)->calculateAutoMargin(side), QCP::getMarginValue(elements.at(i)->minimumMargins(), side));
  1463. if (m > result)
  1464. result = m;
  1465. }
  1466. return result;
  1467. }
  1468. /*! \internal
  1469. Adds \a element to the internal list of child elements, for the margin \a side.
  1470. This function does not modify the margin group property of \a element.
  1471. */
  1472. void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element)
  1473. {
  1474. if (!mChildren[side].contains(element))
  1475. mChildren[side].append(element);
  1476. else
  1477. qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast<quintptr>(element);
  1478. }
  1479. /*! \internal
  1480. Removes \a element from the internal list of child elements, for the margin \a side.
  1481. This function does not modify the margin group property of \a element.
  1482. */
  1483. void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element)
  1484. {
  1485. if (!mChildren[side].removeOne(element))
  1486. qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast<quintptr>(element);
  1487. }
  1488. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1489. //////////////////// QCPLayoutElement
  1490. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1491. /*! \class QCPLayoutElement
  1492. \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system".
  1493. This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses.
  1494. A Layout element is a rectangular object which can be placed in layouts. It has an outer rect
  1495. (QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference
  1496. between outer and inner rect is called its margin. The margin can either be set to automatic or
  1497. manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be
  1498. set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic,
  1499. the layout element subclass will control the value itself (via \ref calculateAutoMargin).
  1500. Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level
  1501. layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref
  1502. QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested.
  1503. Thus in QCustomPlot one can divide layout elements into two categories: The ones that are
  1504. invisible by themselves, because they don't draw anything. Their only purpose is to manage the
  1505. position and size of other layout elements. This category of layout elements usually use
  1506. QCPLayout as base class. Then there is the category of layout elements which actually draw
  1507. something. For example, QCPAxisRect, QCPLegend and QCPPlotTitle are of this category. This does
  1508. not necessarily mean that the latter category can't have child layout elements. QCPLegend for
  1509. instance, actually derives from QCPLayoutGrid and the individual legend items are child layout
  1510. elements in the grid layout.
  1511. */
  1512. /* start documentation of inline functions */
  1513. /*! \fn QCPLayout *QCPLayoutElement::layout() const
  1514. Returns the parent layout of this layout element.
  1515. */
  1516. /*! \fn QRect QCPLayoutElement::rect() const
  1517. Returns the inner rect of this layout element. The inner rect is the outer rect (\ref
  1518. setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins).
  1519. In some cases, the area between outer and inner rect is left blank. In other cases the margin
  1520. area is used to display peripheral graphics while the main content is in the inner rect. This is
  1521. where automatic margin calculation becomes interesting because it allows the layout element to
  1522. adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect
  1523. draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if
  1524. \ref setAutoMargins is enabled) according to the space required by the labels of the axes.
  1525. */
  1526. /*! \fn virtual void QCPLayoutElement::mousePressEvent(QMouseEvent *event)
  1527. This event is called, if the mouse was pressed while being inside the outer rect of this layout
  1528. element.
  1529. */
  1530. /*! \fn virtual void QCPLayoutElement::mouseMoveEvent(QMouseEvent *event)
  1531. This event is called, if the mouse is moved inside the outer rect of this layout element.
  1532. */
  1533. /*! \fn virtual void QCPLayoutElement::mouseReleaseEvent(QMouseEvent *event)
  1534. This event is called, if the mouse was previously pressed inside the outer rect of this layout
  1535. element and is now released.
  1536. */
  1537. /*! \fn virtual void QCPLayoutElement::mouseDoubleClickEvent(QMouseEvent *event)
  1538. This event is called, if the mouse is double-clicked inside the outer rect of this layout
  1539. element.
  1540. */
  1541. /*! \fn virtual void QCPLayoutElement::wheelEvent(QWheelEvent *event)
  1542. This event is called, if the mouse wheel is scrolled while the cursor is inside the rect of this
  1543. layout element.
  1544. */
  1545. /* end documentation of inline functions */
  1546. /*!
  1547. Creates an instance of QCPLayoutElement and sets default values.
  1548. */
  1549. QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) :
  1550. QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout)
  1551. mParentLayout(0),
  1552. mMinimumSize(),
  1553. mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX),
  1554. mRect(0, 0, 0, 0),
  1555. mOuterRect(0, 0, 0, 0),
  1556. mMargins(0, 0, 0, 0),
  1557. mMinimumMargins(0, 0, 0, 0),
  1558. mAutoMargins(QCP::msAll)
  1559. {
  1560. }
  1561. QCPLayoutElement::~QCPLayoutElement()
  1562. {
  1563. setMarginGroup(QCP::msAll, 0); // unregister at margin groups, if there are any
  1564. // unregister at layout:
  1565. 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
  1566. mParentLayout->take(this);
  1567. }
  1568. /*!
  1569. Sets the outer rect of this layout element. If the layout element is inside a layout, the layout
  1570. sets the position and size of this layout element using this function.
  1571. Calling this function externally has no effect, since the layout will overwrite any changes to
  1572. the outer rect upon the next replot.
  1573. The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect.
  1574. \see rect
  1575. */
  1576. void QCPLayoutElement::setOuterRect(const QRect &rect)
  1577. {
  1578. if (mOuterRect != rect)
  1579. {
  1580. mOuterRect = rect;
  1581. mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
  1582. }
  1583. }
  1584. /*!
  1585. Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all
  1586. sides, this function is used to manually set the margin on those sides. Sides that are still set
  1587. to be handled automatically are ignored and may have any value in \a margins.
  1588. The margin is the distance between the outer rect (controlled by the parent layout via \ref
  1589. setOuterRect) and the inner \ref rect (which usually contains the main content of this layout
  1590. element).
  1591. \see setAutoMargins
  1592. */
  1593. void QCPLayoutElement::setMargins(const QMargins &margins)
  1594. {
  1595. if (mMargins != margins)
  1596. {
  1597. mMargins = margins;
  1598. mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
  1599. }
  1600. }
  1601. /*!
  1602. If \ref setAutoMargins is enabled on some or all margins, this function is used to provide
  1603. minimum values for those margins.
  1604. The minimum values are not enforced on margin sides that were set to be under manual control via
  1605. \ref setAutoMargins.
  1606. \see setAutoMargins
  1607. */
  1608. void QCPLayoutElement::setMinimumMargins(const QMargins &margins)
  1609. {
  1610. if (mMinimumMargins != margins)
  1611. {
  1612. mMinimumMargins = margins;
  1613. }
  1614. }
  1615. /*!
  1616. Sets on which sides the margin shall be calculated automatically. If a side is calculated
  1617. automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is
  1618. set to be controlled manually, the value may be specified with \ref setMargins.
  1619. Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref
  1620. setMarginGroup), to synchronize (align) it with other layout elements in the plot.
  1621. \see setMinimumMargins, setMargins
  1622. */
  1623. void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides)
  1624. {
  1625. mAutoMargins = sides;
  1626. }
  1627. /*!
  1628. Sets the minimum size for the inner \ref rect of this layout element. A parent layout tries to
  1629. respect the \a size here by changing row/column sizes in the layout accordingly.
  1630. If the parent layout size is not sufficient to satisfy all minimum size constraints of its child
  1631. layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot
  1632. propagates the layout's size constraints to the outside by setting its own minimum QWidget size
  1633. accordingly, so violations of \a size should be exceptions.
  1634. */
  1635. void QCPLayoutElement::setMinimumSize(const QSize &size)
  1636. {
  1637. if (mMinimumSize != size)
  1638. {
  1639. mMinimumSize = size;
  1640. if (mParentLayout)
  1641. mParentLayout->sizeConstraintsChanged();
  1642. }
  1643. }
  1644. /*! \overload
  1645. Sets the minimum size for the inner \ref rect of this layout element.
  1646. */
  1647. void QCPLayoutElement::setMinimumSize(int width, int height)
  1648. {
  1649. setMinimumSize(QSize(width, height));
  1650. }
  1651. /*!
  1652. Sets the maximum size for the inner \ref rect of this layout element. A parent layout tries to
  1653. respect the \a size here by changing row/column sizes in the layout accordingly.
  1654. */
  1655. void QCPLayoutElement::setMaximumSize(const QSize &size)
  1656. {
  1657. if (mMaximumSize != size)
  1658. {
  1659. mMaximumSize = size;
  1660. if (mParentLayout)
  1661. mParentLayout->sizeConstraintsChanged();
  1662. }
  1663. }
  1664. /*! \overload
  1665. Sets the maximum size for the inner \ref rect of this layout element.
  1666. */
  1667. void QCPLayoutElement::setMaximumSize(int width, int height)
  1668. {
  1669. setMaximumSize(QSize(width, height));
  1670. }
  1671. /*!
  1672. Sets the margin \a group of the specified margin \a sides.
  1673. Margin groups allow synchronizing specified margins across layout elements, see the documentation
  1674. of \ref QCPMarginGroup.
  1675. To unset the margin group of \a sides, set \a group to 0.
  1676. Note that margin groups only work for margin sides that are set to automatic (\ref
  1677. setAutoMargins).
  1678. */
  1679. void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group)
  1680. {
  1681. QVector<QCP::MarginSide> sideVector;
  1682. if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft);
  1683. if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight);
  1684. if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop);
  1685. if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom);
  1686. for (int i=0; i<sideVector.size(); ++i)
  1687. {
  1688. QCP::MarginSide side = sideVector.at(i);
  1689. if (marginGroup(side) != group)
  1690. {
  1691. QCPMarginGroup *oldGroup = marginGroup(side);
  1692. if (oldGroup) // unregister at old group
  1693. oldGroup->removeChild(side, this);
  1694. if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there
  1695. {
  1696. mMarginGroups.remove(side);
  1697. } else // setting to a new group
  1698. {
  1699. mMarginGroups[side] = group;
  1700. group->addChild(side, this);
  1701. }
  1702. }
  1703. }
  1704. }
  1705. /*!
  1706. Updates the layout element and sub-elements. This function is automatically called before every
  1707. replot by the parent layout element. It is called multiple times, once for every \ref
  1708. UpdatePhase. The phases are run through in the order of the enum values. For details about what
  1709. happens at the different phases, see the documentation of \ref UpdatePhase.
  1710. Layout elements that have child elements should call the \ref update method of their child
  1711. elements, and pass the current \a phase unchanged.
  1712. The default implementation executes the automatic margin mechanism in the \ref upMargins phase.
  1713. Subclasses should make sure to call the base class implementation.
  1714. */
  1715. void QCPLayoutElement::update(UpdatePhase phase)
  1716. {
  1717. if (phase == upMargins)
  1718. {
  1719. if (mAutoMargins != QCP::msNone)
  1720. {
  1721. // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group:
  1722. QMargins newMargins = mMargins;
  1723. foreach (QCP::MarginSide side, QList<QCP::MarginSide>() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom)
  1724. {
  1725. if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically
  1726. {
  1727. if (mMarginGroups.contains(side))
  1728. QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group
  1729. else
  1730. QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly
  1731. // apply minimum margin restrictions:
  1732. if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side))
  1733. QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side));
  1734. }
  1735. }
  1736. setMargins(newMargins);
  1737. }
  1738. }
  1739. }
  1740. /*!
  1741. Returns the minimum size this layout element (the inner \ref rect) may be compressed to.
  1742. if a minimum size (\ref setMinimumSize) was not set manually, parent layouts consult this
  1743. function to determine the minimum allowed size of this layout element. (A manual minimum size is
  1744. considered set if it is non-zero.)
  1745. */
  1746. QSize QCPLayoutElement::minimumSizeHint() const
  1747. {
  1748. return mMinimumSize;
  1749. }
  1750. /*!
  1751. Returns the maximum size this layout element (the inner \ref rect) may be expanded to.
  1752. if a maximum size (\ref setMaximumSize) was not set manually, parent layouts consult this
  1753. function to determine the maximum allowed size of this layout element. (A manual maximum size is
  1754. considered set if it is smaller than Qt's QWIDGETSIZE_MAX.)
  1755. */
  1756. QSize QCPLayoutElement::maximumSizeHint() const
  1757. {
  1758. return mMaximumSize;
  1759. }
  1760. /*!
  1761. Returns a list of all child elements in this layout element. If \a recursive is true, all
  1762. sub-child elements are included in the list, too.
  1763. \warning There may be entries with value 0 in the returned list. (For example, QCPLayoutGrid may have
  1764. empty cells which yield 0 at the respective index.)
  1765. */
  1766. QList<QCPLayoutElement*> QCPLayoutElement::elements(bool recursive) const
  1767. {
  1768. Q_UNUSED(recursive)
  1769. return QList<QCPLayoutElement*>();
  1770. }
  1771. /*!
  1772. Layout elements are sensitive to events inside their outer rect. If \a pos is within the outer
  1773. rect, this method returns a value corresponding to 0.99 times the parent plot's selection
  1774. tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is
  1775. true, -1.0 is returned.
  1776. See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
  1777. QCPLayoutElement subclasses may reimplement this method to provide more specific selection test
  1778. behaviour.
  1779. */
  1780. double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  1781. {
  1782. Q_UNUSED(details)
  1783. if (onlySelectable)
  1784. return -1;
  1785. if (QRectF(mOuterRect).contains(pos))
  1786. {
  1787. if (mParentPlot)
  1788. return mParentPlot->selectionTolerance()*0.99;
  1789. else
  1790. {
  1791. qDebug() << Q_FUNC_INFO << "parent plot not defined";
  1792. return -1;
  1793. }
  1794. } else
  1795. return -1;
  1796. }
  1797. /*! \internal
  1798. propagates the parent plot initialization to all child elements, by calling \ref
  1799. QCPLayerable::initializeParentPlot on them.
  1800. */
  1801. void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot)
  1802. {
  1803. foreach (QCPLayoutElement* el, elements(false))
  1804. {
  1805. if (!el->parentPlot())
  1806. el->initializeParentPlot(parentPlot);
  1807. }
  1808. }
  1809. /*! \internal
  1810. Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a
  1811. side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the
  1812. returned value will not be smaller than the specified minimum margin.
  1813. The default implementation just returns the respective manual margin (\ref setMargins) or the
  1814. minimum margin, whichever is larger.
  1815. */
  1816. int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side)
  1817. {
  1818. return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side));
  1819. }
  1820. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1821. //////////////////// QCPLayout
  1822. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1823. /*! \class QCPLayout
  1824. \brief The abstract base class for layouts
  1825. This is an abstract base class for layout elements whose main purpose is to define the position
  1826. and size of other child layout elements. In most cases, layouts don't draw anything themselves
  1827. (but there are exceptions to this, e.g. QCPLegend).
  1828. QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts.
  1829. QCPLayout introduces a common interface for accessing and manipulating the child elements. Those
  1830. functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref
  1831. simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions
  1832. to this interface which are more specialized to the form of the layout. For example, \ref
  1833. QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid
  1834. more conveniently.
  1835. Since this is an abstract base class, you can't instantiate it directly. Rather use one of its
  1836. subclasses like QCPLayoutGrid or QCPLayoutInset.
  1837. For a general introduction to the layout system, see the dedicated documentation page \ref
  1838. thelayoutsystem "The Layout System".
  1839. */
  1840. /* start documentation of pure virtual functions */
  1841. /*! \fn virtual int QCPLayout::elementCount() const = 0
  1842. Returns the number of elements/cells in the layout.
  1843. \see elements, elementAt
  1844. */
  1845. /*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0
  1846. Returns the element in the cell with the given \a index. If \a index is invalid, returns 0.
  1847. Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g.
  1848. QCPLayoutGrid), so this function may return 0 in those cases. You may use this function to check
  1849. whether a cell is empty or not.
  1850. \see elements, elementCount, takeAt
  1851. */
  1852. /*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0
  1853. Removes the element with the given \a index from the layout and returns it.
  1854. If the \a index is invalid or the cell with that index is empty, returns 0.
  1855. Note that some layouts don't remove the respective cell right away but leave an empty cell after
  1856. successful removal of the layout element. To collapse empty cells, use \ref simplify.
  1857. \see elementAt, take
  1858. */
  1859. /*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0
  1860. Removes the specified \a element from the layout and returns true on success.
  1861. If the \a element isn't in this layout, returns false.
  1862. Note that some layouts don't remove the respective cell right away but leave an empty cell after
  1863. successful removal of the layout element. To collapse empty cells, use \ref simplify.
  1864. \see takeAt
  1865. */
  1866. /* end documentation of pure virtual functions */
  1867. /*!
  1868. Creates an instance of QCPLayout and sets default values. Note that since QCPLayout
  1869. is an abstract base class, it can't be instantiated directly.
  1870. */
  1871. QCPLayout::QCPLayout()
  1872. {
  1873. }
  1874. /*!
  1875. First calls the QCPLayoutElement::update base class implementation to update the margins on this
  1876. layout.
  1877. Then calls \ref updateLayout which subclasses reimplement to reposition and resize their cells.
  1878. Finally, \ref update is called on all child elements.
  1879. */
  1880. void QCPLayout::update(UpdatePhase phase)
  1881. {
  1882. QCPLayoutElement::update(phase);
  1883. // set child element rects according to layout:
  1884. if (phase == upLayout)
  1885. updateLayout();
  1886. // propagate update call to child elements:
  1887. const int elCount = elementCount();
  1888. for (int i=0; i<elCount; ++i)
  1889. {
  1890. if (QCPLayoutElement *el = elementAt(i))
  1891. el->update(phase);
  1892. }
  1893. }
  1894. /* inherits documentation from base class */
  1895. QList<QCPLayoutElement*> QCPLayout::elements(bool recursive) const
  1896. {
  1897. const int c = elementCount();
  1898. QList<QCPLayoutElement*> result;
  1899. #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
  1900. result.reserve(c);
  1901. #endif
  1902. for (int i=0; i<c; ++i)
  1903. result.append(elementAt(i));
  1904. if (recursive)
  1905. {
  1906. for (int i=0; i<c; ++i)
  1907. {
  1908. if (result.at(i))
  1909. result << result.at(i)->elements(recursive);
  1910. }
  1911. }
  1912. return result;
  1913. }
  1914. /*!
  1915. Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the
  1916. default implementation does nothing.
  1917. Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit
  1918. simplification while QCPLayoutGrid does.
  1919. */
  1920. void QCPLayout::simplify()
  1921. {
  1922. }
  1923. /*!
  1924. Removes and deletes the element at the provided \a index. Returns true on success. If \a index is
  1925. invalid or points to an empty cell, returns false.
  1926. This function internally uses \ref takeAt to remove the element from the layout and then deletes
  1927. the returned element.
  1928. \see remove, takeAt
  1929. */
  1930. bool QCPLayout::removeAt(int index)
  1931. {
  1932. if (QCPLayoutElement *el = takeAt(index))
  1933. {
  1934. delete el;
  1935. return true;
  1936. } else
  1937. return false;
  1938. }
  1939. /*!
  1940. Removes and deletes the provided \a element. Returns true on success. If \a element is not in the
  1941. layout, returns false.
  1942. This function internally uses \ref takeAt to remove the element from the layout and then deletes
  1943. the element.
  1944. \see removeAt, take
  1945. */
  1946. bool QCPLayout::remove(QCPLayoutElement *element)
  1947. {
  1948. if (take(element))
  1949. {
  1950. delete element;
  1951. return true;
  1952. } else
  1953. return false;
  1954. }
  1955. /*!
  1956. Removes and deletes all layout elements in this layout.
  1957. \see remove, removeAt
  1958. */
  1959. void QCPLayout::clear()
  1960. {
  1961. for (int i=elementCount()-1; i>=0; --i)
  1962. {
  1963. if (elementAt(i))
  1964. removeAt(i);
  1965. }
  1966. simplify();
  1967. }
  1968. /*!
  1969. Subclasses call this method to report changed (minimum/maximum) size constraints.
  1970. If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref
  1971. sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of
  1972. QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout,
  1973. it may update itself and resize cells accordingly.
  1974. */
  1975. void QCPLayout::sizeConstraintsChanged() const
  1976. {
  1977. if (QWidget *w = qobject_cast<QWidget*>(parent()))
  1978. w->updateGeometry();
  1979. else if (QCPLayout *l = qobject_cast<QCPLayout*>(parent()))
  1980. l->sizeConstraintsChanged();
  1981. }
  1982. /*! \internal
  1983. Subclasses reimplement this method to update the position and sizes of the child elements/cells
  1984. via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing.
  1985. The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay
  1986. within that rect.
  1987. \ref getSectionSizes may help with the reimplementation of this function.
  1988. \see update
  1989. */
  1990. void QCPLayout::updateLayout()
  1991. {
  1992. }
  1993. /*! \internal
  1994. Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the
  1995. \ref QCPLayerable::parentLayerable and the QObject parent to this layout.
  1996. Further, if \a el didn't previously have a parent plot, calls \ref
  1997. QCPLayerable::initializeParentPlot on \a el to set the paret plot.
  1998. This method is used by subclass specific methods that add elements to the layout. Note that this
  1999. method only changes properties in \a el. The removal from the old layout and the insertion into
  2000. the new layout must be done additionally.
  2001. */
  2002. void QCPLayout::adoptElement(QCPLayoutElement *el)
  2003. {
  2004. if (el)
  2005. {
  2006. el->mParentLayout = this;
  2007. el->setParentLayerable(this);
  2008. el->setParent(this);
  2009. if (!el->parentPlot())
  2010. el->initializeParentPlot(mParentPlot);
  2011. } else
  2012. qDebug() << Q_FUNC_INFO << "Null element passed";
  2013. }
  2014. /*! \internal
  2015. Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout
  2016. and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent
  2017. QCustomPlot.
  2018. This method is used by subclass specific methods that remove elements from the layout (e.g. \ref
  2019. take or \ref takeAt). Note that this method only changes properties in \a el. The removal from
  2020. the old layout must be done additionally.
  2021. */
  2022. void QCPLayout::releaseElement(QCPLayoutElement *el)
  2023. {
  2024. if (el)
  2025. {
  2026. el->mParentLayout = 0;
  2027. el->setParentLayerable(0);
  2028. el->setParent(mParentPlot);
  2029. // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot
  2030. } else
  2031. qDebug() << Q_FUNC_INFO << "Null element passed";
  2032. }
  2033. /*! \internal
  2034. This is a helper function for the implementation of \ref updateLayout in subclasses.
  2035. It calculates the sizes of one-dimensional sections with provided constraints on maximum section
  2036. sizes, minimum section sizes, relative stretch factors and the final total size of all sections.
  2037. The QVector entries refer to the sections. Thus all QVectors must have the same size.
  2038. \a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size
  2039. imposed, set all vector values to Qt's QWIDGETSIZE_MAX.
  2040. \a minSizes gives the minimum allowed size of each section. If there shall be no minimum size
  2041. imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than
  2042. \a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words,
  2043. not exceeding the allowed total size is taken to be more important than not going below minimum
  2044. section sizes.)
  2045. \a stretchFactors give the relative proportions of the sections to each other. If all sections
  2046. shall be scaled equally, set all values equal. If the first section shall be double the size of
  2047. each individual other section, set the first number of \a stretchFactors to double the value of
  2048. the other individual values (e.g. {2, 1, 1, 1}).
  2049. \a totalSize is the value that the final section sizes will add up to. Due to rounding, the
  2050. actual sum may differ slightly. If you want the section sizes to sum up to exactly that value,
  2051. you could distribute the remaining difference on the sections.
  2052. The return value is a QVector containing the section sizes.
  2053. */
  2054. QVector<int> QCPLayout::getSectionSizes(QVector<int> maxSizes, QVector<int> minSizes, QVector<double> stretchFactors, int totalSize) const
  2055. {
  2056. if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size())
  2057. {
  2058. qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors;
  2059. return QVector<int>();
  2060. }
  2061. if (stretchFactors.isEmpty())
  2062. return QVector<int>();
  2063. int sectionCount = stretchFactors.size();
  2064. QVector<double> sectionSizes(sectionCount);
  2065. // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections):
  2066. int minSizeSum = 0;
  2067. for (int i=0; i<sectionCount; ++i)
  2068. minSizeSum += minSizes.at(i);
  2069. if (totalSize < minSizeSum)
  2070. {
  2071. // new stretch factors are minimum sizes and minimum sizes are set to zero:
  2072. for (int i=0; i<sectionCount; ++i)
  2073. {
  2074. stretchFactors[i] = minSizes.at(i);
  2075. minSizes[i] = 0;
  2076. }
  2077. }
  2078. QList<int> minimumLockedSections;
  2079. QList<int> unfinishedSections;
  2080. for (int i=0; i<sectionCount; ++i)
  2081. unfinishedSections.append(i);
  2082. double freeSize = totalSize;
  2083. int outerIterations = 0;
  2084. while (!unfinishedSections.isEmpty() && outerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
  2085. {
  2086. ++outerIterations;
  2087. int innerIterations = 0;
  2088. while (!unfinishedSections.isEmpty() && innerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
  2089. {
  2090. ++innerIterations;
  2091. // find section that hits its maximum next:
  2092. int nextId = -1;
  2093. double nextMax = 1e12;
  2094. for (int i=0; i<unfinishedSections.size(); ++i)
  2095. {
  2096. int secId = unfinishedSections.at(i);
  2097. double hitsMaxAt = (maxSizes.at(secId)-sectionSizes.at(secId))/stretchFactors.at(secId);
  2098. if (hitsMaxAt < nextMax)
  2099. {
  2100. nextMax = hitsMaxAt;
  2101. nextId = secId;
  2102. }
  2103. }
  2104. // 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
  2105. // actually hits its maximum, without exceeding the total size when we add up all sections)
  2106. double stretchFactorSum = 0;
  2107. for (int i=0; i<unfinishedSections.size(); ++i)
  2108. stretchFactorSum += stretchFactors.at(unfinishedSections.at(i));
  2109. double nextMaxLimit = freeSize/stretchFactorSum;
  2110. if (nextMax < nextMaxLimit) // next maximum is actually hit, move forward to that point and fix the size of that section
  2111. {
  2112. for (int i=0; i<unfinishedSections.size(); ++i)
  2113. {
  2114. sectionSizes[unfinishedSections.at(i)] += nextMax*stretchFactors.at(unfinishedSections.at(i)); // increment all sections
  2115. freeSize -= nextMax*stretchFactors.at(unfinishedSections.at(i));
  2116. }
  2117. unfinishedSections.removeOne(nextId); // exclude the section that is now at maximum from further changes
  2118. } else // next maximum isn't hit, just distribute rest of free space on remaining sections
  2119. {
  2120. for (int i=0; i<unfinishedSections.size(); ++i)
  2121. sectionSizes[unfinishedSections.at(i)] += nextMaxLimit*stretchFactors.at(unfinishedSections.at(i)); // increment all sections
  2122. unfinishedSections.clear();
  2123. }
  2124. }
  2125. if (innerIterations == sectionCount*2)
  2126. qDebug() << Q_FUNC_INFO << "Exceeded maximum expected inner iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
  2127. // now check whether the resulting section sizes violate minimum restrictions:
  2128. bool foundMinimumViolation = false;
  2129. for (int i=0; i<sectionSizes.size(); ++i)
  2130. {
  2131. if (minimumLockedSections.contains(i))
  2132. continue;
  2133. if (sectionSizes.at(i) < minSizes.at(i)) // section violates minimum
  2134. {
  2135. sectionSizes[i] = minSizes.at(i); // set it to minimum
  2136. foundMinimumViolation = true; // make sure we repeat the whole optimization process
  2137. minimumLockedSections.append(i);
  2138. }
  2139. }
  2140. if (foundMinimumViolation)
  2141. {
  2142. freeSize = totalSize;
  2143. for (int i=0; i<sectionCount; ++i)
  2144. {
  2145. if (!minimumLockedSections.contains(i)) // only put sections that haven't hit their minimum back into the pool
  2146. unfinishedSections.append(i);
  2147. else
  2148. freeSize -= sectionSizes.at(i); // remove size of minimum locked sections from available space in next round
  2149. }
  2150. // reset all section sizes to zero that are in unfinished sections (all others have been set to their minimum):
  2151. for (int i=0; i<unfinishedSections.size(); ++i)
  2152. sectionSizes[unfinishedSections.at(i)] = 0;
  2153. }
  2154. }
  2155. if (outerIterations == sectionCount*2)
  2156. qDebug() << Q_FUNC_INFO << "Exceeded maximum expected outer iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
  2157. QVector<int> result(sectionCount);
  2158. for (int i=0; i<sectionCount; ++i)
  2159. result[i] = qRound(sectionSizes.at(i));
  2160. return result;
  2161. }
  2162. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2163. //////////////////// QCPLayoutGrid
  2164. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2165. /*! \class QCPLayoutGrid
  2166. \brief A layout that arranges child elements in a grid
  2167. Elements are laid out in a grid with configurable stretch factors (\ref setColumnStretchFactor,
  2168. \ref setRowStretchFactor) and spacing (\ref setColumnSpacing, \ref setRowSpacing).
  2169. Elements can be added to cells via \ref addElement. The grid is expanded if the specified row or
  2170. column doesn't exist yet. Whether a cell contains a valid layout element can be checked with \ref
  2171. hasElement, that element can be retrieved with \ref element. If rows and columns that only have
  2172. empty cells shall be removed, call \ref simplify. Removal of elements is either done by just
  2173. adding the element to a different layout or by using the QCPLayout interface \ref take or \ref
  2174. remove.
  2175. Row and column insertion can be performed with \ref insertRow and \ref insertColumn.
  2176. */
  2177. /*!
  2178. Creates an instance of QCPLayoutGrid and sets default values.
  2179. */
  2180. QCPLayoutGrid::QCPLayoutGrid() :
  2181. mColumnSpacing(5),
  2182. mRowSpacing(5)
  2183. {
  2184. }
  2185. QCPLayoutGrid::~QCPLayoutGrid()
  2186. {
  2187. // clear all child layout elements. This is important because only the specific layouts know how
  2188. // to handle removing elements (clear calls virtual removeAt method to do that).
  2189. clear();
  2190. }
  2191. /*!
  2192. Returns the element in the cell in \a row and \a column.
  2193. Returns 0 if either the row/column is invalid or if the cell is empty. In those cases, a qDebug
  2194. message is printed. To check whether a cell exists and isn't empty, use \ref hasElement.
  2195. \see addElement, hasElement
  2196. */
  2197. QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const
  2198. {
  2199. if (row >= 0 && row < mElements.size())
  2200. {
  2201. if (column >= 0 && column < mElements.first().size())
  2202. {
  2203. if (QCPLayoutElement *result = mElements.at(row).at(column))
  2204. return result;
  2205. else
  2206. qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column;
  2207. } else
  2208. qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column;
  2209. } else
  2210. qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column;
  2211. return 0;
  2212. }
  2213. /*!
  2214. Returns the number of rows in the layout.
  2215. \see columnCount
  2216. */
  2217. int QCPLayoutGrid::rowCount() const
  2218. {
  2219. return mElements.size();
  2220. }
  2221. /*!
  2222. Returns the number of columns in the layout.
  2223. \see rowCount
  2224. */
  2225. int QCPLayoutGrid::columnCount() const
  2226. {
  2227. if (mElements.size() > 0)
  2228. return mElements.first().size();
  2229. else
  2230. return 0;
  2231. }
  2232. /*!
  2233. Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it
  2234. is first removed from there. If \a row or \a column don't exist yet, the layout is expanded
  2235. accordingly.
  2236. Returns true if the element was added successfully, i.e. if the cell at \a row and \a column
  2237. didn't already have an element.
  2238. \see element, hasElement, take, remove
  2239. */
  2240. bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element)
  2241. {
  2242. if (element)
  2243. {
  2244. if (!hasElement(row, column))
  2245. {
  2246. if (element->layout()) // remove from old layout first
  2247. element->layout()->take(element);
  2248. expandTo(row+1, column+1);
  2249. mElements[row][column] = element;
  2250. adoptElement(element);
  2251. return true;
  2252. } else
  2253. qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column;
  2254. } else
  2255. qDebug() << Q_FUNC_INFO << "Can't add null element to row/column:" << row << column;
  2256. return false;
  2257. }
  2258. /*!
  2259. Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't
  2260. empty.
  2261. \see element
  2262. */
  2263. bool QCPLayoutGrid::hasElement(int row, int column)
  2264. {
  2265. if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount())
  2266. return mElements.at(row).at(column);
  2267. else
  2268. return false;
  2269. }
  2270. /*!
  2271. Sets the stretch \a factor of \a column.
  2272. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  2273. their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
  2274. QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
  2275. The default stretch factor of newly created rows/columns is 1.
  2276. \see setColumnStretchFactors, setRowStretchFactor
  2277. */
  2278. void QCPLayoutGrid::setColumnStretchFactor(int column, double factor)
  2279. {
  2280. if (column >= 0 && column < columnCount())
  2281. {
  2282. if (factor > 0)
  2283. mColumnStretchFactors[column] = factor;
  2284. else
  2285. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
  2286. } else
  2287. qDebug() << Q_FUNC_INFO << "Invalid column:" << column;
  2288. }
  2289. /*!
  2290. Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount.
  2291. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  2292. their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
  2293. QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
  2294. The default stretch factor of newly created rows/columns is 1.
  2295. \see setColumnStretchFactor, setRowStretchFactors
  2296. */
  2297. void QCPLayoutGrid::setColumnStretchFactors(const QList<double> &factors)
  2298. {
  2299. if (factors.size() == mColumnStretchFactors.size())
  2300. {
  2301. mColumnStretchFactors = factors;
  2302. for (int i=0; i<mColumnStretchFactors.size(); ++i)
  2303. {
  2304. if (mColumnStretchFactors.at(i) <= 0)
  2305. {
  2306. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mColumnStretchFactors.at(i);
  2307. mColumnStretchFactors[i] = 1;
  2308. }
  2309. }
  2310. } else
  2311. qDebug() << Q_FUNC_INFO << "Column count not equal to passed stretch factor count:" << factors;
  2312. }
  2313. /*!
  2314. Sets the stretch \a factor of \a row.
  2315. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  2316. their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
  2317. QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
  2318. The default stretch factor of newly created rows/columns is 1.
  2319. \see setColumnStretchFactors, setRowStretchFactor
  2320. */
  2321. void QCPLayoutGrid::setRowStretchFactor(int row, double factor)
  2322. {
  2323. if (row >= 0 && row < rowCount())
  2324. {
  2325. if (factor > 0)
  2326. mRowStretchFactors[row] = factor;
  2327. else
  2328. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
  2329. } else
  2330. qDebug() << Q_FUNC_INFO << "Invalid row:" << row;
  2331. }
  2332. /*!
  2333. Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount.
  2334. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  2335. their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
  2336. QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
  2337. The default stretch factor of newly created rows/columns is 1.
  2338. \see setRowStretchFactor, setColumnStretchFactors
  2339. */
  2340. void QCPLayoutGrid::setRowStretchFactors(const QList<double> &factors)
  2341. {
  2342. if (factors.size() == mRowStretchFactors.size())
  2343. {
  2344. mRowStretchFactors = factors;
  2345. for (int i=0; i<mRowStretchFactors.size(); ++i)
  2346. {
  2347. if (mRowStretchFactors.at(i) <= 0)
  2348. {
  2349. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mRowStretchFactors.at(i);
  2350. mRowStretchFactors[i] = 1;
  2351. }
  2352. }
  2353. } else
  2354. qDebug() << Q_FUNC_INFO << "Row count not equal to passed stretch factor count:" << factors;
  2355. }
  2356. /*!
  2357. Sets the gap that is left blank between columns to \a pixels.
  2358. \see setRowSpacing
  2359. */
  2360. void QCPLayoutGrid::setColumnSpacing(int pixels)
  2361. {
  2362. mColumnSpacing = pixels;
  2363. }
  2364. /*!
  2365. Sets the gap that is left blank between rows to \a pixels.
  2366. \see setColumnSpacing
  2367. */
  2368. void QCPLayoutGrid::setRowSpacing(int pixels)
  2369. {
  2370. mRowSpacing = pixels;
  2371. }
  2372. /*!
  2373. Expands the layout to have \a newRowCount rows and \a newColumnCount columns. So the last valid
  2374. row index will be \a newRowCount-1, the last valid column index will be \a newColumnCount-1.
  2375. If the current column/row count is already larger or equal to \a newColumnCount/\a newRowCount,
  2376. this function does nothing in that dimension.
  2377. Newly created cells are empty, new rows and columns have the stretch factor 1.
  2378. Note that upon a call to \ref addElement, the layout is expanded automatically to contain the
  2379. specified row and column, using this function.
  2380. \see simplify
  2381. */
  2382. void QCPLayoutGrid::expandTo(int newRowCount, int newColumnCount)
  2383. {
  2384. // add rows as necessary:
  2385. while (rowCount() < newRowCount)
  2386. {
  2387. mElements.append(QList<QCPLayoutElement*>());
  2388. mRowStretchFactors.append(1);
  2389. }
  2390. // go through rows and expand columns as necessary:
  2391. int newColCount = qMax(columnCount(), newColumnCount);
  2392. for (int i=0; i<rowCount(); ++i)
  2393. {
  2394. while (mElements.at(i).size() < newColCount)
  2395. mElements[i].append(0);
  2396. }
  2397. while (mColumnStretchFactors.size() < newColCount)
  2398. mColumnStretchFactors.append(1);
  2399. }
  2400. /*!
  2401. Inserts a new row with empty cells at the row index \a newIndex. Valid values for \a newIndex
  2402. range from 0 (inserts a row at the top) to \a rowCount (appends a row at the bottom).
  2403. \see insertColumn
  2404. */
  2405. void QCPLayoutGrid::insertRow(int newIndex)
  2406. {
  2407. if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
  2408. {
  2409. expandTo(1, 1);
  2410. return;
  2411. }
  2412. if (newIndex < 0)
  2413. newIndex = 0;
  2414. if (newIndex > rowCount())
  2415. newIndex = rowCount();
  2416. mRowStretchFactors.insert(newIndex, 1);
  2417. QList<QCPLayoutElement*> newRow;
  2418. for (int col=0; col<columnCount(); ++col)
  2419. newRow.append((QCPLayoutElement*)0);
  2420. mElements.insert(newIndex, newRow);
  2421. }
  2422. /*!
  2423. Inserts a new column with empty cells at the column index \a newIndex. Valid values for \a
  2424. newIndex range from 0 (inserts a row at the left) to \a rowCount (appends a row at the right).
  2425. \see insertRow
  2426. */
  2427. void QCPLayoutGrid::insertColumn(int newIndex)
  2428. {
  2429. if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
  2430. {
  2431. expandTo(1, 1);
  2432. return;
  2433. }
  2434. if (newIndex < 0)
  2435. newIndex = 0;
  2436. if (newIndex > columnCount())
  2437. newIndex = columnCount();
  2438. mColumnStretchFactors.insert(newIndex, 1);
  2439. for (int row=0; row<rowCount(); ++row)
  2440. mElements[row].insert(newIndex, (QCPLayoutElement*)0);
  2441. }
  2442. /* inherits documentation from base class */
  2443. void QCPLayoutGrid::updateLayout()
  2444. {
  2445. QVector<int> minColWidths, minRowHeights, maxColWidths, maxRowHeights;
  2446. getMinimumRowColSizes(&minColWidths, &minRowHeights);
  2447. getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
  2448. int totalRowSpacing = (rowCount()-1) * mRowSpacing;
  2449. int totalColSpacing = (columnCount()-1) * mColumnSpacing;
  2450. QVector<int> colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing);
  2451. QVector<int> rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing);
  2452. // go through cells and set rects accordingly:
  2453. int yOffset = mRect.top();
  2454. for (int row=0; row<rowCount(); ++row)
  2455. {
  2456. if (row > 0)
  2457. yOffset += rowHeights.at(row-1)+mRowSpacing;
  2458. int xOffset = mRect.left();
  2459. for (int col=0; col<columnCount(); ++col)
  2460. {
  2461. if (col > 0)
  2462. xOffset += colWidths.at(col-1)+mColumnSpacing;
  2463. if (mElements.at(row).at(col))
  2464. mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row)));
  2465. }
  2466. }
  2467. }
  2468. /* inherits documentation from base class */
  2469. int QCPLayoutGrid::elementCount() const
  2470. {
  2471. return rowCount()*columnCount();
  2472. }
  2473. /* inherits documentation from base class */
  2474. QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const
  2475. {
  2476. if (index >= 0 && index < elementCount())
  2477. return mElements.at(index / columnCount()).at(index % columnCount());
  2478. else
  2479. return 0;
  2480. }
  2481. /* inherits documentation from base class */
  2482. QCPLayoutElement *QCPLayoutGrid::takeAt(int index)
  2483. {
  2484. if (QCPLayoutElement *el = elementAt(index))
  2485. {
  2486. releaseElement(el);
  2487. mElements[index / columnCount()][index % columnCount()] = 0;
  2488. return el;
  2489. } else
  2490. {
  2491. qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
  2492. return 0;
  2493. }
  2494. }
  2495. /* inherits documentation from base class */
  2496. bool QCPLayoutGrid::take(QCPLayoutElement *element)
  2497. {
  2498. if (element)
  2499. {
  2500. for (int i=0; i<elementCount(); ++i)
  2501. {
  2502. if (elementAt(i) == element)
  2503. {
  2504. takeAt(i);
  2505. return true;
  2506. }
  2507. }
  2508. qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
  2509. } else
  2510. qDebug() << Q_FUNC_INFO << "Can't take null element";
  2511. return false;
  2512. }
  2513. /* inherits documentation from base class */
  2514. QList<QCPLayoutElement*> QCPLayoutGrid::elements(bool recursive) const
  2515. {
  2516. QList<QCPLayoutElement*> result;
  2517. int colC = columnCount();
  2518. int rowC = rowCount();
  2519. #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
  2520. result.reserve(colC*rowC);
  2521. #endif
  2522. for (int row=0; row<rowC; ++row)
  2523. {
  2524. for (int col=0; col<colC; ++col)
  2525. {
  2526. result.append(mElements.at(row).at(col));
  2527. }
  2528. }
  2529. if (recursive)
  2530. {
  2531. int c = result.size();
  2532. for (int i=0; i<c; ++i)
  2533. {
  2534. if (result.at(i))
  2535. result << result.at(i)->elements(recursive);
  2536. }
  2537. }
  2538. return result;
  2539. }
  2540. /*!
  2541. Simplifies the layout by collapsing rows and columns which only contain empty cells.
  2542. */
  2543. void QCPLayoutGrid::simplify()
  2544. {
  2545. // remove rows with only empty cells:
  2546. for (int row=rowCount()-1; row>=0; --row)
  2547. {
  2548. bool hasElements = false;
  2549. for (int col=0; col<columnCount(); ++col)
  2550. {
  2551. if (mElements.at(row).at(col))
  2552. {
  2553. hasElements = true;
  2554. break;
  2555. }
  2556. }
  2557. if (!hasElements)
  2558. {
  2559. mRowStretchFactors.removeAt(row);
  2560. mElements.removeAt(row);
  2561. if (mElements.isEmpty()) // removed last element, also remove stretch factor (wouldn't happen below because also columnCount changed to 0 now)
  2562. mColumnStretchFactors.clear();
  2563. }
  2564. }
  2565. // remove columns with only empty cells:
  2566. for (int col=columnCount()-1; col>=0; --col)
  2567. {
  2568. bool hasElements = false;
  2569. for (int row=0; row<rowCount(); ++row)
  2570. {
  2571. if (mElements.at(row).at(col))
  2572. {
  2573. hasElements = true;
  2574. break;
  2575. }
  2576. }
  2577. if (!hasElements)
  2578. {
  2579. mColumnStretchFactors.removeAt(col);
  2580. for (int row=0; row<rowCount(); ++row)
  2581. mElements[row].removeAt(col);
  2582. }
  2583. }
  2584. }
  2585. /* inherits documentation from base class */
  2586. QSize QCPLayoutGrid::minimumSizeHint() const
  2587. {
  2588. QVector<int> minColWidths, minRowHeights;
  2589. getMinimumRowColSizes(&minColWidths, &minRowHeights);
  2590. QSize result(0, 0);
  2591. for (int i=0; i<minColWidths.size(); ++i)
  2592. result.rwidth() += minColWidths.at(i);
  2593. for (int i=0; i<minRowHeights.size(); ++i)
  2594. result.rheight() += minRowHeights.at(i);
  2595. result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing + mMargins.left() + mMargins.right();
  2596. result.rheight() += qMax(0, rowCount()-1) * mRowSpacing + mMargins.top() + mMargins.bottom();
  2597. return result;
  2598. }
  2599. /* inherits documentation from base class */
  2600. QSize QCPLayoutGrid::maximumSizeHint() const
  2601. {
  2602. QVector<int> maxColWidths, maxRowHeights;
  2603. getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
  2604. QSize result(0, 0);
  2605. for (int i=0; i<maxColWidths.size(); ++i)
  2606. result.setWidth(qMin(result.width()+maxColWidths.at(i), QWIDGETSIZE_MAX));
  2607. for (int i=0; i<maxRowHeights.size(); ++i)
  2608. result.setHeight(qMin(result.height()+maxRowHeights.at(i), QWIDGETSIZE_MAX));
  2609. result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing + mMargins.left() + mMargins.right();
  2610. result.rheight() += qMax(0, rowCount()-1) * mRowSpacing + mMargins.top() + mMargins.bottom();
  2611. return result;
  2612. }
  2613. /*! \internal
  2614. Places the minimum column widths and row heights into \a minColWidths and \a minRowHeights
  2615. respectively.
  2616. The minimum height of a row is the largest minimum height of any element in that row. The minimum
  2617. width of a column is the largest minimum width of any element in that column.
  2618. This is a helper function for \ref updateLayout.
  2619. \see getMaximumRowColSizes
  2620. */
  2621. void QCPLayoutGrid::getMinimumRowColSizes(QVector<int> *minColWidths, QVector<int> *minRowHeights) const
  2622. {
  2623. *minColWidths = QVector<int>(columnCount(), 0);
  2624. *minRowHeights = QVector<int>(rowCount(), 0);
  2625. for (int row=0; row<rowCount(); ++row)
  2626. {
  2627. for (int col=0; col<columnCount(); ++col)
  2628. {
  2629. if (mElements.at(row).at(col))
  2630. {
  2631. QSize minHint = mElements.at(row).at(col)->minimumSizeHint();
  2632. QSize min = mElements.at(row).at(col)->minimumSize();
  2633. QSize final(min.width() > 0 ? min.width() : minHint.width(), min.height() > 0 ? min.height() : minHint.height());
  2634. if (minColWidths->at(col) < final.width())
  2635. (*minColWidths)[col] = final.width();
  2636. if (minRowHeights->at(row) < final.height())
  2637. (*minRowHeights)[row] = final.height();
  2638. }
  2639. }
  2640. }
  2641. }
  2642. /*! \internal
  2643. Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights
  2644. respectively.
  2645. The maximum height of a row is the smallest maximum height of any element in that row. The
  2646. maximum width of a column is the smallest maximum width of any element in that column.
  2647. This is a helper function for \ref updateLayout.
  2648. \see getMinimumRowColSizes
  2649. */
  2650. void QCPLayoutGrid::getMaximumRowColSizes(QVector<int> *maxColWidths, QVector<int> *maxRowHeights) const
  2651. {
  2652. *maxColWidths = QVector<int>(columnCount(), QWIDGETSIZE_MAX);
  2653. *maxRowHeights = QVector<int>(rowCount(), QWIDGETSIZE_MAX);
  2654. for (int row=0; row<rowCount(); ++row)
  2655. {
  2656. for (int col=0; col<columnCount(); ++col)
  2657. {
  2658. if (mElements.at(row).at(col))
  2659. {
  2660. QSize maxHint = mElements.at(row).at(col)->maximumSizeHint();
  2661. QSize max = mElements.at(row).at(col)->maximumSize();
  2662. QSize final(max.width() < QWIDGETSIZE_MAX ? max.width() : maxHint.width(), max.height() < QWIDGETSIZE_MAX ? max.height() : maxHint.height());
  2663. if (maxColWidths->at(col) > final.width())
  2664. (*maxColWidths)[col] = final.width();
  2665. if (maxRowHeights->at(row) > final.height())
  2666. (*maxRowHeights)[row] = final.height();
  2667. }
  2668. }
  2669. }
  2670. }
  2671. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2672. //////////////////// QCPLayoutInset
  2673. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2674. /*! \class QCPLayoutInset
  2675. \brief A layout that places child elements aligned to the border or arbitrarily positioned
  2676. Elements are placed either aligned to the border or at arbitrary position in the area of the
  2677. layout. Which placement applies is controlled with the \ref InsetPlacement (\ref
  2678. setInsetPlacement).
  2679. Elements are added via \ref addElement(QCPLayoutElement *element, Qt::Alignment alignment) or
  2680. addElement(QCPLayoutElement *element, const QRectF &rect). If the first method is used, the inset
  2681. placement will default to \ref ipBorderAligned and the element will be aligned according to the
  2682. \a alignment parameter. The second method defaults to \ref ipFree and allows placing elements at
  2683. arbitrary position and size, defined by \a rect.
  2684. The alignment or rect can be set via \ref setInsetAlignment or \ref setInsetRect, respectively.
  2685. This is the layout that every QCPAxisRect has as \ref QCPAxisRect::insetLayout.
  2686. */
  2687. /* start documentation of inline functions */
  2688. /*! \fn virtual void QCPLayoutInset::simplify()
  2689. The QCPInsetLayout does not need simplification since it can never have empty cells due to its
  2690. linear index structure. This method does nothing.
  2691. */
  2692. /* end documentation of inline functions */
  2693. /*!
  2694. Creates an instance of QCPLayoutInset and sets default values.
  2695. */
  2696. QCPLayoutInset::QCPLayoutInset()
  2697. {
  2698. }
  2699. QCPLayoutInset::~QCPLayoutInset()
  2700. {
  2701. // clear all child layout elements. This is important because only the specific layouts know how
  2702. // to handle removing elements (clear calls virtual removeAt method to do that).
  2703. clear();
  2704. }
  2705. /*!
  2706. Returns the placement type of the element with the specified \a index.
  2707. */
  2708. QCPLayoutInset::InsetPlacement QCPLayoutInset::insetPlacement(int index) const
  2709. {
  2710. if (elementAt(index))
  2711. return mInsetPlacement.at(index);
  2712. else
  2713. {
  2714. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  2715. return ipFree;
  2716. }
  2717. }
  2718. /*!
  2719. Returns the alignment of the element with the specified \a index. The alignment only has a
  2720. meaning, if the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned.
  2721. */
  2722. Qt::Alignment QCPLayoutInset::insetAlignment(int index) const
  2723. {
  2724. if (elementAt(index))
  2725. return mInsetAlignment.at(index);
  2726. else
  2727. {
  2728. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  2729. return 0;
  2730. }
  2731. }
  2732. /*!
  2733. Returns the rect of the element with the specified \a index. The rect only has a
  2734. meaning, if the inset placement (\ref setInsetPlacement) is \ref ipFree.
  2735. */
  2736. QRectF QCPLayoutInset::insetRect(int index) const
  2737. {
  2738. if (elementAt(index))
  2739. return mInsetRect.at(index);
  2740. else
  2741. {
  2742. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  2743. return QRectF();
  2744. }
  2745. }
  2746. /*!
  2747. Sets the inset placement type of the element with the specified \a index to \a placement.
  2748. \see InsetPlacement
  2749. */
  2750. void QCPLayoutInset::setInsetPlacement(int index, QCPLayoutInset::InsetPlacement placement)
  2751. {
  2752. if (elementAt(index))
  2753. mInsetPlacement[index] = placement;
  2754. else
  2755. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  2756. }
  2757. /*!
  2758. If the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned, this function
  2759. is used to set the alignment of the element with the specified \a index to \a alignment.
  2760. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
  2761. Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
  2762. alignment flags will be ignored.
  2763. */
  2764. void QCPLayoutInset::setInsetAlignment(int index, Qt::Alignment alignment)
  2765. {
  2766. if (elementAt(index))
  2767. mInsetAlignment[index] = alignment;
  2768. else
  2769. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  2770. }
  2771. /*!
  2772. If the inset placement (\ref setInsetPlacement) is \ref ipFree, this function is used to set the
  2773. position and size of the element with the specified \a index to \a rect.
  2774. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
  2775. will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
  2776. corner of the layout, with 35% width and height of the parent layout.
  2777. Note that the minimum and maximum sizes of the embedded element (\ref
  2778. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize) are enforced.
  2779. */
  2780. void QCPLayoutInset::setInsetRect(int index, const QRectF &rect)
  2781. {
  2782. if (elementAt(index))
  2783. mInsetRect[index] = rect;
  2784. else
  2785. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  2786. }
  2787. /* inherits documentation from base class */
  2788. void QCPLayoutInset::updateLayout()
  2789. {
  2790. for (int i=0; i<mElements.size(); ++i)
  2791. {
  2792. QRect insetRect;
  2793. QSize finalMinSize, finalMaxSize;
  2794. QSize minSizeHint = mElements.at(i)->minimumSizeHint();
  2795. QSize maxSizeHint = mElements.at(i)->maximumSizeHint();
  2796. finalMinSize.setWidth(mElements.at(i)->minimumSize().width() > 0 ? mElements.at(i)->minimumSize().width() : minSizeHint.width());
  2797. finalMinSize.setHeight(mElements.at(i)->minimumSize().height() > 0 ? mElements.at(i)->minimumSize().height() : minSizeHint.height());
  2798. finalMaxSize.setWidth(mElements.at(i)->maximumSize().width() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().width() : maxSizeHint.width());
  2799. finalMaxSize.setHeight(mElements.at(i)->maximumSize().height() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().height() : maxSizeHint.height());
  2800. if (mInsetPlacement.at(i) == ipFree)
  2801. {
  2802. insetRect = QRect(rect().x()+rect().width()*mInsetRect.at(i).x(),
  2803. rect().y()+rect().height()*mInsetRect.at(i).y(),
  2804. rect().width()*mInsetRect.at(i).width(),
  2805. rect().height()*mInsetRect.at(i).height());
  2806. if (insetRect.size().width() < finalMinSize.width())
  2807. insetRect.setWidth(finalMinSize.width());
  2808. if (insetRect.size().height() < finalMinSize.height())
  2809. insetRect.setHeight(finalMinSize.height());
  2810. if (insetRect.size().width() > finalMaxSize.width())
  2811. insetRect.setWidth(finalMaxSize.width());
  2812. if (insetRect.size().height() > finalMaxSize.height())
  2813. insetRect.setHeight(finalMaxSize.height());
  2814. } else if (mInsetPlacement.at(i) == ipBorderAligned)
  2815. {
  2816. insetRect.setSize(finalMinSize);
  2817. Qt::Alignment al = mInsetAlignment.at(i);
  2818. if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x());
  2819. else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width());
  2820. else insetRect.moveLeft(rect().x()+rect().width()*0.5-finalMinSize.width()*0.5); // default to Qt::AlignHCenter
  2821. if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y());
  2822. else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height());
  2823. else insetRect.moveTop(rect().y()+rect().height()*0.5-finalMinSize.height()*0.5); // default to Qt::AlignVCenter
  2824. }
  2825. mElements.at(i)->setOuterRect(insetRect);
  2826. }
  2827. }
  2828. /* inherits documentation from base class */
  2829. int QCPLayoutInset::elementCount() const
  2830. {
  2831. return mElements.size();
  2832. }
  2833. /* inherits documentation from base class */
  2834. QCPLayoutElement *QCPLayoutInset::elementAt(int index) const
  2835. {
  2836. if (index >= 0 && index < mElements.size())
  2837. return mElements.at(index);
  2838. else
  2839. return 0;
  2840. }
  2841. /* inherits documentation from base class */
  2842. QCPLayoutElement *QCPLayoutInset::takeAt(int index)
  2843. {
  2844. if (QCPLayoutElement *el = elementAt(index))
  2845. {
  2846. releaseElement(el);
  2847. mElements.removeAt(index);
  2848. mInsetPlacement.removeAt(index);
  2849. mInsetAlignment.removeAt(index);
  2850. mInsetRect.removeAt(index);
  2851. return el;
  2852. } else
  2853. {
  2854. qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
  2855. return 0;
  2856. }
  2857. }
  2858. /* inherits documentation from base class */
  2859. bool QCPLayoutInset::take(QCPLayoutElement *element)
  2860. {
  2861. if (element)
  2862. {
  2863. for (int i=0; i<elementCount(); ++i)
  2864. {
  2865. if (elementAt(i) == element)
  2866. {
  2867. takeAt(i);
  2868. return true;
  2869. }
  2870. }
  2871. qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
  2872. } else
  2873. qDebug() << Q_FUNC_INFO << "Can't take null element";
  2874. return false;
  2875. }
  2876. /*!
  2877. The inset layout is sensitive to events only at areas where its (visible) child elements are
  2878. sensitive. If the selectTest method of any of the child elements returns a positive number for \a
  2879. pos, this method returns a value corresponding to 0.99 times the parent plot's selection
  2880. tolerance. The inset layout is not selectable itself by default. So if \a onlySelectable is true,
  2881. -1.0 is returned.
  2882. See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
  2883. */
  2884. double QCPLayoutInset::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  2885. {
  2886. Q_UNUSED(details)
  2887. if (onlySelectable)
  2888. return -1;
  2889. for (int i=0; i<mElements.size(); ++i)
  2890. {
  2891. // inset layout shall only return positive selectTest, if actually an inset object is at pos
  2892. // else it would block the entire underlying QCPAxisRect with its surface.
  2893. if (mElements.at(i)->realVisibility() && mElements.at(i)->selectTest(pos, onlySelectable) >= 0)
  2894. return mParentPlot->selectionTolerance()*0.99;
  2895. }
  2896. return -1;
  2897. }
  2898. /*!
  2899. Adds the specified \a element to the layout as an inset aligned at the border (\ref
  2900. setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a
  2901. alignment.
  2902. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
  2903. Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
  2904. alignment flags will be ignored.
  2905. \see addElement(QCPLayoutElement *element, const QRectF &rect)
  2906. */
  2907. void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment)
  2908. {
  2909. if (element)
  2910. {
  2911. if (element->layout()) // remove from old layout first
  2912. element->layout()->take(element);
  2913. mElements.append(element);
  2914. mInsetPlacement.append(ipBorderAligned);
  2915. mInsetAlignment.append(alignment);
  2916. mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4));
  2917. adoptElement(element);
  2918. } else
  2919. qDebug() << Q_FUNC_INFO << "Can't add null element";
  2920. }
  2921. /*!
  2922. Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref
  2923. setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a
  2924. rect.
  2925. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
  2926. will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
  2927. corner of the layout, with 35% width and height of the parent layout.
  2928. \see addElement(QCPLayoutElement *element, Qt::Alignment alignment)
  2929. */
  2930. void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect)
  2931. {
  2932. if (element)
  2933. {
  2934. if (element->layout()) // remove from old layout first
  2935. element->layout()->take(element);
  2936. mElements.append(element);
  2937. mInsetPlacement.append(ipFree);
  2938. mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop);
  2939. mInsetRect.append(rect);
  2940. adoptElement(element);
  2941. } else
  2942. qDebug() << Q_FUNC_INFO << "Can't add null element";
  2943. }
  2944. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2945. //////////////////// QCPLineEnding
  2946. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2947. /*! \class QCPLineEnding
  2948. \brief Handles the different ending decorations for line-like items
  2949. \image html QCPLineEnding.png "The various ending styles currently supported"
  2950. For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine
  2951. has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail.
  2952. The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can
  2953. be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of
  2954. the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item.
  2955. For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite
  2956. directions, e.g. "outward". This can be changed by \ref setInverted, which would make the
  2957. respective arrow point inward.
  2958. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a
  2959. QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g. \code
  2960. myItemLine->setHead(QCPLineEnding::esSpikeArrow) \endcode
  2961. */
  2962. /*!
  2963. Creates a QCPLineEnding instance with default values (style \ref esNone).
  2964. */
  2965. QCPLineEnding::QCPLineEnding() :
  2966. mStyle(esNone),
  2967. mWidth(8),
  2968. mLength(10),
  2969. mInverted(false)
  2970. {
  2971. }
  2972. /*!
  2973. Creates a QCPLineEnding instance with the specified values.
  2974. */
  2975. QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) :
  2976. mStyle(style),
  2977. mWidth(width),
  2978. mLength(length),
  2979. mInverted(inverted)
  2980. {
  2981. }
  2982. /*!
  2983. Sets the style of the ending decoration.
  2984. */
  2985. void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style)
  2986. {
  2987. mStyle = style;
  2988. }
  2989. /*!
  2990. Sets the width of the ending decoration, if the style supports it. On arrows, for example, the
  2991. width defines the size perpendicular to the arrow's pointing direction.
  2992. \see setLength
  2993. */
  2994. void QCPLineEnding::setWidth(double width)
  2995. {
  2996. mWidth = width;
  2997. }
  2998. /*!
  2999. Sets the length of the ending decoration, if the style supports it. On arrows, for example, the
  3000. length defines the size in pointing direction.
  3001. \see setWidth
  3002. */
  3003. void QCPLineEnding::setLength(double length)
  3004. {
  3005. mLength = length;
  3006. }
  3007. /*!
  3008. Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point
  3009. inward when \a inverted is set to true.
  3010. Note that also the \a width direction is inverted. For symmetrical ending styles like arrows or
  3011. discs, this doesn't make a difference. However, asymmetric styles like \ref esHalfBar are
  3012. affected by it, which can be used to control to which side the half bar points to.
  3013. */
  3014. void QCPLineEnding::setInverted(bool inverted)
  3015. {
  3016. mInverted = inverted;
  3017. }
  3018. /*! \internal
  3019. Returns the maximum pixel radius the ending decoration might cover, starting from the position
  3020. the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item).
  3021. This is relevant for clipping. Only omit painting of the decoration when the position where the
  3022. decoration is supposed to be drawn is farther away from the clipping rect than the returned
  3023. distance.
  3024. */
  3025. double QCPLineEnding::boundingDistance() const
  3026. {
  3027. switch (mStyle)
  3028. {
  3029. case esNone:
  3030. return 0;
  3031. case esFlatArrow:
  3032. case esSpikeArrow:
  3033. case esLineArrow:
  3034. case esSkewedBar:
  3035. return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length
  3036. case esDisc:
  3037. case esSquare:
  3038. case esDiamond:
  3039. case esBar:
  3040. case esHalfBar:
  3041. return mWidth*1.42; // items that only have a width -> width*sqrt(2)
  3042. }
  3043. return 0;
  3044. }
  3045. /*!
  3046. Starting from the origin of this line ending (which is style specific), returns the length
  3047. covered by the line ending symbol, in backward direction.
  3048. For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if
  3049. both have the same \ref setLength value, because the spike arrow has an inward curved back, which
  3050. reduces the length along its center axis (the drawing origin for arrows is at the tip).
  3051. This function is used for precise, style specific placement of line endings, for example in
  3052. QCPAxes.
  3053. */
  3054. double QCPLineEnding::realLength() const
  3055. {
  3056. switch (mStyle)
  3057. {
  3058. case esNone:
  3059. case esLineArrow:
  3060. case esSkewedBar:
  3061. case esBar:
  3062. case esHalfBar:
  3063. return 0;
  3064. case esFlatArrow:
  3065. return mLength;
  3066. case esDisc:
  3067. case esSquare:
  3068. case esDiamond:
  3069. return mWidth*0.5;
  3070. case esSpikeArrow:
  3071. return mLength*0.8;
  3072. }
  3073. return 0;
  3074. }
  3075. /*! \internal
  3076. Draws the line ending with the specified \a painter at the position \a pos. The direction of the
  3077. line ending is controlled with \a dir.
  3078. */
  3079. void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const
  3080. {
  3081. if (mStyle == esNone)
  3082. return;
  3083. QVector2D lengthVec(dir.normalized());
  3084. if (lengthVec.isNull())
  3085. lengthVec = QVector2D(1, 0);
  3086. QVector2D widthVec(-lengthVec.y(), lengthVec.x());
  3087. lengthVec *= (float)(mLength*(mInverted ? -1 : 1));
  3088. widthVec *= (float)(mWidth*0.5*(mInverted ? -1 : 1));
  3089. QPen penBackup = painter->pen();
  3090. QBrush brushBackup = painter->brush();
  3091. QPen miterPen = penBackup;
  3092. miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey
  3093. QBrush brush(painter->pen().color(), Qt::SolidPattern);
  3094. switch (mStyle)
  3095. {
  3096. case esNone: break;
  3097. case esFlatArrow:
  3098. {
  3099. QPointF points[3] = {pos.toPointF(),
  3100. (pos-lengthVec+widthVec).toPointF(),
  3101. (pos-lengthVec-widthVec).toPointF()
  3102. };
  3103. painter->setPen(miterPen);
  3104. painter->setBrush(brush);
  3105. painter->drawConvexPolygon(points, 3);
  3106. painter->setBrush(brushBackup);
  3107. painter->setPen(penBackup);
  3108. break;
  3109. }
  3110. case esSpikeArrow:
  3111. {
  3112. QPointF points[4] = {pos.toPointF(),
  3113. (pos-lengthVec+widthVec).toPointF(),
  3114. (pos-lengthVec*0.8f).toPointF(),
  3115. (pos-lengthVec-widthVec).toPointF()
  3116. };
  3117. painter->setPen(miterPen);
  3118. painter->setBrush(brush);
  3119. painter->drawConvexPolygon(points, 4);
  3120. painter->setBrush(brushBackup);
  3121. painter->setPen(penBackup);
  3122. break;
  3123. }
  3124. case esLineArrow:
  3125. {
  3126. QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(),
  3127. pos.toPointF(),
  3128. (pos-lengthVec-widthVec).toPointF()
  3129. };
  3130. painter->setPen(miterPen);
  3131. painter->drawPolyline(points, 3);
  3132. painter->setPen(penBackup);
  3133. break;
  3134. }
  3135. case esDisc:
  3136. {
  3137. painter->setBrush(brush);
  3138. painter->drawEllipse(pos.toPointF(), mWidth*0.5, mWidth*0.5);
  3139. painter->setBrush(brushBackup);
  3140. break;
  3141. }
  3142. case esSquare:
  3143. {
  3144. QVector2D widthVecPerp(-widthVec.y(), widthVec.x());
  3145. QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(),
  3146. (pos-widthVecPerp-widthVec).toPointF(),
  3147. (pos+widthVecPerp-widthVec).toPointF(),
  3148. (pos+widthVecPerp+widthVec).toPointF()
  3149. };
  3150. painter->setPen(miterPen);
  3151. painter->setBrush(brush);
  3152. painter->drawConvexPolygon(points, 4);
  3153. painter->setBrush(brushBackup);
  3154. painter->setPen(penBackup);
  3155. break;
  3156. }
  3157. case esDiamond:
  3158. {
  3159. QVector2D widthVecPerp(-widthVec.y(), widthVec.x());
  3160. QPointF points[4] = {(pos-widthVecPerp).toPointF(),
  3161. (pos-widthVec).toPointF(),
  3162. (pos+widthVecPerp).toPointF(),
  3163. (pos+widthVec).toPointF()
  3164. };
  3165. painter->setPen(miterPen);
  3166. painter->setBrush(brush);
  3167. painter->drawConvexPolygon(points, 4);
  3168. painter->setBrush(brushBackup);
  3169. painter->setPen(penBackup);
  3170. break;
  3171. }
  3172. case esBar:
  3173. {
  3174. painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF());
  3175. break;
  3176. }
  3177. case esHalfBar:
  3178. {
  3179. painter->drawLine((pos+widthVec).toPointF(), pos.toPointF());
  3180. break;
  3181. }
  3182. case esSkewedBar:
  3183. {
  3184. if (qFuzzyIsNull(painter->pen().widthF()) && !painter->modes().testFlag(QCPPainter::pmNonCosmetic))
  3185. {
  3186. // if drawing with cosmetic pen (perfectly thin stroke, happens only in vector exports), draw bar exactly on tip of line
  3187. painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)).toPointF(),
  3188. (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)).toPointF());
  3189. } else
  3190. {
  3191. // if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly
  3192. painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF(),
  3193. (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF());
  3194. }
  3195. break;
  3196. }
  3197. }
  3198. }
  3199. /*! \internal
  3200. \overload
  3201. Draws the line ending. The direction is controlled with the \a angle parameter in radians.
  3202. */
  3203. void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, double angle) const
  3204. {
  3205. draw(painter, pos, QVector2D(qCos(angle), qSin(angle)));
  3206. }
  3207. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3208. //////////////////// QCPGrid
  3209. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3210. /*! \class QCPGrid
  3211. \brief Responsible for drawing the grid of a QCPAxis.
  3212. This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the
  3213. grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref
  3214. QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself.
  3215. The axis and grid drawing was split into two classes to allow them to be placed on different
  3216. layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid
  3217. in the background and the axes in the foreground, and any plottables/items in between. This
  3218. described situation is the default setup, see the QCPLayer documentation.
  3219. */
  3220. /*!
  3221. Creates a QCPGrid instance and sets default values.
  3222. You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid.
  3223. */
  3224. QCPGrid::QCPGrid(QCPAxis *parentAxis) :
  3225. QCPLayerable(parentAxis->parentPlot(), "", parentAxis),
  3226. mParentAxis(parentAxis)
  3227. {
  3228. // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called
  3229. setParent(parentAxis);
  3230. setPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
  3231. setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
  3232. setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine));
  3233. setSubGridVisible(false);
  3234. setAntialiased(false);
  3235. setAntialiasedSubGrid(false);
  3236. setAntialiasedZeroLine(false);
  3237. }
  3238. /*!
  3239. Sets whether grid lines at sub tick marks are drawn.
  3240. \see setSubGridPen
  3241. */
  3242. void QCPGrid::setSubGridVisible(bool visible)
  3243. {
  3244. mSubGridVisible = visible;
  3245. }
  3246. /*!
  3247. Sets whether sub grid lines are drawn antialiased.
  3248. */
  3249. void QCPGrid::setAntialiasedSubGrid(bool enabled)
  3250. {
  3251. mAntialiasedSubGrid = enabled;
  3252. }
  3253. /*!
  3254. Sets whether zero lines are drawn antialiased.
  3255. */
  3256. void QCPGrid::setAntialiasedZeroLine(bool enabled)
  3257. {
  3258. mAntialiasedZeroLine = enabled;
  3259. }
  3260. /*!
  3261. Sets the pen with which (major) grid lines are drawn.
  3262. */
  3263. void QCPGrid::setPen(const QPen &pen)
  3264. {
  3265. mPen = pen;
  3266. }
  3267. /*!
  3268. Sets the pen with which sub grid lines are drawn.
  3269. */
  3270. void QCPGrid::setSubGridPen(const QPen &pen)
  3271. {
  3272. mSubGridPen = pen;
  3273. }
  3274. /*!
  3275. Sets the pen with which zero lines are drawn.
  3276. Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid
  3277. lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen.
  3278. */
  3279. void QCPGrid::setZeroLinePen(const QPen &pen)
  3280. {
  3281. mZeroLinePen = pen;
  3282. }
  3283. /*! \internal
  3284. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  3285. before drawing the major grid lines.
  3286. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  3287. This function takes into account the local setting of the antialiasing flag as well as the
  3288. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  3289. QCustomPlot::setNotAntialiasedElements.
  3290. \see setAntialiased
  3291. */
  3292. void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const
  3293. {
  3294. applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid);
  3295. }
  3296. /*! \internal
  3297. Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning
  3298. over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen).
  3299. */
  3300. void QCPGrid::draw(QCPPainter *painter)
  3301. {
  3302. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  3303. if (mSubGridVisible)
  3304. drawSubGridLines(painter);
  3305. drawGridLines(painter);
  3306. }
  3307. /*! \internal
  3308. Draws the main grid lines and possibly a zero line with the specified painter.
  3309. This is a helper function called by \ref draw.
  3310. */
  3311. void QCPGrid::drawGridLines(QCPPainter *painter) const
  3312. {
  3313. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  3314. int lowTick = mParentAxis->mLowestVisibleTick;
  3315. int highTick = mParentAxis->mHighestVisibleTick;
  3316. double t; // helper variable, result of coordinate-to-pixel transforms
  3317. if (mParentAxis->orientation() == Qt::Horizontal)
  3318. {
  3319. // draw zeroline:
  3320. int zeroLineIndex = -1;
  3321. if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
  3322. {
  3323. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  3324. painter->setPen(mZeroLinePen);
  3325. double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero
  3326. for (int i=lowTick; i <= highTick; ++i)
  3327. {
  3328. if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
  3329. {
  3330. zeroLineIndex = i;
  3331. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
  3332. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  3333. break;
  3334. }
  3335. }
  3336. }
  3337. // draw grid lines:
  3338. applyDefaultAntialiasingHint(painter);
  3339. painter->setPen(mPen);
  3340. for (int i=lowTick; i <= highTick; ++i)
  3341. {
  3342. if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
  3343. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
  3344. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  3345. }
  3346. } else
  3347. {
  3348. // draw zeroline:
  3349. int zeroLineIndex = -1;
  3350. if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
  3351. {
  3352. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  3353. painter->setPen(mZeroLinePen);
  3354. double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero
  3355. for (int i=lowTick; i <= highTick; ++i)
  3356. {
  3357. if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
  3358. {
  3359. zeroLineIndex = i;
  3360. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
  3361. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  3362. break;
  3363. }
  3364. }
  3365. }
  3366. // draw grid lines:
  3367. applyDefaultAntialiasingHint(painter);
  3368. painter->setPen(mPen);
  3369. for (int i=lowTick; i <= highTick; ++i)
  3370. {
  3371. if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
  3372. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
  3373. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  3374. }
  3375. }
  3376. }
  3377. /*! \internal
  3378. Draws the sub grid lines with the specified painter.
  3379. This is a helper function called by \ref draw.
  3380. */
  3381. void QCPGrid::drawSubGridLines(QCPPainter *painter) const
  3382. {
  3383. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  3384. applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid);
  3385. double t; // helper variable, result of coordinate-to-pixel transforms
  3386. painter->setPen(mSubGridPen);
  3387. if (mParentAxis->orientation() == Qt::Horizontal)
  3388. {
  3389. for (int i=0; i<mParentAxis->mSubTickVector.size(); ++i)
  3390. {
  3391. t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // x
  3392. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  3393. }
  3394. } else
  3395. {
  3396. for (int i=0; i<mParentAxis->mSubTickVector.size(); ++i)
  3397. {
  3398. t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // y
  3399. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  3400. }
  3401. }
  3402. }
  3403. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3404. //////////////////// QCPAxis
  3405. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3406. /*! \class QCPAxis
  3407. \brief Manages a single axis inside a QCustomPlot.
  3408. Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via
  3409. QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and
  3410. QCustomPlot::yAxis2 (right).
  3411. Axes are always part of an axis rect, see QCPAxisRect.
  3412. \image html AxisNamesOverview.png
  3413. <center>Naming convention of axis parts</center>
  3414. \n
  3415. \image html AxisRectSpacingOverview.png
  3416. <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line
  3417. on the left represents the QCustomPlot widget border.</center>
  3418. */
  3419. /* start of documentation of inline functions */
  3420. /*! \fn Qt::Orientation QCPAxis::orientation() const
  3421. Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced
  3422. from the axis type (left, top, right or bottom).
  3423. \see orientation(AxisType type)
  3424. */
  3425. /*! \fn QCPGrid *QCPAxis::grid() const
  3426. Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the
  3427. grid is displayed.
  3428. */
  3429. /*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type)
  3430. Returns the orientation of the specified axis type
  3431. \see orientation()
  3432. */
  3433. /* end of documentation of inline functions */
  3434. /* start of documentation of signals */
  3435. /*! \fn void QCPAxis::ticksRequest()
  3436. This signal is emitted when \ref setAutoTicks is false and the axis is about to generate tick
  3437. labels for a replot.
  3438. Modifying the tick positions can be done with \ref setTickVector. If you also want to control the
  3439. tick labels, set \ref setAutoTickLabels to false and also provide the labels with \ref
  3440. setTickVectorLabels.
  3441. If you only want static ticks you probably don't need this signal, since you can just set the
  3442. tick vector (and possibly tick label vector) once. However, if you want to provide ticks (and
  3443. maybe labels) dynamically, e.g. depending on the current axis range, connect a slot to this
  3444. signal and set the vector/vectors there.
  3445. */
  3446. /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange)
  3447. This signal is emitted when the range of this axis has changed. You can connect it to the \ref
  3448. setRange slot of another axis to communicate the new range to the other axis, in order for it to
  3449. be synchronized.
  3450. */
  3451. /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange)
  3452. \overload
  3453. Additionally to the new range, this signal also provides the previous range held by the axis as
  3454. \a oldRange.
  3455. */
  3456. /*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType);
  3457. This signal is emitted when the scale type changes, by calls to \ref setScaleType
  3458. */
  3459. /*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection)
  3460. This signal is emitted when the selection state of this axis has changed, either by user interaction
  3461. or by a direct call to \ref setSelectedParts.
  3462. */
  3463. /*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts);
  3464. This signal is emitted when the selectability changes, by calls to \ref setSelectableParts
  3465. */
  3466. /* end of documentation of signals */
  3467. /*!
  3468. Constructs an Axis instance of Type \a type for the axis rect \a parent.
  3469. You shouldn't instantiate axes directly, rather use \ref QCPAxisRect::addAxis.
  3470. */
  3471. QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) :
  3472. QCPLayerable(parent->parentPlot(), "", parent),
  3473. // axis base:
  3474. mAxisType(type),
  3475. mAxisRect(parent),
  3476. mPadding(5),
  3477. mOrientation(orientation(type)),
  3478. mSelectableParts(spAxis | spTickLabels | spAxisLabel),
  3479. mSelectedParts(spNone),
  3480. mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  3481. mSelectedBasePen(QPen(Qt::blue, 2)),
  3482. // axis label:
  3483. mLabel(""),
  3484. mLabelFont(mParentPlot->font()),
  3485. mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
  3486. mLabelColor(Qt::black),
  3487. mSelectedLabelColor(Qt::blue),
  3488. // tick labels:
  3489. mTickLabels(true),
  3490. mAutoTickLabels(true),
  3491. mTickLabelType(ltNumber),
  3492. mTickLabelFont(mParentPlot->font()),
  3493. mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
  3494. mTickLabelColor(Qt::black),
  3495. mSelectedTickLabelColor(Qt::blue),
  3496. mDateTimeFormat("hh:mm:ss\ndd.MM.yy"),
  3497. mDateTimeSpec(Qt::LocalTime),
  3498. mNumberPrecision(6),
  3499. mNumberFormatChar('g'),
  3500. mNumberBeautifulPowers(true),
  3501. // ticks and subticks:
  3502. mTicks(true),
  3503. mTickStep(1),
  3504. mSubTickCount(4),
  3505. mAutoTickCount(6),
  3506. mAutoTicks(true),
  3507. mAutoTickStep(true),
  3508. mAutoSubTicks(true),
  3509. mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  3510. mSelectedTickPen(QPen(Qt::blue, 2)),
  3511. mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  3512. mSelectedSubTickPen(QPen(Qt::blue, 2)),
  3513. // scale and range:
  3514. mRange(0, 5),
  3515. mRangeReversed(false),
  3516. mScaleType(stLinear),
  3517. mScaleLogBase(10),
  3518. mScaleLogBaseLogInv(1.0/qLn(mScaleLogBase)),
  3519. // internal members:
  3520. mGrid(new QCPGrid(this)),
  3521. mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())),
  3522. mLowestVisibleTick(0),
  3523. mHighestVisibleTick(-1),
  3524. mCachedMarginValid(false),
  3525. mCachedMargin(0)
  3526. {
  3527. mGrid->setVisible(false);
  3528. setAntialiased(false);
  3529. 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
  3530. if (type == atTop)
  3531. {
  3532. setTickLabelPadding(3);
  3533. setLabelPadding(6);
  3534. } else if (type == atRight)
  3535. {
  3536. setTickLabelPadding(7);
  3537. setLabelPadding(12);
  3538. } else if (type == atBottom)
  3539. {
  3540. setTickLabelPadding(3);
  3541. setLabelPadding(3);
  3542. } else if (type == atLeft)
  3543. {
  3544. setTickLabelPadding(5);
  3545. setLabelPadding(10);
  3546. }
  3547. }
  3548. QCPAxis::~QCPAxis()
  3549. {
  3550. delete mAxisPainter;
  3551. }
  3552. /* No documentation as it is a property getter */
  3553. int QCPAxis::tickLabelPadding() const
  3554. {
  3555. return mAxisPainter->tickLabelPadding;
  3556. }
  3557. /* No documentation as it is a property getter */
  3558. double QCPAxis::tickLabelRotation() const
  3559. {
  3560. return mAxisPainter->tickLabelRotation;
  3561. }
  3562. /* No documentation as it is a property getter */
  3563. QString QCPAxis::numberFormat() const
  3564. {
  3565. QString result;
  3566. result.append(mNumberFormatChar);
  3567. if (mNumberBeautifulPowers)
  3568. {
  3569. result.append("b");
  3570. if (mAxisPainter->numberMultiplyCross)
  3571. result.append("c");
  3572. }
  3573. return result;
  3574. }
  3575. /* No documentation as it is a property getter */
  3576. int QCPAxis::tickLengthIn() const
  3577. {
  3578. return mAxisPainter->tickLengthIn;
  3579. }
  3580. /* No documentation as it is a property getter */
  3581. int QCPAxis::tickLengthOut() const
  3582. {
  3583. return mAxisPainter->tickLengthOut;
  3584. }
  3585. /* No documentation as it is a property getter */
  3586. int QCPAxis::subTickLengthIn() const
  3587. {
  3588. return mAxisPainter->subTickLengthIn;
  3589. }
  3590. /* No documentation as it is a property getter */
  3591. int QCPAxis::subTickLengthOut() const
  3592. {
  3593. return mAxisPainter->subTickLengthOut;
  3594. }
  3595. /* No documentation as it is a property getter */
  3596. int QCPAxis::labelPadding() const
  3597. {
  3598. return mAxisPainter->labelPadding;
  3599. }
  3600. /* No documentation as it is a property getter */
  3601. int QCPAxis::offset() const
  3602. {
  3603. return mAxisPainter->offset;
  3604. }
  3605. /* No documentation as it is a property getter */
  3606. QCPLineEnding QCPAxis::lowerEnding() const
  3607. {
  3608. return mAxisPainter->lowerEnding;
  3609. }
  3610. /* No documentation as it is a property getter */
  3611. QCPLineEnding QCPAxis::upperEnding() const
  3612. {
  3613. return mAxisPainter->upperEnding;
  3614. }
  3615. /*!
  3616. Sets whether the axis uses a linear scale or a logarithmic scale. If \a type is set to \ref
  3617. stLogarithmic, the logarithm base can be set with \ref setScaleLogBase. In logarithmic axis
  3618. scaling, major tick marks appear at all powers of the logarithm base. Properties like tick step
  3619. (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but less major
  3620. ticks, consider choosing a logarithm base of 100, 1000 or even higher.
  3621. If \a type is \ref stLogarithmic and the number format (\ref setNumberFormat) uses the 'b' option
  3622. (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10
  3623. [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]"
  3624. part). To only display the decimal power, set the number precision to zero with
  3625. \ref setNumberPrecision.
  3626. */
  3627. void QCPAxis::setScaleType(QCPAxis::ScaleType type)
  3628. {
  3629. if (mScaleType != type)
  3630. {
  3631. mScaleType = type;
  3632. if (mScaleType == stLogarithmic)
  3633. setRange(mRange.sanitizedForLogScale());
  3634. mCachedMarginValid = false;
  3635. emit scaleTypeChanged(mScaleType);
  3636. }
  3637. }
  3638. /*!
  3639. If \ref setScaleType is set to \ref stLogarithmic, \a base will be the logarithm base of the
  3640. scaling. In logarithmic axis scaling, major tick marks appear at all powers of \a base.
  3641. Properties like tick step (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but
  3642. less major ticks, consider choosing \a base 100, 1000 or even higher.
  3643. */
  3644. void QCPAxis::setScaleLogBase(double base)
  3645. {
  3646. if (base > 1)
  3647. {
  3648. mScaleLogBase = base;
  3649. mScaleLogBaseLogInv = 1.0/qLn(mScaleLogBase); // buffer for faster baseLog() calculation
  3650. mCachedMarginValid = false;
  3651. } else
  3652. qDebug() << Q_FUNC_INFO << "Invalid logarithmic scale base (must be greater 1):" << base;
  3653. }
  3654. /*!
  3655. Sets the range of the axis.
  3656. This slot may be connected with the \ref rangeChanged signal of another axis so this axis
  3657. is always synchronized with the other axis range, when it changes.
  3658. To invert the direction of an axis, use \ref setRangeReversed.
  3659. */
  3660. void QCPAxis::setRange(const QCPRange &range)
  3661. {
  3662. if (range.lower == mRange.lower && range.upper == mRange.upper)
  3663. return;
  3664. if (!QCPRange::validRange(range)) return;
  3665. QCPRange oldRange = mRange;
  3666. if (mScaleType == stLogarithmic)
  3667. {
  3668. mRange = range.sanitizedForLogScale();
  3669. } else
  3670. {
  3671. mRange = range.sanitizedForLinScale();
  3672. }
  3673. mCachedMarginValid = false;
  3674. emit rangeChanged(mRange);
  3675. emit rangeChanged(mRange, oldRange);
  3676. }
  3677. /*!
  3678. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  3679. (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
  3680. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  3681. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  3682. directly.
  3683. \see SelectablePart, setSelectedParts
  3684. */
  3685. void QCPAxis::setSelectableParts(const SelectableParts &selectable)
  3686. {
  3687. if (mSelectableParts != selectable)
  3688. {
  3689. mSelectableParts = selectable;
  3690. emit selectableChanged(mSelectableParts);
  3691. }
  3692. }
  3693. /*!
  3694. Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
  3695. is selected, it uses a different pen/font.
  3696. The entire selection mechanism for axes is handled automatically when \ref
  3697. QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
  3698. wish to change the selection state manually.
  3699. This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
  3700. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  3701. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
  3702. setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
  3703. */
  3704. void QCPAxis::setSelectedParts(const SelectableParts &selected)
  3705. {
  3706. if (mSelectedParts != selected)
  3707. {
  3708. mSelectedParts = selected;
  3709. emit selectionChanged(mSelectedParts);
  3710. }
  3711. }
  3712. /*!
  3713. \overload
  3714. Sets the lower and upper bound of the axis range.
  3715. To invert the direction of an axis, use \ref setRangeReversed.
  3716. There is also a slot to set a range, see \ref setRange(const QCPRange &range).
  3717. */
  3718. void QCPAxis::setRange(double lower, double upper)
  3719. {
  3720. if (lower == mRange.lower && upper == mRange.upper)
  3721. return;
  3722. if (!QCPRange::validRange(lower, upper)) return;
  3723. QCPRange oldRange = mRange;
  3724. mRange.lower = lower;
  3725. mRange.upper = upper;
  3726. if (mScaleType == stLogarithmic)
  3727. {
  3728. mRange = mRange.sanitizedForLogScale();
  3729. } else
  3730. {
  3731. mRange = mRange.sanitizedForLinScale();
  3732. }
  3733. mCachedMarginValid = false;
  3734. emit rangeChanged(mRange);
  3735. emit rangeChanged(mRange, oldRange);
  3736. }
  3737. /*!
  3738. \overload
  3739. Sets the range of the axis.
  3740. The \a position coordinate indicates together with the \a alignment parameter, where the new
  3741. range will be positioned. \a size defines the size of the new axis range. \a alignment may be
  3742. Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
  3743. or center of the range to be aligned with \a position. Any other values of \a alignment will
  3744. default to Qt::AlignCenter.
  3745. */
  3746. void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment)
  3747. {
  3748. if (alignment == Qt::AlignLeft)
  3749. setRange(position, position+size);
  3750. else if (alignment == Qt::AlignRight)
  3751. setRange(position-size, position);
  3752. else // alignment == Qt::AlignCenter
  3753. setRange(position-size/2.0, position+size/2.0);
  3754. }
  3755. /*!
  3756. Sets the lower bound of the axis range. The upper bound is not changed.
  3757. \see setRange
  3758. */
  3759. void QCPAxis::setRangeLower(double lower)
  3760. {
  3761. if (mRange.lower == lower)
  3762. return;
  3763. QCPRange oldRange = mRange;
  3764. mRange.lower = lower;
  3765. if (mScaleType == stLogarithmic)
  3766. {
  3767. mRange = mRange.sanitizedForLogScale();
  3768. } else
  3769. {
  3770. mRange = mRange.sanitizedForLinScale();
  3771. }
  3772. mCachedMarginValid = false;
  3773. emit rangeChanged(mRange);
  3774. emit rangeChanged(mRange, oldRange);
  3775. }
  3776. /*!
  3777. Sets the upper bound of the axis range. The lower bound is not changed.
  3778. \see setRange
  3779. */
  3780. void QCPAxis::setRangeUpper(double upper)
  3781. {
  3782. if (mRange.upper == upper)
  3783. return;
  3784. QCPRange oldRange = mRange;
  3785. mRange.upper = upper;
  3786. if (mScaleType == stLogarithmic)
  3787. {
  3788. mRange = mRange.sanitizedForLogScale();
  3789. } else
  3790. {
  3791. mRange = mRange.sanitizedForLinScale();
  3792. }
  3793. mCachedMarginValid = false;
  3794. emit rangeChanged(mRange);
  3795. emit rangeChanged(mRange, oldRange);
  3796. }
  3797. /*!
  3798. Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
  3799. axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
  3800. direction of increasing values is inverted.
  3801. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
  3802. of the \ref setRange interface will still reference the mathematically smaller number than the \a
  3803. upper part.
  3804. */
  3805. void QCPAxis::setRangeReversed(bool reversed)
  3806. {
  3807. if (mRangeReversed != reversed)
  3808. {
  3809. mRangeReversed = reversed;
  3810. mCachedMarginValid = false;
  3811. }
  3812. }
  3813. /*!
  3814. Sets whether the tick positions should be calculated automatically (either from an automatically
  3815. generated tick step or a tick step provided manually via \ref setTickStep, see \ref setAutoTickStep).
  3816. If \a on is set to false, you must provide the tick positions manually via \ref setTickVector.
  3817. For these manual ticks you may let QCPAxis generate the appropriate labels automatically by
  3818. leaving \ref setAutoTickLabels set to true. If you also wish to control the displayed labels
  3819. manually, set \ref setAutoTickLabels to false and provide the label strings with \ref
  3820. setTickVectorLabels.
  3821. If you need dynamically calculated tick vectors (and possibly tick label vectors), set the
  3822. vectors in a slot connected to the \ref ticksRequest signal.
  3823. \see setAutoTickLabels, setAutoSubTicks, setAutoTickCount, setAutoTickStep
  3824. */
  3825. void QCPAxis::setAutoTicks(bool on)
  3826. {
  3827. if (mAutoTicks != on)
  3828. {
  3829. mAutoTicks = on;
  3830. mCachedMarginValid = false;
  3831. }
  3832. }
  3833. /*!
  3834. When \ref setAutoTickStep is true, \a approximateCount determines how many ticks should be
  3835. generated in the visible range, approximately.
  3836. It's not guaranteed that this number of ticks is met exactly, but approximately within a
  3837. tolerance of about two.
  3838. Only values greater than zero are accepted as \a approximateCount.
  3839. \see setAutoTickStep, setAutoTicks, setAutoSubTicks
  3840. */
  3841. void QCPAxis::setAutoTickCount(int approximateCount)
  3842. {
  3843. if (mAutoTickCount != approximateCount)
  3844. {
  3845. if (approximateCount > 0)
  3846. {
  3847. mAutoTickCount = approximateCount;
  3848. mCachedMarginValid = false;
  3849. } else
  3850. qDebug() << Q_FUNC_INFO << "approximateCount must be greater than zero:" << approximateCount;
  3851. }
  3852. }
  3853. /*!
  3854. Sets whether the tick labels are generated automatically. Depending on the tick label type (\ref
  3855. ltNumber or \ref ltDateTime), the labels will either show the coordinate as floating point
  3856. number (\ref setNumberFormat), or a date/time formatted according to \ref setDateTimeFormat.
  3857. If \a on is set to false, you should provide the tick labels via \ref setTickVectorLabels. This
  3858. is usually used in a combination with \ref setAutoTicks set to false for complete control over
  3859. tick positions and labels, e.g. when the ticks should be at multiples of pi and show "2pi", "3pi"
  3860. etc. as tick labels.
  3861. If you need dynamically calculated tick vectors (and possibly tick label vectors), set the
  3862. vectors in a slot connected to the \ref ticksRequest signal.
  3863. \see setAutoTicks
  3864. */
  3865. void QCPAxis::setAutoTickLabels(bool on)
  3866. {
  3867. if (mAutoTickLabels != on)
  3868. {
  3869. mAutoTickLabels = on;
  3870. mCachedMarginValid = false;
  3871. }
  3872. }
  3873. /*!
  3874. Sets whether the tick step, i.e. the interval between two (major) ticks, is calculated
  3875. automatically. If \a on is set to true, the axis finds a tick step that is reasonable for human
  3876. readable plots.
  3877. The number of ticks the algorithm aims for within the visible range can be specified with \ref
  3878. setAutoTickCount.
  3879. If \a on is set to false, you may set the tick step manually with \ref setTickStep.
  3880. \see setAutoTicks, setAutoSubTicks, setAutoTickCount
  3881. */
  3882. void QCPAxis::setAutoTickStep(bool on)
  3883. {
  3884. if (mAutoTickStep != on)
  3885. {
  3886. mAutoTickStep = on;
  3887. mCachedMarginValid = false;
  3888. }
  3889. }
  3890. /*!
  3891. Sets whether the number of sub ticks in one tick interval is determined automatically. This
  3892. works, as long as the tick step mantissa is a multiple of 0.5. When \ref setAutoTickStep is
  3893. enabled, this is always the case.
  3894. When \a on is set to false, you may set the sub tick count with \ref setSubTickCount manually.
  3895. \see setAutoTickCount, setAutoTicks, setAutoTickStep
  3896. */
  3897. void QCPAxis::setAutoSubTicks(bool on)
  3898. {
  3899. if (mAutoSubTicks != on)
  3900. {
  3901. mAutoSubTicks = on;
  3902. mCachedMarginValid = false;
  3903. }
  3904. }
  3905. /*!
  3906. Sets whether tick marks are displayed.
  3907. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
  3908. that, see \ref setTickLabels.
  3909. */
  3910. void QCPAxis::setTicks(bool show)
  3911. {
  3912. if (mTicks != show)
  3913. {
  3914. mTicks = show;
  3915. mCachedMarginValid = false;
  3916. }
  3917. }
  3918. /*!
  3919. Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
  3920. */
  3921. void QCPAxis::setTickLabels(bool show)
  3922. {
  3923. if (mTickLabels != show)
  3924. {
  3925. mTickLabels = show;
  3926. mCachedMarginValid = false;
  3927. }
  3928. }
  3929. /*!
  3930. Sets the distance between the axis base line (including any outward ticks) and the tick labels.
  3931. \see setLabelPadding, setPadding
  3932. */
  3933. void QCPAxis::setTickLabelPadding(int padding)
  3934. {
  3935. if (mAxisPainter->tickLabelPadding != padding)
  3936. {
  3937. mAxisPainter->tickLabelPadding = padding;
  3938. mCachedMarginValid = false;
  3939. }
  3940. }
  3941. /*!
  3942. Sets whether the tick labels display numbers or dates/times.
  3943. If \a type is set to \ref ltNumber, the format specifications of \ref setNumberFormat apply.
  3944. If \a type is set to \ref ltDateTime, the format specifications of \ref setDateTimeFormat apply.
  3945. In QCustomPlot, date/time coordinates are <tt>double</tt> numbers representing the seconds since
  3946. 1970-01-01T00:00:00 UTC. This format can be retrieved from QDateTime objects with the
  3947. QDateTime::toTime_t() function. Since this only gives a resolution of one second, there is also
  3948. the QDateTime::toMSecsSinceEpoch() function which returns the timespan described above in
  3949. milliseconds. Divide its return value by 1000.0 to get a value with the format needed for
  3950. date/time plotting, with a resolution of one millisecond.
  3951. Using the toMSecsSinceEpoch function allows dates that go back to 2nd January 4713 B.C.
  3952. (represented by a negative number), unlike the toTime_t function, which works with unsigned
  3953. integers and thus only goes back to 1st January 1970. So both for range and accuracy, use of
  3954. toMSecsSinceEpoch()/1000.0 should be preferred as key coordinate for date/time axes.
  3955. \see setTickLabels
  3956. */
  3957. void QCPAxis::setTickLabelType(LabelType type)
  3958. {
  3959. if (mTickLabelType != type)
  3960. {
  3961. mTickLabelType = type;
  3962. mCachedMarginValid = false;
  3963. }
  3964. }
  3965. /*!
  3966. Sets the font of the tick labels.
  3967. \see setTickLabels, setTickLabelColor
  3968. */
  3969. void QCPAxis::setTickLabelFont(const QFont &font)
  3970. {
  3971. if (font != mTickLabelFont)
  3972. {
  3973. mTickLabelFont = font;
  3974. mCachedMarginValid = false;
  3975. }
  3976. }
  3977. /*!
  3978. Sets the color of the tick labels.
  3979. \see setTickLabels, setTickLabelFont
  3980. */
  3981. void QCPAxis::setTickLabelColor(const QColor &color)
  3982. {
  3983. if (color != mTickLabelColor)
  3984. {
  3985. mTickLabelColor = color;
  3986. mCachedMarginValid = false;
  3987. }
  3988. }
  3989. /*!
  3990. Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
  3991. the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
  3992. from -90 to 90 degrees.
  3993. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
  3994. other angles, the label is drawn with an offset such that it seems to point toward or away from
  3995. the tick mark.
  3996. */
  3997. void QCPAxis::setTickLabelRotation(double degrees)
  3998. {
  3999. if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation))
  4000. {
  4001. mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0);
  4002. mCachedMarginValid = false;
  4003. }
  4004. }
  4005. /*!
  4006. Sets the format in which dates and times are displayed as tick labels, if \ref setTickLabelType is \ref ltDateTime.
  4007. for details about the \a format string, see the documentation of QDateTime::toString().
  4008. Newlines can be inserted with "\n".
  4009. \see setDateTimeSpec
  4010. */
  4011. void QCPAxis::setDateTimeFormat(const QString &format)
  4012. {
  4013. if (mDateTimeFormat != format)
  4014. {
  4015. mDateTimeFormat = format;
  4016. mCachedMarginValid = false;
  4017. }
  4018. }
  4019. /*!
  4020. Sets the time spec that is used for the date time values when \ref setTickLabelType is \ref
  4021. ltDateTime.
  4022. The default value of QDateTime objects (and also QCustomPlot) is <tt>Qt::LocalTime</tt>. However,
  4023. if the date time values passed to QCustomPlot are given in the UTC spec, set \a
  4024. timeSpec to <tt>Qt::UTC</tt> to get the correct axis labels.
  4025. \see setDateTimeFormat
  4026. */
  4027. void QCPAxis::setDateTimeSpec(const Qt::TimeSpec &timeSpec)
  4028. {
  4029. mDateTimeSpec = timeSpec;
  4030. }
  4031. /*!
  4032. Sets the number format for the numbers drawn as tick labels (if tick label type is \ref
  4033. ltNumber). This \a formatCode is an extended version of the format code used e.g. by
  4034. QString::number() and QLocale::toString(). For reference about that, see the "Argument Formats"
  4035. section in the detailed description of the QString class. \a formatCode is a string of one, two
  4036. or three characters. The first character is identical to the normal format code used by Qt. In
  4037. short, this means: 'e'/'E' scientific format, 'f' fixed format, 'g'/'G' scientific or fixed,
  4038. whichever is shorter.
  4039. The second and third characters are optional and specific to QCustomPlot:\n
  4040. If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
  4041. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for
  4042. "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
  4043. [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
  4044. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
  4045. be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
  4046. cross and 183 (0xB7) for the dot.
  4047. If the scale type (\ref setScaleType) is \ref stLogarithmic and the \a formatCode uses the 'b'
  4048. option (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10
  4049. [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]"
  4050. part). To only display the decimal power, set the number precision to zero with \ref
  4051. setNumberPrecision.
  4052. Examples for \a formatCode:
  4053. \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
  4054. normal scientific format is used
  4055. \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
  4056. beautifully typeset decimal powers and a dot as multiplication sign
  4057. \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
  4058. multiplication sign
  4059. \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
  4060. powers. Format code will be reduced to 'f'.
  4061. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
  4062. code will not be changed.
  4063. */
  4064. void QCPAxis::setNumberFormat(const QString &formatCode)
  4065. {
  4066. if (formatCode.isEmpty())
  4067. {
  4068. qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
  4069. return;
  4070. }
  4071. mCachedMarginValid = false;
  4072. // interpret first char as number format char:
  4073. QString allowedFormatChars = "eEfgG";
  4074. if (allowedFormatChars.contains(formatCode.at(0)))
  4075. {
  4076. mNumberFormatChar = formatCode.at(0).toLatin1();
  4077. } else
  4078. {
  4079. qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
  4080. return;
  4081. }
  4082. if (formatCode.length() < 2)
  4083. {
  4084. mNumberBeautifulPowers = false;
  4085. mAxisPainter->numberMultiplyCross = false;
  4086. return;
  4087. }
  4088. // interpret second char as indicator for beautiful decimal powers:
  4089. if (formatCode.at(1) == 'b' && (mNumberFormatChar == 'e' || mNumberFormatChar == 'g'))
  4090. {
  4091. mNumberBeautifulPowers = true;
  4092. } else
  4093. {
  4094. qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
  4095. return;
  4096. }
  4097. if (formatCode.length() < 3)
  4098. {
  4099. mAxisPainter->numberMultiplyCross = false;
  4100. return;
  4101. }
  4102. // interpret third char as indicator for dot or cross multiplication symbol:
  4103. if (formatCode.at(2) == 'c')
  4104. {
  4105. mAxisPainter->numberMultiplyCross = true;
  4106. } else if (formatCode.at(2) == 'd')
  4107. {
  4108. mAxisPainter->numberMultiplyCross = false;
  4109. } else
  4110. {
  4111. qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
  4112. return;
  4113. }
  4114. }
  4115. /*!
  4116. Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
  4117. for details. The effect of precisions are most notably for number Formats starting with 'e', see
  4118. \ref setNumberFormat
  4119. If the scale type (\ref setScaleType) is \ref stLogarithmic and the number format (\ref
  4120. setNumberFormat) uses the 'b' format code (beautifully typeset decimal powers), the display
  4121. usually is "1 [multiplication sign] 10 [superscript] n", which looks unnatural for logarithmic
  4122. scaling (the redundant "1 [multiplication sign]" part). To only display the decimal power "10
  4123. [superscript] n", set \a precision to zero.
  4124. */
  4125. void QCPAxis::setNumberPrecision(int precision)
  4126. {
  4127. if (mNumberPrecision != precision)
  4128. {
  4129. mNumberPrecision = precision;
  4130. mCachedMarginValid = false;
  4131. }
  4132. }
  4133. /*!
  4134. If \ref setAutoTickStep is set to false, use this function to set the tick step manually.
  4135. The tick step is the interval between (major) ticks, in plot coordinates.
  4136. \see setSubTickCount
  4137. */
  4138. void QCPAxis::setTickStep(double step)
  4139. {
  4140. if (mTickStep != step)
  4141. {
  4142. mTickStep = step;
  4143. mCachedMarginValid = false;
  4144. }
  4145. }
  4146. /*!
  4147. If you want full control over what ticks (and possibly labels) the axes show, this function is
  4148. used to set the coordinates at which ticks will appear.\ref setAutoTicks must be disabled, else
  4149. the provided tick vector will be overwritten with automatically generated tick coordinates upon
  4150. replot. The labels of the ticks can be generated automatically when \ref setAutoTickLabels is
  4151. left enabled. If it is disabled, you can set the labels manually with \ref setTickVectorLabels.
  4152. \a vec is a vector containing the positions of the ticks, in plot coordinates.
  4153. \warning \a vec must be sorted in ascending order, no additional checks are made to ensure this.
  4154. \see setTickVectorLabels
  4155. */
  4156. void QCPAxis::setTickVector(const QVector<double> &vec)
  4157. {
  4158. // don't check whether mTickVector != vec here, because it takes longer than we would save
  4159. mTickVector = vec;
  4160. mCachedMarginValid = false;
  4161. }
  4162. /*!
  4163. If you want full control over what ticks and labels the axes show, this function is used to set a
  4164. number of QStrings that will be displayed at the tick positions which you need to provide with
  4165. \ref setTickVector. These two vectors should have the same size. (Note that you need to disable
  4166. \ref setAutoTicks and \ref setAutoTickLabels first.)
  4167. \a vec is a vector containing the labels of the ticks. The entries correspond to the respective
  4168. indices in the tick vector, passed via \ref setTickVector.
  4169. \see setTickVector
  4170. */
  4171. void QCPAxis::setTickVectorLabels(const QVector<QString> &vec)
  4172. {
  4173. // don't check whether mTickVectorLabels != vec here, because it takes longer than we would save
  4174. mTickVectorLabels = vec;
  4175. mCachedMarginValid = false;
  4176. }
  4177. /*!
  4178. Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
  4179. plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
  4180. zero, the tick labels and axis label will increase their distance to the axis accordingly, so
  4181. they won't collide with the ticks.
  4182. \see setSubTickLength, setTickLengthIn, setTickLengthOut
  4183. */
  4184. void QCPAxis::setTickLength(int inside, int outside)
  4185. {
  4186. setTickLengthIn(inside);
  4187. setTickLengthOut(outside);
  4188. }
  4189. /*!
  4190. Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
  4191. inside the plot.
  4192. \see setTickLengthOut, setTickLength, setSubTickLength
  4193. */
  4194. void QCPAxis::setTickLengthIn(int inside)
  4195. {
  4196. if (mAxisPainter->tickLengthIn != inside)
  4197. {
  4198. mAxisPainter->tickLengthIn = inside;
  4199. }
  4200. }
  4201. /*!
  4202. Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
  4203. outside the plot. If \a outside is greater than zero, the tick labels and axis label will
  4204. increase their distance to the axis accordingly, so they won't collide with the ticks.
  4205. \see setTickLengthIn, setTickLength, setSubTickLength
  4206. */
  4207. void QCPAxis::setTickLengthOut(int outside)
  4208. {
  4209. if (mAxisPainter->tickLengthOut != outside)
  4210. {
  4211. mAxisPainter->tickLengthOut = outside;
  4212. mCachedMarginValid = false; // only outside tick length can change margin
  4213. }
  4214. }
  4215. /*!
  4216. Sets the number of sub ticks in one (major) tick step. A sub tick count of three for example,
  4217. divides the tick intervals in four sub intervals.
  4218. By default, the number of sub ticks is chosen automatically in a reasonable manner as long as the
  4219. mantissa of the tick step is a multiple of 0.5. When \ref setAutoTickStep is enabled, this is
  4220. always the case.
  4221. If you want to disable automatic sub tick count and use this function to set the count manually,
  4222. see \ref setAutoSubTicks.
  4223. */
  4224. void QCPAxis::setSubTickCount(int count)
  4225. {
  4226. mSubTickCount = count;
  4227. }
  4228. /*!
  4229. Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
  4230. the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
  4231. than zero, the tick labels and axis label will increase their distance to the axis accordingly,
  4232. so they won't collide with the ticks.
  4233. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
  4234. */
  4235. void QCPAxis::setSubTickLength(int inside, int outside)
  4236. {
  4237. setSubTickLengthIn(inside);
  4238. setSubTickLengthOut(outside);
  4239. }
  4240. /*!
  4241. Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
  4242. the plot.
  4243. \see setSubTickLengthOut, setSubTickLength, setTickLength
  4244. */
  4245. void QCPAxis::setSubTickLengthIn(int inside)
  4246. {
  4247. if (mAxisPainter->subTickLengthIn != inside)
  4248. {
  4249. mAxisPainter->subTickLengthIn = inside;
  4250. }
  4251. }
  4252. /*!
  4253. Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
  4254. outside the plot. If \a outside is greater than zero, the tick labels will increase their
  4255. distance to the axis accordingly, so they won't collide with the ticks.
  4256. \see setSubTickLengthIn, setSubTickLength, setTickLength
  4257. */
  4258. void QCPAxis::setSubTickLengthOut(int outside)
  4259. {
  4260. if (mAxisPainter->subTickLengthOut != outside)
  4261. {
  4262. mAxisPainter->subTickLengthOut = outside;
  4263. mCachedMarginValid = false; // only outside tick length can change margin
  4264. }
  4265. }
  4266. /*!
  4267. Sets the pen, the axis base line is drawn with.
  4268. \see setTickPen, setSubTickPen
  4269. */
  4270. void QCPAxis::setBasePen(const QPen &pen)
  4271. {
  4272. mBasePen = pen;
  4273. }
  4274. /*!
  4275. Sets the pen, tick marks will be drawn with.
  4276. \see setTickLength, setBasePen
  4277. */
  4278. void QCPAxis::setTickPen(const QPen &pen)
  4279. {
  4280. mTickPen = pen;
  4281. }
  4282. /*!
  4283. Sets the pen, subtick marks will be drawn with.
  4284. \see setSubTickCount, setSubTickLength, setBasePen
  4285. */
  4286. void QCPAxis::setSubTickPen(const QPen &pen)
  4287. {
  4288. mSubTickPen = pen;
  4289. }
  4290. /*!
  4291. Sets the font of the axis label.
  4292. \see setLabelColor
  4293. */
  4294. void QCPAxis::setLabelFont(const QFont &font)
  4295. {
  4296. if (mLabelFont != font)
  4297. {
  4298. mLabelFont = font;
  4299. mCachedMarginValid = false;
  4300. }
  4301. }
  4302. /*!
  4303. Sets the color of the axis label.
  4304. \see setLabelFont
  4305. */
  4306. void QCPAxis::setLabelColor(const QColor &color)
  4307. {
  4308. mLabelColor = color;
  4309. }
  4310. /*!
  4311. Sets the text of the axis label that will be shown below/above or next to the axis, depending on
  4312. its orientation. To disable axis labels, pass an empty string as \a str.
  4313. */
  4314. void QCPAxis::setLabel(const QString &str)
  4315. {
  4316. if (mLabel != str)
  4317. {
  4318. mLabel = str;
  4319. mCachedMarginValid = false;
  4320. }
  4321. }
  4322. /*!
  4323. Sets the distance between the tick labels and the axis label.
  4324. \see setTickLabelPadding, setPadding
  4325. */
  4326. void QCPAxis::setLabelPadding(int padding)
  4327. {
  4328. if (mAxisPainter->labelPadding != padding)
  4329. {
  4330. mAxisPainter->labelPadding = padding;
  4331. mCachedMarginValid = false;
  4332. }
  4333. }
  4334. /*!
  4335. Sets the padding of the axis.
  4336. When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space,
  4337. that is left blank.
  4338. The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled.
  4339. \see setLabelPadding, setTickLabelPadding
  4340. */
  4341. void QCPAxis::setPadding(int padding)
  4342. {
  4343. if (mPadding != padding)
  4344. {
  4345. mPadding = padding;
  4346. mCachedMarginValid = false;
  4347. }
  4348. }
  4349. /*!
  4350. Sets the offset the axis has to its axis rect side.
  4351. If an axis rect side has multiple axes and automatic margin calculation is enabled for that side,
  4352. only the offset of the inner most axis has meaning (even if it is set to be invisible). The
  4353. offset of the other, outer axes is controlled automatically, to place them at appropriate
  4354. positions.
  4355. */
  4356. void QCPAxis::setOffset(int offset)
  4357. {
  4358. mAxisPainter->offset = offset;
  4359. }
  4360. /*!
  4361. Sets the font that is used for tick labels when they are selected.
  4362. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4363. */
  4364. void QCPAxis::setSelectedTickLabelFont(const QFont &font)
  4365. {
  4366. if (font != mSelectedTickLabelFont)
  4367. {
  4368. mSelectedTickLabelFont = font;
  4369. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  4370. }
  4371. }
  4372. /*!
  4373. Sets the font that is used for the axis label when it is selected.
  4374. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4375. */
  4376. void QCPAxis::setSelectedLabelFont(const QFont &font)
  4377. {
  4378. mSelectedLabelFont = font;
  4379. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  4380. }
  4381. /*!
  4382. Sets the color that is used for tick labels when they are selected.
  4383. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4384. */
  4385. void QCPAxis::setSelectedTickLabelColor(const QColor &color)
  4386. {
  4387. if (color != mSelectedTickLabelColor)
  4388. {
  4389. mSelectedTickLabelColor = color;
  4390. }
  4391. }
  4392. /*!
  4393. Sets the color that is used for the axis label when it is selected.
  4394. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4395. */
  4396. void QCPAxis::setSelectedLabelColor(const QColor &color)
  4397. {
  4398. mSelectedLabelColor = color;
  4399. }
  4400. /*!
  4401. Sets the pen that is used to draw the axis base line when selected.
  4402. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4403. */
  4404. void QCPAxis::setSelectedBasePen(const QPen &pen)
  4405. {
  4406. mSelectedBasePen = pen;
  4407. }
  4408. /*!
  4409. Sets the pen that is used to draw the (major) ticks when selected.
  4410. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4411. */
  4412. void QCPAxis::setSelectedTickPen(const QPen &pen)
  4413. {
  4414. mSelectedTickPen = pen;
  4415. }
  4416. /*!
  4417. Sets the pen that is used to draw the subticks when selected.
  4418. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4419. */
  4420. void QCPAxis::setSelectedSubTickPen(const QPen &pen)
  4421. {
  4422. mSelectedSubTickPen = pen;
  4423. }
  4424. /*!
  4425. Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available
  4426. styles.
  4427. For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending.
  4428. Note that this meaning does not change when the axis range is reversed with \ref
  4429. setRangeReversed.
  4430. \see setUpperEnding
  4431. */
  4432. void QCPAxis::setLowerEnding(const QCPLineEnding &ending)
  4433. {
  4434. mAxisPainter->lowerEnding = ending;
  4435. }
  4436. /*!
  4437. Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available
  4438. styles.
  4439. For horizontal axes, this method refers to the right ending, for vertical axes the top ending.
  4440. Note that this meaning does not change when the axis range is reversed with \ref
  4441. setRangeReversed.
  4442. \see setLowerEnding
  4443. */
  4444. void QCPAxis::setUpperEnding(const QCPLineEnding &ending)
  4445. {
  4446. mAxisPainter->upperEnding = ending;
  4447. }
  4448. /*!
  4449. If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
  4450. bounds of the range. The range is simply moved by \a diff.
  4451. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
  4452. corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
  4453. */
  4454. void QCPAxis::moveRange(double diff)
  4455. {
  4456. QCPRange oldRange = mRange;
  4457. if (mScaleType == stLinear)
  4458. {
  4459. mRange.lower += diff;
  4460. mRange.upper += diff;
  4461. } else // mScaleType == stLogarithmic
  4462. {
  4463. mRange.lower *= diff;
  4464. mRange.upper *= diff;
  4465. }
  4466. mCachedMarginValid = false;
  4467. emit rangeChanged(mRange);
  4468. emit rangeChanged(mRange, oldRange);
  4469. }
  4470. /*!
  4471. Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
  4472. factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
  4473. coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
  4474. around 1.0 will have moved symmetrically closer to 1.0).
  4475. */
  4476. void QCPAxis::scaleRange(double factor, double center)
  4477. {
  4478. QCPRange oldRange = mRange;
  4479. if (mScaleType == stLinear)
  4480. {
  4481. QCPRange newRange;
  4482. newRange.lower = (mRange.lower-center)*factor + center;
  4483. newRange.upper = (mRange.upper-center)*factor + center;
  4484. if (QCPRange::validRange(newRange))
  4485. mRange = newRange.sanitizedForLinScale();
  4486. } else // mScaleType == stLogarithmic
  4487. {
  4488. if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range
  4489. {
  4490. QCPRange newRange;
  4491. newRange.lower = pow(mRange.lower/center, factor)*center;
  4492. newRange.upper = pow(mRange.upper/center, factor)*center;
  4493. if (QCPRange::validRange(newRange))
  4494. mRange = newRange.sanitizedForLogScale();
  4495. } else
  4496. qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center;
  4497. }
  4498. mCachedMarginValid = false;
  4499. emit rangeChanged(mRange);
  4500. emit rangeChanged(mRange, oldRange);
  4501. }
  4502. /*!
  4503. Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will
  4504. be done around the center of the current axis range.
  4505. For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs
  4506. plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the
  4507. axis rect has.
  4508. This is an operation that changes the range of this axis once, it doesn't fix the scale ratio
  4509. indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent
  4510. won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent
  4511. will follow.
  4512. */
  4513. void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio)
  4514. {
  4515. int otherPixelSize, ownPixelSize;
  4516. if (otherAxis->orientation() == Qt::Horizontal)
  4517. otherPixelSize = otherAxis->axisRect()->width();
  4518. else
  4519. otherPixelSize = otherAxis->axisRect()->height();
  4520. if (orientation() == Qt::Horizontal)
  4521. ownPixelSize = axisRect()->width();
  4522. else
  4523. ownPixelSize = axisRect()->height();
  4524. double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/(double)otherPixelSize;
  4525. setRange(range().center(), newRangeSize, Qt::AlignCenter);
  4526. }
  4527. /*!
  4528. Changes the axis range such that all plottables associated with this axis are fully visible in
  4529. that dimension.
  4530. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
  4531. */
  4532. void QCPAxis::rescale(bool onlyVisiblePlottables)
  4533. {
  4534. QList<QCPAbstractPlottable*> p = plottables();
  4535. QCPRange newRange;
  4536. bool haveRange = false;
  4537. for (int i=0; i<p.size(); ++i)
  4538. {
  4539. if (!p.at(i)->realVisibility() && onlyVisiblePlottables)
  4540. continue;
  4541. QCPRange plottableRange;
  4542. bool currentFoundRange;
  4543. QCPAbstractPlottable::SignDomain signDomain = QCPAbstractPlottable::sdBoth;
  4544. if (mScaleType == stLogarithmic)
  4545. signDomain = (mRange.upper < 0 ? QCPAbstractPlottable::sdNegative : QCPAbstractPlottable::sdPositive);
  4546. if (p.at(i)->keyAxis() == this)
  4547. plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain);
  4548. else
  4549. plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain);
  4550. if (currentFoundRange)
  4551. {
  4552. if (!haveRange)
  4553. newRange = plottableRange;
  4554. else
  4555. newRange.expand(plottableRange);
  4556. haveRange = true;
  4557. }
  4558. }
  4559. if (haveRange)
  4560. {
  4561. 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
  4562. {
  4563. 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
  4564. if (mScaleType == stLinear)
  4565. {
  4566. newRange.lower = center-mRange.size()/2.0;
  4567. newRange.upper = center+mRange.size()/2.0;
  4568. } else // mScaleType == stLogarithmic
  4569. {
  4570. newRange.lower = center/qSqrt(mRange.upper/mRange.lower);
  4571. newRange.upper = center*qSqrt(mRange.upper/mRange.lower);
  4572. }
  4573. }
  4574. setRange(newRange);
  4575. }
  4576. }
  4577. /*!
  4578. Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
  4579. */
  4580. double QCPAxis::pixelToCoord(double value) const
  4581. {
  4582. if (orientation() == Qt::Horizontal)
  4583. {
  4584. if (mScaleType == stLinear)
  4585. {
  4586. if (!mRangeReversed)
  4587. return (value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.lower;
  4588. else
  4589. return -(value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.upper;
  4590. } else // mScaleType == stLogarithmic
  4591. {
  4592. if (!mRangeReversed)
  4593. return pow(mRange.upper/mRange.lower, (value-mAxisRect->left())/(double)mAxisRect->width())*mRange.lower;
  4594. else
  4595. return pow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/(double)mAxisRect->width())*mRange.upper;
  4596. }
  4597. } else // orientation() == Qt::Vertical
  4598. {
  4599. if (mScaleType == stLinear)
  4600. {
  4601. if (!mRangeReversed)
  4602. return (mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.lower;
  4603. else
  4604. return -(mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.upper;
  4605. } else // mScaleType == stLogarithmic
  4606. {
  4607. if (!mRangeReversed)
  4608. return pow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/(double)mAxisRect->height())*mRange.lower;
  4609. else
  4610. return pow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/(double)mAxisRect->height())*mRange.upper;
  4611. }
  4612. }
  4613. }
  4614. /*!
  4615. Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
  4616. */
  4617. double QCPAxis::coordToPixel(double value) const
  4618. {
  4619. if (orientation() == Qt::Horizontal)
  4620. {
  4621. if (mScaleType == stLinear)
  4622. {
  4623. if (!mRangeReversed)
  4624. return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left();
  4625. else
  4626. return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left();
  4627. } else // mScaleType == stLogarithmic
  4628. {
  4629. if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range
  4630. return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200;
  4631. else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range
  4632. return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200;
  4633. else
  4634. {
  4635. if (!mRangeReversed)
  4636. return baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
  4637. else
  4638. return baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
  4639. }
  4640. }
  4641. } else // orientation() == Qt::Vertical
  4642. {
  4643. if (mScaleType == stLinear)
  4644. {
  4645. if (!mRangeReversed)
  4646. return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height();
  4647. else
  4648. return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height();
  4649. } else // mScaleType == stLogarithmic
  4650. {
  4651. if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range
  4652. return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200;
  4653. else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range
  4654. return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200;
  4655. else
  4656. {
  4657. if (!mRangeReversed)
  4658. return mAxisRect->bottom()-baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height();
  4659. else
  4660. return mAxisRect->bottom()-baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height();
  4661. }
  4662. }
  4663. }
  4664. }
  4665. /*!
  4666. Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
  4667. is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
  4668. function does not change the current selection state of the axis.
  4669. If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
  4670. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
  4671. */
  4672. QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const
  4673. {
  4674. if (!mVisible)
  4675. return spNone;
  4676. if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
  4677. return spAxis;
  4678. else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
  4679. return spTickLabels;
  4680. else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
  4681. return spAxisLabel;
  4682. else
  4683. return spNone;
  4684. }
  4685. /* inherits documentation from base class */
  4686. double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  4687. {
  4688. if (!mParentPlot) return -1;
  4689. SelectablePart part = getPartAt(pos);
  4690. if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
  4691. return -1;
  4692. if (details)
  4693. details->setValue(part);
  4694. return mParentPlot->selectionTolerance()*0.99;
  4695. }
  4696. /*!
  4697. Returns a list of all the plottables that have this axis as key or value axis.
  4698. If you are only interested in plottables of type QCPGraph, see \ref graphs.
  4699. \see graphs, items
  4700. */
  4701. QList<QCPAbstractPlottable*> QCPAxis::plottables() const
  4702. {
  4703. QList<QCPAbstractPlottable*> result;
  4704. if (!mParentPlot) return result;
  4705. for (int i=0; i<mParentPlot->mPlottables.size(); ++i)
  4706. {
  4707. if (mParentPlot->mPlottables.at(i)->keyAxis() == this ||mParentPlot->mPlottables.at(i)->valueAxis() == this)
  4708. result.append(mParentPlot->mPlottables.at(i));
  4709. }
  4710. return result;
  4711. }
  4712. /*!
  4713. Returns a list of all the graphs that have this axis as key or value axis.
  4714. \see plottables, items
  4715. */
  4716. QList<QCPGraph*> QCPAxis::graphs() const
  4717. {
  4718. QList<QCPGraph*> result;
  4719. if (!mParentPlot) return result;
  4720. for (int i=0; i<mParentPlot->mGraphs.size(); ++i)
  4721. {
  4722. if (mParentPlot->mGraphs.at(i)->keyAxis() == this || mParentPlot->mGraphs.at(i)->valueAxis() == this)
  4723. result.append(mParentPlot->mGraphs.at(i));
  4724. }
  4725. return result;
  4726. }
  4727. /*!
  4728. Returns a list of all the items that are associated with this axis. An item is considered
  4729. associated with an axis if at least one of its positions uses the axis as key or value axis.
  4730. \see plottables, graphs
  4731. */
  4732. QList<QCPAbstractItem*> QCPAxis::items() const
  4733. {
  4734. QList<QCPAbstractItem*> result;
  4735. if (!mParentPlot) return result;
  4736. for (int itemId=0; itemId<mParentPlot->mItems.size(); ++itemId)
  4737. {
  4738. QList<QCPItemPosition*> positions = mParentPlot->mItems.at(itemId)->positions();
  4739. for (int posId=0; posId<positions.size(); ++posId)
  4740. {
  4741. if (positions.at(posId)->keyAxis() == this || positions.at(posId)->valueAxis() == this)
  4742. {
  4743. result.append(mParentPlot->mItems.at(itemId));
  4744. break;
  4745. }
  4746. }
  4747. }
  4748. return result;
  4749. }
  4750. /*!
  4751. Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to
  4752. QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.)
  4753. */
  4754. QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side)
  4755. {
  4756. switch (side)
  4757. {
  4758. case QCP::msLeft: return atLeft;
  4759. case QCP::msRight: return atRight;
  4760. case QCP::msTop: return atTop;
  4761. case QCP::msBottom: return atBottom;
  4762. default: break;
  4763. }
  4764. qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << (int)side;
  4765. return atLeft;
  4766. }
  4767. /*!
  4768. Returns the axis type that describes the opposite axis of an axis with the specified \a type.
  4769. */
  4770. QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type)
  4771. {
  4772. switch (type)
  4773. {
  4774. case atLeft: return atRight; break;
  4775. case atRight: return atLeft; break;
  4776. case atBottom: return atTop; break;
  4777. case atTop: return atBottom; break;
  4778. default: qDebug() << Q_FUNC_INFO << "invalid axis type"; return atLeft; break;
  4779. }
  4780. }
  4781. /*! \internal
  4782. This function is called to prepare the tick vector, sub tick vector and tick label vector. If
  4783. \ref setAutoTicks is set to true, appropriate tick values are determined automatically via \ref
  4784. generateAutoTicks. If it's set to false, the signal ticksRequest is emitted, which can be used to
  4785. provide external tick positions. Then the sub tick vectors and tick label vectors are created.
  4786. */
  4787. void QCPAxis::setupTickVectors()
  4788. {
  4789. if (!mParentPlot) return;
  4790. if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
  4791. // fill tick vectors, either by auto generating or by notifying user to fill the vectors himself
  4792. if (mAutoTicks)
  4793. {
  4794. generateAutoTicks();
  4795. } else
  4796. {
  4797. emit ticksRequest();
  4798. }
  4799. visibleTickBounds(mLowestVisibleTick, mHighestVisibleTick);
  4800. if (mTickVector.isEmpty())
  4801. {
  4802. mSubTickVector.clear();
  4803. return;
  4804. }
  4805. // generate subticks between ticks:
  4806. mSubTickVector.resize((mTickVector.size()-1)*mSubTickCount);
  4807. if (mSubTickCount > 0)
  4808. {
  4809. double subTickStep = 0;
  4810. double subTickPosition = 0;
  4811. int subTickIndex = 0;
  4812. bool done = false;
  4813. int lowTick = mLowestVisibleTick > 0 ? mLowestVisibleTick-1 : mLowestVisibleTick;
  4814. int highTick = mHighestVisibleTick < mTickVector.size()-1 ? mHighestVisibleTick+1 : mHighestVisibleTick;
  4815. for (int i=lowTick+1; i<=highTick; ++i)
  4816. {
  4817. subTickStep = (mTickVector.at(i)-mTickVector.at(i-1))/(double)(mSubTickCount+1);
  4818. for (int k=1; k<=mSubTickCount; ++k)
  4819. {
  4820. subTickPosition = mTickVector.at(i-1) + k*subTickStep;
  4821. if (subTickPosition < mRange.lower)
  4822. continue;
  4823. if (subTickPosition > mRange.upper)
  4824. {
  4825. done = true;
  4826. break;
  4827. }
  4828. mSubTickVector[subTickIndex] = subTickPosition;
  4829. subTickIndex++;
  4830. }
  4831. if (done) break;
  4832. }
  4833. mSubTickVector.resize(subTickIndex);
  4834. }
  4835. // generate tick labels according to tick positions:
  4836. if (mAutoTickLabels)
  4837. {
  4838. int vecsize = mTickVector.size();
  4839. mTickVectorLabels.resize(vecsize);
  4840. if (mTickLabelType == ltNumber)
  4841. {
  4842. for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i)
  4843. mTickVectorLabels[i] = mParentPlot->locale().toString(mTickVector.at(i), mNumberFormatChar, mNumberPrecision);
  4844. } else if (mTickLabelType == ltDateTime)
  4845. {
  4846. for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i)
  4847. {
  4848. #if QT_VERSION < QT_VERSION_CHECK(4, 7, 0) // use fromMSecsSinceEpoch function if available, to gain sub-second accuracy on tick labels (e.g. for format "hh:mm:ss:zzz")
  4849. mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromTime_t(mTickVector.at(i)).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
  4850. #else
  4851. mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromMSecsSinceEpoch(mTickVector.at(i)*1000).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
  4852. #endif
  4853. }
  4854. }
  4855. } else // mAutoTickLabels == false
  4856. {
  4857. if (mAutoTicks) // ticks generated automatically, but not ticklabels, so emit ticksRequest here for labels
  4858. {
  4859. emit ticksRequest();
  4860. }
  4861. // make sure provided tick label vector has correct (minimal) length:
  4862. if (mTickVectorLabels.size() < mTickVector.size())
  4863. mTickVectorLabels.resize(mTickVector.size());
  4864. }
  4865. }
  4866. /*! \internal
  4867. If \ref setAutoTicks is set to true, this function is called by \ref setupTickVectors to
  4868. generate reasonable tick positions (and subtick count). The algorithm tries to create
  4869. approximately <tt>mAutoTickCount</tt> ticks (set via \ref setAutoTickCount).
  4870. If the scale is logarithmic, \ref setAutoTickCount is ignored, and one tick is generated at every
  4871. power of the current logarithm base, set via \ref setScaleLogBase.
  4872. */
  4873. void QCPAxis::generateAutoTicks()
  4874. {
  4875. if (mScaleType == stLinear)
  4876. {
  4877. if (mAutoTickStep)
  4878. {
  4879. // Generate tick positions according to linear scaling:
  4880. mTickStep = mRange.size()/(double)(mAutoTickCount+1e-10); // mAutoTickCount ticks on average, the small addition is to prevent jitter on exact integers
  4881. double magnitudeFactor = qPow(10.0, qFloor(qLn(mTickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc.
  4882. double tickStepMantissa = mTickStep/magnitudeFactor;
  4883. if (tickStepMantissa < 5)
  4884. {
  4885. // round digit after decimal point to 0.5
  4886. mTickStep = (int)(tickStepMantissa*2)/2.0*magnitudeFactor;
  4887. } else
  4888. {
  4889. // round to first digit in multiples of 2
  4890. mTickStep = (int)(tickStepMantissa/2.0)*2.0*magnitudeFactor;
  4891. }
  4892. }
  4893. if (mAutoSubTicks)
  4894. mSubTickCount = calculateAutoSubTickCount(mTickStep);
  4895. // Generate tick positions according to mTickStep:
  4896. qint64 firstStep = floor(mRange.lower/mTickStep);
  4897. qint64 lastStep = ceil(mRange.upper/mTickStep);
  4898. int tickcount = lastStep-firstStep+1;
  4899. if (tickcount < 0) tickcount = 0;
  4900. mTickVector.resize(tickcount);
  4901. for (int i=0; i<tickcount; ++i)
  4902. mTickVector[i] = (firstStep+i)*mTickStep;
  4903. } else // mScaleType == stLogarithmic
  4904. {
  4905. // Generate tick positions according to logbase scaling:
  4906. if (mRange.lower > 0 && mRange.upper > 0) // positive range
  4907. {
  4908. double lowerMag = basePow((int)floor(baseLog(mRange.lower)));
  4909. double currentMag = lowerMag;
  4910. mTickVector.clear();
  4911. mTickVector.append(currentMag);
  4912. while (currentMag < mRange.upper && currentMag > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
  4913. {
  4914. currentMag *= mScaleLogBase;
  4915. mTickVector.append(currentMag);
  4916. }
  4917. } else if (mRange.lower < 0 && mRange.upper < 0) // negative range
  4918. {
  4919. double lowerMag = -basePow((int)ceil(baseLog(-mRange.lower)));
  4920. double currentMag = lowerMag;
  4921. mTickVector.clear();
  4922. mTickVector.append(currentMag);
  4923. while (currentMag < mRange.upper && currentMag < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
  4924. {
  4925. currentMag /= mScaleLogBase;
  4926. mTickVector.append(currentMag);
  4927. }
  4928. } else // invalid range for logarithmic scale, because lower and upper have different sign
  4929. {
  4930. mTickVector.clear();
  4931. qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << mRange.lower << "-" << mRange.upper;
  4932. }
  4933. }
  4934. }
  4935. /*! \internal
  4936. Called by generateAutoTicks when \ref setAutoSubTicks is set to true. Depending on the \a
  4937. tickStep between two major ticks on the axis, a different number of sub ticks is appropriate. For
  4938. Example taking 4 sub ticks for a \a tickStep of 1 makes more sense than taking 5 sub ticks,
  4939. because this corresponds to a sub tick step of 0.2, instead of the less intuitive 0.16667. Note
  4940. that a subtick count of 4 means dividing the major tick step into 5 sections.
  4941. This is implemented by a hand made lookup for integer tick steps as well as fractional tick steps
  4942. with a fractional part of (approximately) 0.5. If a tick step is different (i.e. has no
  4943. fractional part close to 0.5), the currently set sub tick count (\ref setSubTickCount) is
  4944. returned.
  4945. */
  4946. int QCPAxis::calculateAutoSubTickCount(double tickStep) const
  4947. {
  4948. int result = mSubTickCount; // default to current setting, if no proper value can be found
  4949. // get mantissa of tickstep:
  4950. double magnitudeFactor = qPow(10.0, qFloor(qLn(tickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc.
  4951. double tickStepMantissa = tickStep/magnitudeFactor;
  4952. // separate integer and fractional part of mantissa:
  4953. double epsilon = 0.01;
  4954. double intPartf;
  4955. int intPart;
  4956. double fracPart = modf(tickStepMantissa, &intPartf);
  4957. intPart = intPartf;
  4958. // handle cases with (almost) integer mantissa:
  4959. if (fracPart < epsilon || 1.0-fracPart < epsilon)
  4960. {
  4961. if (1.0-fracPart < epsilon)
  4962. ++intPart;
  4963. switch (intPart)
  4964. {
  4965. case 1: result = 4; break; // 1.0 -> 0.2 substep
  4966. case 2: result = 3; break; // 2.0 -> 0.5 substep
  4967. case 3: result = 2; break; // 3.0 -> 1.0 substep
  4968. case 4: result = 3; break; // 4.0 -> 1.0 substep
  4969. case 5: result = 4; break; // 5.0 -> 1.0 substep
  4970. case 6: result = 2; break; // 6.0 -> 2.0 substep
  4971. case 7: result = 6; break; // 7.0 -> 1.0 substep
  4972. case 8: result = 3; break; // 8.0 -> 2.0 substep
  4973. case 9: result = 2; break; // 9.0 -> 3.0 substep
  4974. }
  4975. } else
  4976. {
  4977. // handle cases with significantly fractional mantissa:
  4978. if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa
  4979. {
  4980. switch (intPart)
  4981. {
  4982. case 1: result = 2; break; // 1.5 -> 0.5 substep
  4983. case 2: result = 4; break; // 2.5 -> 0.5 substep
  4984. case 3: result = 4; break; // 3.5 -> 0.7 substep
  4985. case 4: result = 2; break; // 4.5 -> 1.5 substep
  4986. case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with autoTickStep from here on)
  4987. case 6: result = 4; break; // 6.5 -> 1.3 substep
  4988. case 7: result = 2; break; // 7.5 -> 2.5 substep
  4989. case 8: result = 4; break; // 8.5 -> 1.7 substep
  4990. case 9: result = 4; break; // 9.5 -> 1.9 substep
  4991. }
  4992. }
  4993. // if mantissa fraction isnt 0.0 or 0.5, don't bother finding good sub tick marks, leave default
  4994. }
  4995. return result;
  4996. }
  4997. /* inherits documentation from base class */
  4998. void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  4999. {
  5000. Q_UNUSED(event)
  5001. SelectablePart part = details.value<SelectablePart>();
  5002. if (mSelectableParts.testFlag(part))
  5003. {
  5004. SelectableParts selBefore = mSelectedParts;
  5005. setSelectedParts(additive ? mSelectedParts^part : part);
  5006. if (selectionStateChanged)
  5007. *selectionStateChanged = mSelectedParts != selBefore;
  5008. }
  5009. }
  5010. /* inherits documentation from base class */
  5011. void QCPAxis::deselectEvent(bool *selectionStateChanged)
  5012. {
  5013. SelectableParts selBefore = mSelectedParts;
  5014. setSelectedParts(mSelectedParts & ~mSelectableParts);
  5015. if (selectionStateChanged)
  5016. *selectionStateChanged = mSelectedParts != selBefore;
  5017. }
  5018. /*! \internal
  5019. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  5020. before drawing axis lines.
  5021. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  5022. This function takes into account the local setting of the antialiasing flag as well as the
  5023. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  5024. QCustomPlot::setNotAntialiasedElements.
  5025. \see setAntialiased
  5026. */
  5027. void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const
  5028. {
  5029. applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
  5030. }
  5031. /*! \internal
  5032. Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance.
  5033. */
  5034. void QCPAxis::draw(QCPPainter *painter)
  5035. {
  5036. const int lowTick = mLowestVisibleTick;
  5037. const int highTick = mHighestVisibleTick;
  5038. QVector<double> subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  5039. QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  5040. QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
  5041. tickPositions.reserve(highTick-lowTick+1);
  5042. tickLabels.reserve(highTick-lowTick+1);
  5043. subTickPositions.reserve(mSubTickVector.size());
  5044. if (mTicks)
  5045. {
  5046. for (int i=lowTick; i<=highTick; ++i)
  5047. {
  5048. tickPositions.append(coordToPixel(mTickVector.at(i)));
  5049. if (mTickLabels)
  5050. tickLabels.append(mTickVectorLabels.at(i));
  5051. }
  5052. if (mSubTickCount > 0)
  5053. {
  5054. const int subTickCount = mSubTickVector.size();
  5055. for (int i=0; i<subTickCount; ++i) // no need to check bounds because subticks are always only created inside current mRange
  5056. subTickPositions.append(coordToPixel(mSubTickVector.at(i)));
  5057. }
  5058. }
  5059. // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to draw the axis.
  5060. // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
  5061. mAxisPainter->type = mAxisType;
  5062. mAxisPainter->basePen = getBasePen();
  5063. mAxisPainter->labelFont = getLabelFont();
  5064. mAxisPainter->labelColor = getLabelColor();
  5065. mAxisPainter->label = mLabel;
  5066. mAxisPainter->substituteExponent = mAutoTickLabels && mNumberBeautifulPowers && mTickLabelType == ltNumber;
  5067. mAxisPainter->tickPen = getTickPen();
  5068. mAxisPainter->subTickPen = getSubTickPen();
  5069. mAxisPainter->tickLabelFont = getTickLabelFont();
  5070. mAxisPainter->tickLabelColor = getTickLabelColor();
  5071. mAxisPainter->alignmentRect = mAxisRect->rect();
  5072. mAxisPainter->viewportRect = mParentPlot->viewport();
  5073. mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic;
  5074. mAxisPainter->reversedEndings = mRangeReversed;
  5075. mAxisPainter->tickPositions = tickPositions;
  5076. mAxisPainter->tickLabels = tickLabels;
  5077. mAxisPainter->subTickPositions = subTickPositions;
  5078. mAxisPainter->draw(painter);
  5079. }
  5080. /*! \internal
  5081. Returns via \a lowIndex and \a highIndex, which ticks in the current tick vector are visible in
  5082. the current range. The return values are indices of the tick vector, not the positions of the
  5083. ticks themselves.
  5084. The actual use of this function is when an external tick vector is provided, since it might
  5085. exceed far beyond the currently displayed range, and would cause unnecessary calculations e.g. of
  5086. subticks.
  5087. If all ticks are outside the axis range, an inverted range is returned, i.e. highIndex will be
  5088. smaller than lowIndex. There is one case, where this function returns indices that are not really
  5089. visible in the current axis range: When the tick spacing is larger than the axis range size and
  5090. one tick is below the axis range and the next tick is already above the axis range. Because in
  5091. such cases it is usually desirable to know the tick pair, to draw proper subticks.
  5092. */
  5093. void QCPAxis::visibleTickBounds(int &lowIndex, int &highIndex) const
  5094. {
  5095. bool lowFound = false;
  5096. bool highFound = false;
  5097. lowIndex = 0;
  5098. highIndex = -1;
  5099. for (int i=0; i < mTickVector.size(); ++i)
  5100. {
  5101. if (mTickVector.at(i) >= mRange.lower)
  5102. {
  5103. lowFound = true;
  5104. lowIndex = i;
  5105. break;
  5106. }
  5107. }
  5108. for (int i=mTickVector.size()-1; i >= 0; --i)
  5109. {
  5110. if (mTickVector.at(i) <= mRange.upper)
  5111. {
  5112. highFound = true;
  5113. highIndex = i;
  5114. break;
  5115. }
  5116. }
  5117. if (!lowFound && highFound)
  5118. lowIndex = highIndex+1;
  5119. else if (lowFound && !highFound)
  5120. highIndex = lowIndex-1;
  5121. }
  5122. /*! \internal
  5123. A log function with the base mScaleLogBase, used mostly for coordinate transforms in logarithmic
  5124. scales with arbitrary log base. Uses the buffered mScaleLogBaseLogInv for faster calculation.
  5125. This is set to <tt>1.0/qLn(mScaleLogBase)</tt> in \ref setScaleLogBase.
  5126. \see basePow, setScaleLogBase, setScaleType
  5127. */
  5128. double QCPAxis::baseLog(double value) const
  5129. {
  5130. return qLn(value)*mScaleLogBaseLogInv;
  5131. }
  5132. /*! \internal
  5133. A power function with the base mScaleLogBase, used mostly for coordinate transforms in
  5134. logarithmic scales with arbitrary log base.
  5135. \see baseLog, setScaleLogBase, setScaleType
  5136. */
  5137. double QCPAxis::basePow(double value) const
  5138. {
  5139. return qPow(mScaleLogBase, value);
  5140. }
  5141. /*! \internal
  5142. Returns the pen that is used to draw the axis base line. Depending on the selection state, this
  5143. is either mSelectedBasePen or mBasePen.
  5144. */
  5145. QPen QCPAxis::getBasePen() const
  5146. {
  5147. return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
  5148. }
  5149. /*! \internal
  5150. Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
  5151. is either mSelectedTickPen or mTickPen.
  5152. */
  5153. QPen QCPAxis::getTickPen() const
  5154. {
  5155. return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
  5156. }
  5157. /*! \internal
  5158. Returns the pen that is used to draw the subticks. Depending on the selection state, this
  5159. is either mSelectedSubTickPen or mSubTickPen.
  5160. */
  5161. QPen QCPAxis::getSubTickPen() const
  5162. {
  5163. return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
  5164. }
  5165. /*! \internal
  5166. Returns the font that is used to draw the tick labels. Depending on the selection state, this
  5167. is either mSelectedTickLabelFont or mTickLabelFont.
  5168. */
  5169. QFont QCPAxis::getTickLabelFont() const
  5170. {
  5171. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
  5172. }
  5173. /*! \internal
  5174. Returns the font that is used to draw the axis label. Depending on the selection state, this
  5175. is either mSelectedLabelFont or mLabelFont.
  5176. */
  5177. QFont QCPAxis::getLabelFont() const
  5178. {
  5179. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
  5180. }
  5181. /*! \internal
  5182. Returns the color that is used to draw the tick labels. Depending on the selection state, this
  5183. is either mSelectedTickLabelColor or mTickLabelColor.
  5184. */
  5185. QColor QCPAxis::getTickLabelColor() const
  5186. {
  5187. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
  5188. }
  5189. /*! \internal
  5190. Returns the color that is used to draw the axis label. Depending on the selection state, this
  5191. is either mSelectedLabelColor or mLabelColor.
  5192. */
  5193. QColor QCPAxis::getLabelColor() const
  5194. {
  5195. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
  5196. }
  5197. /*! \internal
  5198. Returns the appropriate outward margin for this axis. It is needed if \ref
  5199. QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref
  5200. atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom
  5201. margin and so forth. For the calculation, this function goes through similar steps as \ref draw,
  5202. so changing one function likely requires the modification of the other one as well.
  5203. The margin consists of the outward tick length, tick label padding, tick label size, label
  5204. padding, label size, and padding.
  5205. The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc.
  5206. unchanged are very fast.
  5207. */
  5208. int QCPAxis::calculateMargin()
  5209. {
  5210. if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis
  5211. return 0;
  5212. if (mCachedMarginValid)
  5213. return mCachedMargin;
  5214. // run through similar steps as QCPAxis::draw, and caluclate margin needed to fit axis and its labels
  5215. int margin = 0;
  5216. int lowTick, highTick;
  5217. visibleTickBounds(lowTick, highTick);
  5218. QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  5219. QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
  5220. tickPositions.reserve(highTick-lowTick+1);
  5221. tickLabels.reserve(highTick-lowTick+1);
  5222. if (mTicks)
  5223. {
  5224. for (int i=lowTick; i<=highTick; ++i)
  5225. {
  5226. tickPositions.append(coordToPixel(mTickVector.at(i)));
  5227. if (mTickLabels)
  5228. tickLabels.append(mTickVectorLabels.at(i));
  5229. }
  5230. }
  5231. // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size.
  5232. // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
  5233. mAxisPainter->type = mAxisType;
  5234. mAxisPainter->labelFont = getLabelFont();
  5235. mAxisPainter->label = mLabel;
  5236. mAxisPainter->tickLabelFont = mTickLabelFont;
  5237. mAxisPainter->alignmentRect = mAxisRect->rect();
  5238. mAxisPainter->viewportRect = mParentPlot->viewport();
  5239. mAxisPainter->tickPositions = tickPositions;
  5240. mAxisPainter->tickLabels = tickLabels;
  5241. margin += mAxisPainter->size();
  5242. margin += mPadding;
  5243. mCachedMargin = margin;
  5244. mCachedMarginValid = true;
  5245. return margin;
  5246. }
  5247. /* inherits documentation from base class */
  5248. QCP::Interaction QCPAxis::selectionCategory() const
  5249. {
  5250. return QCP::iSelectAxes;
  5251. }
  5252. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5253. //////////////////// QCPAxisPainterPrivate
  5254. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5255. /*! \class QCPAxisPainterPrivate
  5256. \internal
  5257. \brief (Private)
  5258. This is a private class and not part of the public QCustomPlot interface.
  5259. It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and
  5260. axis label. It also buffers the labels to reduce replot times. The parameters are configured by
  5261. directly accessing the public member variables.
  5262. */
  5263. /*!
  5264. Constructs a QCPAxisPainterPrivate instance. Make sure to not create a new instance on every
  5265. redraw, to utilize the caching mechanisms.
  5266. */
  5267. QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) :
  5268. type(QCPAxis::atLeft),
  5269. basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  5270. lowerEnding(QCPLineEnding::esNone),
  5271. upperEnding(QCPLineEnding::esNone),
  5272. labelPadding(0),
  5273. tickLabelPadding(0),
  5274. tickLabelRotation(0),
  5275. substituteExponent(true),
  5276. numberMultiplyCross(false),
  5277. tickLengthIn(5),
  5278. tickLengthOut(0),
  5279. subTickLengthIn(2),
  5280. subTickLengthOut(0),
  5281. tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  5282. subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  5283. offset(0),
  5284. abbreviateDecimalPowers(false),
  5285. reversedEndings(false),
  5286. mParentPlot(parentPlot),
  5287. mLabelCache(16) // cache at most 16 (tick) labels
  5288. {
  5289. }
  5290. QCPAxisPainterPrivate::~QCPAxisPainterPrivate()
  5291. {
  5292. }
  5293. /*! \internal
  5294. Draws the axis with the specified \a painter.
  5295. The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set
  5296. here, too.
  5297. */
  5298. void QCPAxisPainterPrivate::draw(QCPPainter *painter)
  5299. {
  5300. QByteArray newHash = generateLabelParameterHash();
  5301. if (newHash != mLabelParameterHash)
  5302. {
  5303. mLabelCache.clear();
  5304. mLabelParameterHash = newHash;
  5305. }
  5306. QPoint origin;
  5307. switch (type)
  5308. {
  5309. case QCPAxis::atLeft: origin = alignmentRect.bottomLeft() +QPoint(-offset, 0); break;
  5310. case QCPAxis::atRight: origin = alignmentRect.bottomRight()+QPoint(+offset, 0); break;
  5311. case QCPAxis::atTop: origin = alignmentRect.topLeft() +QPoint(0, -offset); break;
  5312. case QCPAxis::atBottom: origin = alignmentRect.bottomLeft() +QPoint(0, +offset); break;
  5313. }
  5314. double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes)
  5315. switch (type)
  5316. {
  5317. case QCPAxis::atTop: yCor = -1; break;
  5318. case QCPAxis::atRight: xCor = 1; break;
  5319. default: break;
  5320. }
  5321. int margin = 0;
  5322. // draw baseline:
  5323. QLineF baseLine;
  5324. painter->setPen(basePen);
  5325. if (QCPAxis::orientation(type) == Qt::Horizontal)
  5326. baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(alignmentRect.width()+xCor, yCor));
  5327. else
  5328. baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -alignmentRect.height()+yCor));
  5329. if (reversedEndings)
  5330. baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later
  5331. painter->drawLine(baseLine);
  5332. // draw ticks:
  5333. if (!tickPositions.isEmpty())
  5334. {
  5335. painter->setPen(tickPen);
  5336. int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis)
  5337. if (QCPAxis::orientation(type) == Qt::Horizontal)
  5338. {
  5339. for (int i=0; i<tickPositions.size(); ++i)
  5340. painter->drawLine(QLineF(tickPositions.at(i)+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPositions.at(i)+xCor, origin.y()+tickLengthIn*tickDir+yCor));
  5341. } else
  5342. {
  5343. for (int i=0; i<tickPositions.size(); ++i)
  5344. painter->drawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPositions.at(i)+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPositions.at(i)+yCor));
  5345. }
  5346. }
  5347. // draw subticks:
  5348. if (!subTickPositions.isEmpty())
  5349. {
  5350. painter->setPen(subTickPen);
  5351. // direction of ticks ("inward" is right for left axis and left for right axis)
  5352. int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1;
  5353. if (QCPAxis::orientation(type) == Qt::Horizontal)
  5354. {
  5355. for (int i=0; i<subTickPositions.size(); ++i)
  5356. painter->drawLine(QLineF(subTickPositions.at(i)+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPositions.at(i)+xCor, origin.y()+subTickLengthIn*tickDir+yCor));
  5357. } else
  5358. {
  5359. for (int i=0; i<subTickPositions.size(); ++i)
  5360. painter->drawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPositions.at(i)+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPositions.at(i)+yCor));
  5361. }
  5362. }
  5363. margin += qMax(0, qMax(tickLengthOut, subTickLengthOut));
  5364. // draw axis base endings:
  5365. bool antialiasingBackup = painter->antialiasing();
  5366. painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't
  5367. painter->setBrush(QBrush(basePen.color()));
  5368. QVector2D baseLineVector(baseLine.dx(), baseLine.dy());
  5369. if (lowerEnding.style() != QCPLineEnding::esNone)
  5370. lowerEnding.draw(painter, QVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector);
  5371. if (upperEnding.style() != QCPLineEnding::esNone)
  5372. upperEnding.draw(painter, QVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector);
  5373. painter->setAntialiasing(antialiasingBackup);
  5374. // tick labels:
  5375. QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label
  5376. if (!tickLabels.isEmpty())
  5377. {
  5378. margin += tickLabelPadding;
  5379. painter->setFont(tickLabelFont);
  5380. painter->setPen(QPen(tickLabelColor));
  5381. const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size());
  5382. for (int i=0; i<maxLabelIndex; ++i)
  5383. placeTickLabel(painter, tickPositions.at(i), margin, tickLabels.at(i), &tickLabelsSize);
  5384. if (QCPAxis::orientation(type) == Qt::Horizontal)
  5385. margin += tickLabelsSize.height();
  5386. else
  5387. margin += tickLabelsSize.width();
  5388. }
  5389. // axis label:
  5390. QRect labelBounds;
  5391. if (!label.isEmpty())
  5392. {
  5393. margin += labelPadding;
  5394. painter->setFont(labelFont);
  5395. painter->setPen(QPen(labelColor));
  5396. labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label);
  5397. if (type == QCPAxis::atLeft)
  5398. {
  5399. QTransform oldTransform = painter->transform();
  5400. painter->translate((origin.x()-margin-labelBounds.height()), origin.y());
  5401. painter->rotate(-90);
  5402. painter->drawText(0, 0, alignmentRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  5403. painter->setTransform(oldTransform);
  5404. }
  5405. else if (type == QCPAxis::atRight)
  5406. {
  5407. QTransform oldTransform = painter->transform();
  5408. painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-alignmentRect.height());
  5409. painter->rotate(90);
  5410. painter->drawText(0, 0, alignmentRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  5411. painter->setTransform(oldTransform);
  5412. }
  5413. else if (type == QCPAxis::atTop)
  5414. painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), alignmentRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  5415. else if (type == QCPAxis::atBottom)
  5416. painter->drawText(origin.x(), origin.y()+margin, alignmentRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  5417. }
  5418. // set selection boxes:
  5419. int selectionTolerance = 0;
  5420. if (mParentPlot)
  5421. selectionTolerance = mParentPlot->selectionTolerance();
  5422. else
  5423. qDebug() << Q_FUNC_INFO << "mParentPlot is null";
  5424. int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance);
  5425. int selAxisInSize = selectionTolerance;
  5426. int selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
  5427. int selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding;
  5428. int selLabelSize = labelBounds.height();
  5429. int selLabelOffset = selTickLabelOffset+selTickLabelSize+labelPadding;
  5430. if (type == QCPAxis::atLeft)
  5431. {
  5432. mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, alignmentRect.top(), origin.x()+selAxisInSize, alignmentRect.bottom());
  5433. mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, alignmentRect.top(), origin.x()-selTickLabelOffset, alignmentRect.bottom());
  5434. mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, alignmentRect.top(), origin.x()-selLabelOffset, alignmentRect.bottom());
  5435. } else if (type == QCPAxis::atRight)
  5436. {
  5437. mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, alignmentRect.top(), origin.x()+selAxisOutSize, alignmentRect.bottom());
  5438. mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, alignmentRect.top(), origin.x()+selTickLabelOffset, alignmentRect.bottom());
  5439. mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, alignmentRect.top(), origin.x()+selLabelOffset, alignmentRect.bottom());
  5440. } else if (type == QCPAxis::atTop)
  5441. {
  5442. mAxisSelectionBox.setCoords(alignmentRect.left(), origin.y()-selAxisOutSize, alignmentRect.right(), origin.y()+selAxisInSize);
  5443. mTickLabelsSelectionBox.setCoords(alignmentRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, alignmentRect.right(), origin.y()-selTickLabelOffset);
  5444. mLabelSelectionBox.setCoords(alignmentRect.left(), origin.y()-selLabelOffset-selLabelSize, alignmentRect.right(), origin.y()-selLabelOffset);
  5445. } else if (type == QCPAxis::atBottom)
  5446. {
  5447. mAxisSelectionBox.setCoords(alignmentRect.left(), origin.y()-selAxisInSize, alignmentRect.right(), origin.y()+selAxisOutSize);
  5448. mTickLabelsSelectionBox.setCoords(alignmentRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, alignmentRect.right(), origin.y()+selTickLabelOffset);
  5449. mLabelSelectionBox.setCoords(alignmentRect.left(), origin.y()+selLabelOffset+selLabelSize, alignmentRect.right(), origin.y()+selLabelOffset);
  5450. }
  5451. // draw hitboxes for debug purposes:
  5452. //painter->setBrush(Qt::NoBrush);
  5453. //painter->drawRects(QVector<QRect>() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox);
  5454. }
  5455. /*! \internal
  5456. Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone
  5457. direction) needed to fit the axis.
  5458. */
  5459. int QCPAxisPainterPrivate::size() const
  5460. {
  5461. int result = 0;
  5462. // get length of tick marks pointing outwards:
  5463. if (!tickPositions.isEmpty())
  5464. result += qMax(0, qMax(tickLengthOut, subTickLengthOut));
  5465. // calculate size of tick labels:
  5466. QSize tickLabelsSize(0, 0);
  5467. if (!tickLabels.isEmpty())
  5468. {
  5469. for (int i=0; i<tickLabels.size(); ++i)
  5470. getMaxTickLabelSize(tickLabelFont, tickLabels.at(i), &tickLabelsSize);
  5471. result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width();
  5472. result += tickLabelPadding;
  5473. }
  5474. // calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees):
  5475. if (!label.isEmpty())
  5476. {
  5477. QFontMetrics fontMetrics(labelFont);
  5478. QRect bounds;
  5479. bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label);
  5480. result += bounds.height() + labelPadding;
  5481. }
  5482. return result;
  5483. }
  5484. /*! \internal
  5485. Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This
  5486. method is called automatically in \ref draw, if any parameters have changed that invalidate the
  5487. cached labels, such as font, color, etc.
  5488. */
  5489. void QCPAxisPainterPrivate::clearCache()
  5490. {
  5491. mLabelCache.clear();
  5492. }
  5493. /*! \internal
  5494. Returns a hash that allows uniquely identifying whether the label parameters have changed such
  5495. that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the
  5496. return value of this method hasn't changed since the last redraw, the respective label parameters
  5497. haven't changed and cached labels may be used.
  5498. */
  5499. QByteArray QCPAxisPainterPrivate::generateLabelParameterHash() const
  5500. {
  5501. QByteArray result;
  5502. result.append(QByteArray::number(tickLabelRotation));
  5503. result.append(QByteArray::number((int)substituteExponent));
  5504. result.append(QByteArray::number((int)numberMultiplyCross));
  5505. result.append(tickLabelColor.name()+QByteArray::number(tickLabelColor.alpha(), 16));
  5506. result.append(tickLabelFont.toString());
  5507. return result;
  5508. }
  5509. /*! \internal
  5510. Draws a single tick label with the provided \a painter, utilizing the internal label cache to
  5511. significantly speed up drawing of labels that were drawn in previous calls. The tick label is
  5512. always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in
  5513. pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence
  5514. for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate),
  5515. at which the label should be drawn.
  5516. In order to later draw the axis label in a place that doesn't overlap with the tick labels, the
  5517. largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref
  5518. drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a
  5519. tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently
  5520. holds.
  5521. The label is drawn with the font and pen that are currently set on the \a painter. To draw
  5522. superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref
  5523. getTickLabelData).
  5524. */
  5525. void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize)
  5526. {
  5527. // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly!
  5528. if (text.isEmpty()) return;
  5529. QSize finalSize;
  5530. QPointF labelAnchor;
  5531. switch (type)
  5532. {
  5533. case QCPAxis::atLeft: labelAnchor = QPointF(alignmentRect.left()-distanceToAxis-offset, position); break;
  5534. case QCPAxis::atRight: labelAnchor = QPointF(alignmentRect.right()+distanceToAxis+offset, position); break;
  5535. case QCPAxis::atTop: labelAnchor = QPointF(position, alignmentRect.top()-distanceToAxis-offset); break;
  5536. case QCPAxis::atBottom: labelAnchor = QPointF(position, alignmentRect.bottom()+distanceToAxis+offset); break;
  5537. }
  5538. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled
  5539. {
  5540. if (!mLabelCache.contains(text)) // no cached label exists, create it
  5541. {
  5542. CachedLabel *newCachedLabel = new CachedLabel;
  5543. TickLabelData labelData = getTickLabelData(painter->font(), text);
  5544. QPointF drawOffset = getTickLabelDrawOffset(labelData);
  5545. newCachedLabel->offset = drawOffset+labelData.rotatedTotalBounds.topLeft();
  5546. newCachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
  5547. newCachedLabel->pixmap.fill(Qt::transparent);
  5548. QCPPainter cachePainter(&newCachedLabel->pixmap);
  5549. cachePainter.setPen(painter->pen());
  5550. drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData);
  5551. mLabelCache.insert(text, newCachedLabel, 1);
  5552. }
  5553. // draw cached label:
  5554. const CachedLabel *cachedLabel = mLabelCache.object(text);
  5555. // if label would be partly clipped by widget border on sides, don't draw it:
  5556. if (QCPAxis::orientation(type) == Qt::Horizontal)
  5557. {
  5558. if (labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width() > viewportRect.right() ||
  5559. labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left())
  5560. return;
  5561. } else
  5562. {
  5563. if (labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height() >viewportRect.bottom() ||
  5564. labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top())
  5565. return;
  5566. }
  5567. painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap);
  5568. finalSize = cachedLabel->pixmap.size();
  5569. } else // label caching disabled, draw text directly on surface:
  5570. {
  5571. TickLabelData labelData = getTickLabelData(painter->font(), text);
  5572. QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData);
  5573. // if label would be partly clipped by widget border on sides, don't draw it:
  5574. if (QCPAxis::orientation(type) == Qt::Horizontal)
  5575. {
  5576. if (finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() ||
  5577. finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left())
  5578. return;
  5579. } else
  5580. {
  5581. if (finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() ||
  5582. finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top())
  5583. return;
  5584. }
  5585. drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData);
  5586. finalSize = labelData.rotatedTotalBounds.size();
  5587. }
  5588. // expand passed tickLabelsSize if current tick label is larger:
  5589. if (finalSize.width() > tickLabelsSize->width())
  5590. tickLabelsSize->setWidth(finalSize.width());
  5591. if (finalSize.height() > tickLabelsSize->height())
  5592. tickLabelsSize->setHeight(finalSize.height());
  5593. }
  5594. /*! \internal
  5595. This is a \ref placeTickLabel helper function.
  5596. Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a
  5597. y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to
  5598. directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when
  5599. QCP::phCacheLabels plotting hint is not set.
  5600. */
  5601. void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const
  5602. {
  5603. // backup painter settings that we're about to change:
  5604. QTransform oldTransform = painter->transform();
  5605. QFont oldFont = painter->font();
  5606. // transform painter to position/rotation:
  5607. painter->translate(x, y);
  5608. if (!qFuzzyIsNull(tickLabelRotation))
  5609. painter->rotate(tickLabelRotation);
  5610. // draw text:
  5611. if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used
  5612. {
  5613. painter->setFont(labelData.baseFont);
  5614. painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart);
  5615. painter->setFont(labelData.expFont);
  5616. painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart);
  5617. } else
  5618. {
  5619. painter->setFont(labelData.baseFont);
  5620. painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart);
  5621. }
  5622. // reset painter settings to what it was before:
  5623. painter->setTransform(oldTransform);
  5624. painter->setFont(oldFont);
  5625. }
  5626. /*! \internal
  5627. This is a \ref placeTickLabel helper function.
  5628. Transforms the passed \a text and \a font to a tickLabelData structure that can then be further
  5629. processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and
  5630. exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes.
  5631. */
  5632. QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const
  5633. {
  5634. TickLabelData result;
  5635. // determine whether beautiful decimal powers should be used
  5636. bool useBeautifulPowers = false;
  5637. int ePos = -1;
  5638. if (substituteExponent)
  5639. {
  5640. ePos = text.indexOf('e');
  5641. if (ePos > -1)
  5642. useBeautifulPowers = true;
  5643. }
  5644. // calculate text bounding rects and do string preparation for beautiful decimal powers:
  5645. result.baseFont = font;
  5646. if (result.baseFont.pointSizeF() > 0) // On some rare systems, this sometimes is initialized with -1 (Qt bug?), so we check here before possibly setting a negative value in the next line
  5647. 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
  5648. if (useBeautifulPowers)
  5649. {
  5650. // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent:
  5651. result.basePart = text.left(ePos);
  5652. // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base:
  5653. if (abbreviateDecimalPowers && result.basePart == "1")
  5654. result.basePart = "10";
  5655. else
  5656. result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + "10";
  5657. result.expPart = text.mid(ePos+1);
  5658. // clip "+" and leading zeros off expPart:
  5659. while (result.expPart.length() > 2 && result.expPart.at(1) == '0') // length > 2 so we leave one zero when numberFormatChar is 'e'
  5660. result.expPart.remove(1, 1);
  5661. if (!result.expPart.isEmpty() && result.expPart.at(0) == '+')
  5662. result.expPart.remove(0, 1);
  5663. // prepare smaller font for exponent:
  5664. result.expFont = font;
  5665. result.expFont.setPointSize(result.expFont.pointSize()*0.75);
  5666. // calculate bounding rects of base part, exponent part and total one:
  5667. result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart);
  5668. result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart);
  5669. result.totalBounds = result.baseBounds.adjusted(0, 0, result.expBounds.width()+2, 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel) and an extra pixel to include AA
  5670. } else // useBeautifulPowers == false
  5671. {
  5672. result.basePart = text;
  5673. result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart);
  5674. }
  5675. 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
  5676. // calculate possibly different bounding rect after rotation:
  5677. result.rotatedTotalBounds = result.totalBounds;
  5678. if (!qFuzzyIsNull(tickLabelRotation))
  5679. {
  5680. QTransform transform;
  5681. transform.rotate(tickLabelRotation);
  5682. result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds);
  5683. }
  5684. return result;
  5685. }
  5686. /*! \internal
  5687. This is a \ref placeTickLabel helper function.
  5688. Calculates the offset at which the top left corner of the specified tick label shall be drawn.
  5689. The offset is relative to a point right next to the tick the label belongs to.
  5690. This function is thus responsible for e.g. centering tick labels under ticks and positioning them
  5691. appropriately when they are rotated.
  5692. */
  5693. QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const
  5694. {
  5695. /*
  5696. calculate label offset from base point at tick (non-trivial, for best visual appearance): short
  5697. explanation for bottom axis: The anchor, i.e. the point in the label that is placed
  5698. horizontally under the corresponding tick is always on the label side that is closer to the
  5699. axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height
  5700. is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text
  5701. will be centered under the tick (i.e. displaced horizontally by half its height). At the same
  5702. time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick
  5703. labels.
  5704. */
  5705. bool doRotation = !qFuzzyIsNull(tickLabelRotation);
  5706. bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes.
  5707. double radians = tickLabelRotation/180.0*M_PI;
  5708. int x=0, y=0;
  5709. if (type == QCPAxis::atLeft)
  5710. {
  5711. if (doRotation)
  5712. {
  5713. if (tickLabelRotation > 0)
  5714. {
  5715. x = -qCos(radians)*labelData.totalBounds.width();
  5716. y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0;
  5717. } else
  5718. {
  5719. x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height();
  5720. y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0;
  5721. }
  5722. } else
  5723. {
  5724. x = -labelData.totalBounds.width();
  5725. y = -labelData.totalBounds.height()/2.0;
  5726. }
  5727. } else if (type == QCPAxis::atRight)
  5728. {
  5729. if (doRotation)
  5730. {
  5731. if (tickLabelRotation > 0)
  5732. {
  5733. x = +qSin(radians)*labelData.totalBounds.height();
  5734. y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0;
  5735. } else
  5736. {
  5737. x = 0;
  5738. y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0;
  5739. }
  5740. } else
  5741. {
  5742. x = 0;
  5743. y = -labelData.totalBounds.height()/2.0;
  5744. }
  5745. } else if (type == QCPAxis::atTop)
  5746. {
  5747. if (doRotation)
  5748. {
  5749. if (tickLabelRotation > 0)
  5750. {
  5751. x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0;
  5752. y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height();
  5753. } else
  5754. {
  5755. x = -qSin(-radians)*labelData.totalBounds.height()/2.0;
  5756. y = -qCos(-radians)*labelData.totalBounds.height();
  5757. }
  5758. } else
  5759. {
  5760. x = -labelData.totalBounds.width()/2.0;
  5761. y = -labelData.totalBounds.height();
  5762. }
  5763. } else if (type == QCPAxis::atBottom)
  5764. {
  5765. if (doRotation)
  5766. {
  5767. if (tickLabelRotation > 0)
  5768. {
  5769. x = +qSin(radians)*labelData.totalBounds.height()/2.0;
  5770. y = 0;
  5771. } else
  5772. {
  5773. x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0;
  5774. y = +qSin(-radians)*labelData.totalBounds.width();
  5775. }
  5776. } else
  5777. {
  5778. x = -labelData.totalBounds.width()/2.0;
  5779. y = 0;
  5780. }
  5781. }
  5782. return QPointF(x, y);
  5783. }
  5784. /*! \internal
  5785. Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label
  5786. to be drawn, depending on number format etc. Since only the largest tick label is wanted for the
  5787. margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a
  5788. smaller width/height.
  5789. */
  5790. void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const
  5791. {
  5792. // note: this function must return the same tick label sizes as the placeTickLabel function.
  5793. QSize finalSize;
  5794. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label
  5795. {
  5796. const CachedLabel *cachedLabel = mLabelCache.object(text);
  5797. finalSize = cachedLabel->pixmap.size();
  5798. } else // label caching disabled or no label with this text cached:
  5799. {
  5800. TickLabelData labelData = getTickLabelData(font, text);
  5801. finalSize = labelData.rotatedTotalBounds.size();
  5802. }
  5803. // expand passed tickLabelsSize if current tick label is larger:
  5804. if (finalSize.width() > tickLabelsSize->width())
  5805. tickLabelsSize->setWidth(finalSize.width());
  5806. if (finalSize.height() > tickLabelsSize->height())
  5807. tickLabelsSize->setHeight(finalSize.height());
  5808. }
  5809. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5810. //////////////////// QCPAbstractPlottable
  5811. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5812. /*! \class QCPAbstractPlottable
  5813. \brief The abstract base class for all data representing objects in a plot.
  5814. It defines a very basic interface like name, pen, brush, visibility etc. Since this class is
  5815. abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to
  5816. create new ways of displaying data (see "Creating own plottables" below).
  5817. All further specifics are in the subclasses, for example:
  5818. \li A normal graph with possibly a line, scatter points and error bars is displayed by \ref QCPGraph
  5819. (typically created with \ref QCustomPlot::addGraph).
  5820. \li A parametric curve can be displayed with \ref QCPCurve.
  5821. \li A stackable bar chart can be achieved with \ref QCPBars.
  5822. \li A box of a statistical box plot is created with \ref QCPStatisticalBox.
  5823. \section plottables-subclassing Creating own plottables
  5824. To create an own plottable, you implement a subclass of QCPAbstractPlottable. These are the pure
  5825. virtual functions, you must implement:
  5826. \li \ref clearData
  5827. \li \ref selectTest
  5828. \li \ref draw
  5829. \li \ref drawLegendIcon
  5830. \li \ref getKeyRange
  5831. \li \ref getValueRange
  5832. See the documentation of those functions for what they need to do.
  5833. For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot
  5834. coordinates to pixel coordinates. This function is quite convenient, because it takes the
  5835. orientation of the key and value axes into account for you (x and y are swapped when the key axis
  5836. is vertical and the value axis horizontal). If you are worried about performance (i.e. you need
  5837. to translate many points in a loop like QCPGraph), you can directly use \ref
  5838. QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis
  5839. yourself.
  5840. Here are some important members you inherit from QCPAbstractPlottable:
  5841. <table>
  5842. <tr>
  5843. <td>QCustomPlot *\b mParentPlot</td>
  5844. <td>A pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.</td>
  5845. </tr><tr>
  5846. <td>QString \b mName</td>
  5847. <td>The name of the plottable.</td>
  5848. </tr><tr>
  5849. <td>QPen \b mPen</td>
  5850. <td>The generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable (e.g QCPGraph uses this pen for its graph lines and scatters)</td>
  5851. </tr><tr>
  5852. <td>QPen \b mSelectedPen</td>
  5853. <td>The generic pen that should be used when the plottable is selected (hint: \ref mainPen gives you the right pen, depending on selection state).</td>
  5854. </tr><tr>
  5855. <td>QBrush \b mBrush</td>
  5856. <td>The generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable (e.g. QCPGraph uses this brush to control filling under the graph)</td>
  5857. </tr><tr>
  5858. <td>QBrush \b mSelectedBrush</td>
  5859. <td>The generic brush that should be used when the plottable is selected (hint: \ref mainBrush gives you the right brush, depending on selection state).</td>
  5860. </tr><tr>
  5861. <td>QPointer<QCPAxis>\b mKeyAxis, \b mValueAxis</td>
  5862. <td>The key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates to pixels in either the key or value dimension.
  5863. Make sure to check whether the pointer is null before using it. If one of the axes is null, don't draw the plottable.</td>
  5864. </tr><tr>
  5865. <td>bool \b mSelected</td>
  5866. <td>indicates whether the plottable is selected or not.</td>
  5867. </tr>
  5868. </table>
  5869. */
  5870. /* start of documentation of pure virtual functions */
  5871. /*! \fn void QCPAbstractPlottable::clearData() = 0
  5872. Clears all data in the plottable.
  5873. */
  5874. /*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0
  5875. \internal
  5876. called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation
  5877. of this plottable inside \a rect, next to the plottable name.
  5878. */
  5879. /*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, SignDomain inSignDomain) const = 0
  5880. \internal
  5881. called by rescaleAxes functions to get the full data key bounds. For logarithmic plots, one can
  5882. set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the
  5883. returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain
  5884. to \ref sdNegative and all positive points will be ignored for range calculation. For no
  5885. restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output
  5886. parameter that indicates whether a range could be found or not. If this is false, you shouldn't
  5887. use the returned range (e.g. no points in data).
  5888. Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
  5889. this function may have size zero, which wouldn't count as a valid range.
  5890. \see rescaleAxes, getValueRange
  5891. */
  5892. /*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, SignDomain inSignDomain) const = 0
  5893. \internal
  5894. called by rescaleAxes functions to get the full data value bounds. For logarithmic plots, one can
  5895. set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the
  5896. returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain
  5897. to \ref sdNegative and all positive points will be ignored for range calculation. For no
  5898. restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output
  5899. parameter that indicates whether a range could be found or not. If this is false, you shouldn't
  5900. use the returned range (e.g. no points in data).
  5901. Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
  5902. this function may have size zero, which wouldn't count as a valid range.
  5903. \see rescaleAxes, getKeyRange
  5904. */
  5905. /* end of documentation of pure virtual functions */
  5906. /* start of documentation of signals */
  5907. /*! \fn void QCPAbstractPlottable::selectionChanged(bool selected)
  5908. This signal is emitted when the selection state of this plottable has changed, either by user
  5909. interaction or by a direct call to \ref setSelected.
  5910. */
  5911. /*! \fn void QCPAbstractPlottable::selectableChanged(bool selectable);
  5912. This signal is emitted when the selectability of this plottable has changed.
  5913. \see setSelectable
  5914. */
  5915. /* end of documentation of signals */
  5916. /*!
  5917. Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as
  5918. its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance
  5919. and have perpendicular orientations. If either of these restrictions is violated, a corresponding
  5920. message is printed to the debug output (qDebug), the construction is not aborted, though.
  5921. Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables,
  5922. it can't be directly instantiated.
  5923. You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead.
  5924. */
  5925. QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  5926. QCPLayerable(keyAxis->parentPlot(), "", keyAxis->axisRect()),
  5927. mName(""),
  5928. mAntialiasedFill(true),
  5929. mAntialiasedScatters(true),
  5930. mAntialiasedErrorBars(false),
  5931. mPen(Qt::black),
  5932. mSelectedPen(Qt::black),
  5933. mBrush(Qt::NoBrush),
  5934. mSelectedBrush(Qt::NoBrush),
  5935. mKeyAxis(keyAxis),
  5936. mValueAxis(valueAxis),
  5937. mSelectable(true),
  5938. mSelected(false)
  5939. {
  5940. if (keyAxis->parentPlot() != valueAxis->parentPlot())
  5941. qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
  5942. if (keyAxis->orientation() == valueAxis->orientation())
  5943. qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other.";
  5944. }
  5945. /*!
  5946. The name is the textual representation of this plottable as it is displayed in the legend
  5947. (\ref QCPLegend). It may contain any UTF-8 characters, including newlines.
  5948. */
  5949. void QCPAbstractPlottable::setName(const QString &name)
  5950. {
  5951. mName = name;
  5952. }
  5953. /*!
  5954. Sets whether fills of this plottable is drawn antialiased or not.
  5955. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  5956. QCustomPlot::setNotAntialiasedElements.
  5957. */
  5958. void QCPAbstractPlottable::setAntialiasedFill(bool enabled)
  5959. {
  5960. mAntialiasedFill = enabled;
  5961. }
  5962. /*!
  5963. Sets whether the scatter symbols of this plottable are drawn antialiased or not.
  5964. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  5965. QCustomPlot::setNotAntialiasedElements.
  5966. */
  5967. void QCPAbstractPlottable::setAntialiasedScatters(bool enabled)
  5968. {
  5969. mAntialiasedScatters = enabled;
  5970. }
  5971. /*!
  5972. Sets whether the error bars of this plottable are drawn antialiased or not.
  5973. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  5974. QCustomPlot::setNotAntialiasedElements.
  5975. */
  5976. void QCPAbstractPlottable::setAntialiasedErrorBars(bool enabled)
  5977. {
  5978. mAntialiasedErrorBars = enabled;
  5979. }
  5980. /*!
  5981. The pen is used to draw basic lines that make up the plottable representation in the
  5982. plot.
  5983. For example, the \ref QCPGraph subclass draws its graph lines and scatter points
  5984. with this pen.
  5985. \see setBrush
  5986. */
  5987. void QCPAbstractPlottable::setPen(const QPen &pen)
  5988. {
  5989. mPen = pen;
  5990. }
  5991. /*!
  5992. When the plottable is selected, this pen is used to draw basic lines instead of the normal
  5993. pen set via \ref setPen.
  5994. \see setSelected, setSelectable, setSelectedBrush, selectTest
  5995. */
  5996. void QCPAbstractPlottable::setSelectedPen(const QPen &pen)
  5997. {
  5998. mSelectedPen = pen;
  5999. }
  6000. /*!
  6001. The brush is used to draw basic fills of the plottable representation in the
  6002. plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
  6003. For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when
  6004. it's not set to Qt::NoBrush.
  6005. \see setPen
  6006. */
  6007. void QCPAbstractPlottable::setBrush(const QBrush &brush)
  6008. {
  6009. mBrush = brush;
  6010. }
  6011. /*!
  6012. When the plottable is selected, this brush is used to draw fills instead of the normal
  6013. brush set via \ref setBrush.
  6014. \see setSelected, setSelectable, setSelectedPen, selectTest
  6015. */
  6016. void QCPAbstractPlottable::setSelectedBrush(const QBrush &brush)
  6017. {
  6018. mSelectedBrush = brush;
  6019. }
  6020. /*!
  6021. The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
  6022. to the plottable's value axis. This function performs no checks to make sure this is the case.
  6023. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
  6024. y-axis (QCustomPlot::yAxis) as value axis.
  6025. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  6026. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  6027. \see setValueAxis
  6028. */
  6029. void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis)
  6030. {
  6031. mKeyAxis = axis;
  6032. }
  6033. /*!
  6034. The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is
  6035. orthogonal to the plottable's key axis. This function performs no checks to make sure this is the
  6036. case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and
  6037. the y-axis (QCustomPlot::yAxis) as value axis.
  6038. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  6039. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  6040. \see setKeyAxis
  6041. */
  6042. void QCPAbstractPlottable::setValueAxis(QCPAxis *axis)
  6043. {
  6044. mValueAxis = axis;
  6045. }
  6046. /*!
  6047. Sets whether the user can (de-)select this plottable by clicking on the QCustomPlot surface.
  6048. (When \ref QCustomPlot::setInteractions contains iSelectPlottables.)
  6049. However, even when \a selectable was set to false, it is possible to set the selection manually,
  6050. by calling \ref setSelected directly.
  6051. \see setSelected
  6052. */
  6053. void QCPAbstractPlottable::setSelectable(bool selectable)
  6054. {
  6055. if (mSelectable != selectable)
  6056. {
  6057. mSelectable = selectable;
  6058. emit selectableChanged(mSelectable);
  6059. }
  6060. }
  6061. /*!
  6062. Sets whether this plottable is selected or not. When selected, it uses a different pen and brush
  6063. to draw its lines and fills, see \ref setSelectedPen and \ref setSelectedBrush.
  6064. The entire selection mechanism for plottables is handled automatically when \ref
  6065. QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
  6066. you wish to change the selection state manually.
  6067. This function can change the selection state even when \ref setSelectable was set to false.
  6068. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  6069. \see setSelectable, selectTest
  6070. */
  6071. void QCPAbstractPlottable::setSelected(bool selected)
  6072. {
  6073. if (mSelected != selected)
  6074. {
  6075. mSelected = selected;
  6076. emit selectionChanged(mSelected);
  6077. }
  6078. }
  6079. /*!
  6080. Rescales the key and value axes associated with this plottable to contain all displayed data, so
  6081. the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make
  6082. sure not to rescale to an illegal range i.e. a range containing different signs and/or zero.
  6083. Instead it will stay in the current sign domain and ignore all parts of the plottable that lie
  6084. outside of that domain.
  6085. \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show
  6086. multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has
  6087. \a onlyEnlarge set to false (the default), and all subsequent set to true.
  6088. \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale
  6089. */
  6090. void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const
  6091. {
  6092. rescaleKeyAxis(onlyEnlarge);
  6093. rescaleValueAxis(onlyEnlarge);
  6094. }
  6095. /*!
  6096. Rescales the key axis of the plottable so the whole plottable is visible.
  6097. See \ref rescaleAxes for detailed behaviour.
  6098. */
  6099. void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const
  6100. {
  6101. QCPAxis *keyAxis = mKeyAxis.data();
  6102. if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
  6103. SignDomain signDomain = sdBoth;
  6104. if (keyAxis->scaleType() == QCPAxis::stLogarithmic)
  6105. signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive);
  6106. bool foundRange;
  6107. QCPRange newRange = getKeyRange(foundRange, signDomain);
  6108. if (foundRange)
  6109. {
  6110. if (onlyEnlarge)
  6111. newRange.expand(keyAxis->range());
  6112. 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
  6113. {
  6114. 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
  6115. if (keyAxis->scaleType() == QCPAxis::stLinear)
  6116. {
  6117. newRange.lower = center-keyAxis->range().size()/2.0;
  6118. newRange.upper = center+keyAxis->range().size()/2.0;
  6119. } else // scaleType() == stLogarithmic
  6120. {
  6121. newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower);
  6122. newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower);
  6123. }
  6124. }
  6125. keyAxis->setRange(newRange);
  6126. }
  6127. }
  6128. /*!
  6129. Rescales the value axis of the plottable so the whole plottable is visible.
  6130. Returns true if the axis was actually scaled. This might not be the case if this plottable has an
  6131. invalid range, e.g. because it has no data points.
  6132. See \ref rescaleAxes for detailed behaviour.
  6133. */
  6134. void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge) const
  6135. {
  6136. QCPAxis *valueAxis = mValueAxis.data();
  6137. if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; }
  6138. SignDomain signDomain = sdBoth;
  6139. if (valueAxis->scaleType() == QCPAxis::stLogarithmic)
  6140. signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive);
  6141. bool foundRange;
  6142. QCPRange newRange = getValueRange(foundRange, signDomain);
  6143. if (foundRange)
  6144. {
  6145. if (onlyEnlarge)
  6146. newRange.expand(valueAxis->range());
  6147. 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
  6148. {
  6149. 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
  6150. if (valueAxis->scaleType() == QCPAxis::stLinear)
  6151. {
  6152. newRange.lower = center-valueAxis->range().size()/2.0;
  6153. newRange.upper = center+valueAxis->range().size()/2.0;
  6154. } else // scaleType() == stLogarithmic
  6155. {
  6156. newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  6157. newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  6158. }
  6159. }
  6160. valueAxis->setRange(newRange);
  6161. }
  6162. }
  6163. /*!
  6164. Adds this plottable to the legend of the parent QCustomPlot (QCustomPlot::legend).
  6165. Normally, a QCPPlottableLegendItem is created and inserted into the legend. If the plottable
  6166. needs a more specialized representation in the legend, this function will take this into account
  6167. and instead create the specialized subclass of QCPAbstractLegendItem.
  6168. Returns true on success, i.e. when the legend exists and a legend item associated with this plottable isn't already in
  6169. the legend.
  6170. \see removeFromLegend, QCPLegend::addItem
  6171. */
  6172. bool QCPAbstractPlottable::addToLegend()
  6173. {
  6174. if (!mParentPlot || !mParentPlot->legend)
  6175. return false;
  6176. if (!mParentPlot->legend->hasItemWithPlottable(this))
  6177. {
  6178. mParentPlot->legend->addItem(new QCPPlottableLegendItem(mParentPlot->legend, this));
  6179. return true;
  6180. } else
  6181. return false;
  6182. }
  6183. /*!
  6184. Removes the plottable from the legend of the parent QCustomPlot. This means the
  6185. QCPAbstractLegendItem (usually a QCPPlottableLegendItem) that is associated with this plottable
  6186. is removed.
  6187. Returns true on success, i.e. if the legend exists and a legend item associated with this
  6188. plottable was found and removed.
  6189. \see addToLegend, QCPLegend::removeItem
  6190. */
  6191. bool QCPAbstractPlottable::removeFromLegend() const
  6192. {
  6193. if (!mParentPlot->legend)
  6194. return false;
  6195. if (QCPPlottableLegendItem *lip = mParentPlot->legend->itemWithPlottable(this))
  6196. return mParentPlot->legend->removeItem(lip);
  6197. else
  6198. return false;
  6199. }
  6200. /* inherits documentation from base class */
  6201. QRect QCPAbstractPlottable::clipRect() const
  6202. {
  6203. if (mKeyAxis && mValueAxis)
  6204. return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect();
  6205. else
  6206. return QRect();
  6207. }
  6208. /* inherits documentation from base class */
  6209. QCP::Interaction QCPAbstractPlottable::selectionCategory() const
  6210. {
  6211. return QCP::iSelectPlottables;
  6212. }
  6213. /*! \internal
  6214. Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface,
  6215. taking the orientations of the axes associated with this plottable into account (e.g. whether key
  6216. represents x or y).
  6217. \a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y.
  6218. \see pixelsToCoords, QCPAxis::coordToPixel
  6219. */
  6220. void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const
  6221. {
  6222. QCPAxis *keyAxis = mKeyAxis.data();
  6223. QCPAxis *valueAxis = mValueAxis.data();
  6224. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  6225. if (keyAxis->orientation() == Qt::Horizontal)
  6226. {
  6227. x = keyAxis->coordToPixel(key);
  6228. y = valueAxis->coordToPixel(value);
  6229. } else
  6230. {
  6231. y = keyAxis->coordToPixel(key);
  6232. x = valueAxis->coordToPixel(value);
  6233. }
  6234. }
  6235. /*! \internal
  6236. \overload
  6237. Returns the input as pixel coordinates in a QPointF.
  6238. */
  6239. const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const
  6240. {
  6241. QCPAxis *keyAxis = mKeyAxis.data();
  6242. QCPAxis *valueAxis = mValueAxis.data();
  6243. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
  6244. if (keyAxis->orientation() == Qt::Horizontal)
  6245. return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value));
  6246. else
  6247. return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key));
  6248. }
  6249. /*! \internal
  6250. Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates,
  6251. taking the orientations of the axes associated with this plottable into account (e.g. whether key
  6252. represents x or y).
  6253. \a x and \a y are transformed to the plot coodinates and are written to \a key and \a value.
  6254. \see coordsToPixels, QCPAxis::coordToPixel
  6255. */
  6256. void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const
  6257. {
  6258. QCPAxis *keyAxis = mKeyAxis.data();
  6259. QCPAxis *valueAxis = mValueAxis.data();
  6260. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  6261. if (keyAxis->orientation() == Qt::Horizontal)
  6262. {
  6263. key = keyAxis->pixelToCoord(x);
  6264. value = valueAxis->pixelToCoord(y);
  6265. } else
  6266. {
  6267. key = keyAxis->pixelToCoord(y);
  6268. value = valueAxis->pixelToCoord(x);
  6269. }
  6270. }
  6271. /*! \internal
  6272. \overload
  6273. Returns the pixel input \a pixelPos as plot coordinates \a key and \a value.
  6274. */
  6275. void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
  6276. {
  6277. pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value);
  6278. }
  6279. /*! \internal
  6280. Returns the pen that should be used for drawing lines of the plottable. Returns mPen when the
  6281. graph is not selected and mSelectedPen when it is.
  6282. */
  6283. QPen QCPAbstractPlottable::mainPen() const
  6284. {
  6285. return mSelected ? mSelectedPen : mPen;
  6286. }
  6287. /*! \internal
  6288. Returns the brush that should be used for drawing fills of the plottable. Returns mBrush when the
  6289. graph is not selected and mSelectedBrush when it is.
  6290. */
  6291. QBrush QCPAbstractPlottable::mainBrush() const
  6292. {
  6293. return mSelected ? mSelectedBrush : mBrush;
  6294. }
  6295. /*! \internal
  6296. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  6297. before drawing plottable lines.
  6298. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  6299. This function takes into account the local setting of the antialiasing flag as well as the
  6300. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  6301. QCustomPlot::setNotAntialiasedElements.
  6302. \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint
  6303. */
  6304. void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const
  6305. {
  6306. applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables);
  6307. }
  6308. /*! \internal
  6309. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  6310. before drawing plottable fills.
  6311. This function takes into account the local setting of the antialiasing flag as well as the
  6312. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  6313. QCustomPlot::setNotAntialiasedElements.
  6314. \see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint
  6315. */
  6316. void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const
  6317. {
  6318. applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills);
  6319. }
  6320. /*! \internal
  6321. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  6322. before drawing plottable scatter points.
  6323. This function takes into account the local setting of the antialiasing flag as well as the
  6324. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  6325. QCustomPlot::setNotAntialiasedElements.
  6326. \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint, applyErrorBarsAntialiasingHint
  6327. */
  6328. void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const
  6329. {
  6330. applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
  6331. }
  6332. /*! \internal
  6333. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  6334. before drawing plottable error bars.
  6335. This function takes into account the local setting of the antialiasing flag as well as the
  6336. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  6337. QCustomPlot::setNotAntialiasedElements.
  6338. \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyDefaultAntialiasingHint
  6339. */
  6340. void QCPAbstractPlottable::applyErrorBarsAntialiasingHint(QCPPainter *painter) const
  6341. {
  6342. applyAntialiasingHint(painter, mAntialiasedErrorBars, QCP::aeErrorBars);
  6343. }
  6344. /*! \internal
  6345. Finds the shortest squared distance of \a point to the line segment defined by \a start and \a
  6346. end.
  6347. This function may be used to help with the implementation of the \ref selectTest function for
  6348. specific plottables.
  6349. \note This function is identical to QCPAbstractItem::distSqrToLine
  6350. */
  6351. double QCPAbstractPlottable::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const
  6352. {
  6353. QVector2D a(start);
  6354. QVector2D b(end);
  6355. QVector2D p(point);
  6356. QVector2D v(b-a);
  6357. double vLengthSqr = v.lengthSquared();
  6358. if (!qFuzzyIsNull(vLengthSqr))
  6359. {
  6360. double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr;
  6361. if (mu < 0)
  6362. return (a-p).lengthSquared();
  6363. else if (mu > 1)
  6364. return (b-p).lengthSquared();
  6365. else
  6366. return ((a + mu*v)-p).lengthSquared();
  6367. } else
  6368. return (a-p).lengthSquared();
  6369. }
  6370. /* inherits documentation from base class */
  6371. void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  6372. {
  6373. Q_UNUSED(event)
  6374. Q_UNUSED(details)
  6375. if (mSelectable)
  6376. {
  6377. bool selBefore = mSelected;
  6378. setSelected(additive ? !mSelected : true);
  6379. if (selectionStateChanged)
  6380. *selectionStateChanged = mSelected != selBefore;
  6381. }
  6382. }
  6383. /* inherits documentation from base class */
  6384. void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged)
  6385. {
  6386. if (mSelectable)
  6387. {
  6388. bool selBefore = mSelected;
  6389. setSelected(false);
  6390. if (selectionStateChanged)
  6391. *selectionStateChanged = mSelected != selBefore;
  6392. }
  6393. }
  6394. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6395. //////////////////// QCPItemAnchor
  6396. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6397. /*! \class QCPItemAnchor
  6398. \brief An anchor of an item to which positions can be attached to.
  6399. An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't
  6400. control anything on its item, but provides a way to tie other items via their positions to the
  6401. anchor.
  6402. For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight.
  6403. Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can
  6404. attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by
  6405. calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the
  6406. QCPItemRect. This way the start of the line will now always follow the respective anchor location
  6407. on the rect item.
  6408. Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an
  6409. anchor to other positions.
  6410. To learn how to provide anchors in your own item subclasses, see the subclassing section of the
  6411. QCPAbstractItem documentation.
  6412. */
  6413. /* start documentation of inline functions */
  6414. /*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition()
  6415. Returns 0 if this instance is merely a QCPItemAnchor, and a valid pointer of type QCPItemPosition* if
  6416. it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor).
  6417. This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids
  6418. dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with
  6419. gcc compiler).
  6420. */
  6421. /* end documentation of inline functions */
  6422. /*!
  6423. Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if
  6424. you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as
  6425. explained in the subclassing section of the QCPAbstractItem documentation.
  6426. */
  6427. QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId) :
  6428. mName(name),
  6429. mParentPlot(parentPlot),
  6430. mParentItem(parentItem),
  6431. mAnchorId(anchorId)
  6432. {
  6433. }
  6434. QCPItemAnchor::~QCPItemAnchor()
  6435. {
  6436. // unregister as parent at children:
  6437. QList<QCPItemPosition*> currentChildren(mChildren.toList());
  6438. for (int i=0; i<currentChildren.size(); ++i)
  6439. currentChildren.at(i)->setParentAnchor(0); // this acts back on this anchor and child removes itself from mChildren
  6440. }
  6441. /*!
  6442. Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface.
  6443. The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the
  6444. parent item, QCPItemAnchor is just an intermediary.
  6445. */
  6446. QPointF QCPItemAnchor::pixelPoint() const
  6447. {
  6448. if (mParentItem)
  6449. {
  6450. if (mAnchorId > -1)
  6451. {
  6452. return mParentItem->anchorPixelPoint(mAnchorId);
  6453. } else
  6454. {
  6455. qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId;
  6456. return QPointF();
  6457. }
  6458. } else
  6459. {
  6460. qDebug() << Q_FUNC_INFO << "no parent item set";
  6461. return QPointF();
  6462. }
  6463. }
  6464. /*! \internal
  6465. Adds \a pos to the child list of this anchor. This is necessary to notify the children prior to
  6466. destruction of the anchor.
  6467. Note that this function does not change the parent setting in \a pos.
  6468. */
  6469. void QCPItemAnchor::addChild(QCPItemPosition *pos)
  6470. {
  6471. if (!mChildren.contains(pos))
  6472. mChildren.insert(pos);
  6473. else
  6474. qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
  6475. }
  6476. /*! \internal
  6477. Removes \a pos from the child list of this anchor.
  6478. Note that this function does not change the parent setting in \a pos.
  6479. */
  6480. void QCPItemAnchor::removeChild(QCPItemPosition *pos)
  6481. {
  6482. if (!mChildren.remove(pos))
  6483. qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
  6484. }
  6485. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6486. //////////////////// QCPItemPosition
  6487. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6488. /*! \class QCPItemPosition
  6489. \brief Manages the position of an item.
  6490. Every item has at least one public QCPItemPosition member pointer which provides ways to position the
  6491. item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two:
  6492. \a topLeft and \a bottomRight.
  6493. QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type defines
  6494. how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel coordinates, as
  6495. plot coordinates of certain axes, etc.
  6496. Further, QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. (Note that every
  6497. QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent anchor for other
  6498. positions.) This way you can tie multiple items together. If the QCPItemPosition has a parent, the
  6499. coordinates set with \ref setCoords are considered to be absolute values in the reference frame of the
  6500. parent anchor, where (0, 0) means directly ontop of the parent anchor. For example, You could attach
  6501. the \a start position of a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting
  6502. point of the line always be centered under the text label, no matter where the text is moved to, or is
  6503. itself tied to.
  6504. To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPoint. This
  6505. works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref
  6506. setPixelPoint transforms the coordinates appropriately, to make the position appear at the specified
  6507. pixel values.
  6508. */
  6509. /*!
  6510. Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if
  6511. you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as
  6512. explained in the subclassing section of the QCPAbstractItem documentation.
  6513. */
  6514. QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name) :
  6515. QCPItemAnchor(parentPlot, parentItem, name),
  6516. mPositionType(ptAbsolute),
  6517. mKey(0),
  6518. mValue(0),
  6519. mParentAnchor(0)
  6520. {
  6521. }
  6522. QCPItemPosition::~QCPItemPosition()
  6523. {
  6524. // unregister as parent at children:
  6525. // Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then
  6526. // the setParentAnchor(0) call the correct QCPItemPosition::pixelPoint function instead of QCPItemAnchor::pixelPoint
  6527. QList<QCPItemPosition*> currentChildren(mChildren.toList());
  6528. for (int i=0; i<currentChildren.size(); ++i)
  6529. currentChildren.at(i)->setParentAnchor(0); // this acts back on this anchor and child removes itself from mChildren
  6530. // unregister as child in parent:
  6531. if (mParentAnchor)
  6532. mParentAnchor->removeChild(this);
  6533. }
  6534. /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
  6535. QCPAxisRect *QCPItemPosition::axisRect() const
  6536. {
  6537. return mAxisRect.data();
  6538. }
  6539. /*!
  6540. Sets the type of the position. The type defines how the coordinates passed to \ref setCoords
  6541. should be handled and how the QCPItemPosition should behave in the plot.
  6542. The possible values for \a type can be separated in two main categories:
  6543. \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords
  6544. and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes.
  6545. By default, the QCustomPlot's x- and yAxis are used.
  6546. \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This
  6547. corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref
  6548. ptAxisRectRatio. They differ only in the way the absolute position is described, see the
  6549. documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify
  6550. the axis rect with \ref setAxisRect. By default this is set to the main axis rect.
  6551. Note that the position type \ref ptPlotCoords is only available (and sensible) when the position
  6552. has no parent anchor (\ref setParentAnchor).
  6553. If the type is changed, the apparent pixel position on the plot is preserved. This means
  6554. the coordinates as retrieved with coords() and set with \ref setCoords may change in the process.
  6555. */
  6556. void QCPItemPosition::setType(QCPItemPosition::PositionType type)
  6557. {
  6558. if (mPositionType != type)
  6559. {
  6560. // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
  6561. // were deleted), don't try to recover the pixelPoint() because it would output a qDebug warning.
  6562. bool recoverPixelPosition = true;
  6563. if ((mPositionType == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
  6564. recoverPixelPosition = false;
  6565. if ((mPositionType == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
  6566. recoverPixelPosition = false;
  6567. QPointF pixelP;
  6568. if (recoverPixelPosition)
  6569. pixelP = pixelPoint();
  6570. mPositionType = type;
  6571. if (recoverPixelPosition)
  6572. setPixelPoint(pixelP);
  6573. }
  6574. }
  6575. /*!
  6576. Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now
  6577. follow any position changes of the anchor. The local coordinate system of positions with a parent
  6578. anchor always is absolute with (0, 0) being exactly on top of the parent anchor. (Hence the type
  6579. shouldn't be \ref ptPlotCoords for positions with parent anchors.)
  6580. if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved
  6581. during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position
  6582. will be exactly on top of the parent anchor.
  6583. To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to 0.
  6584. If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is
  6585. set to \ref ptAbsolute, to keep the position in a valid state.
  6586. */
  6587. bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
  6588. {
  6589. // make sure self is not assigned as parent:
  6590. if (parentAnchor == this)
  6591. {
  6592. qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
  6593. return false;
  6594. }
  6595. // make sure no recursive parent-child-relationships are created:
  6596. QCPItemAnchor *currentParent = parentAnchor;
  6597. while (currentParent)
  6598. {
  6599. if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
  6600. {
  6601. // is a QCPItemPosition, might have further parent, so keep iterating
  6602. if (currentParentPos == this)
  6603. {
  6604. qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
  6605. return false;
  6606. }
  6607. currentParent = currentParentPos->mParentAnchor;
  6608. } else
  6609. {
  6610. // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
  6611. // same, to prevent a position being child of an anchor which itself depends on the position,
  6612. // because they're both on the same item:
  6613. if (currentParent->mParentItem == mParentItem)
  6614. {
  6615. qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
  6616. return false;
  6617. }
  6618. break;
  6619. }
  6620. }
  6621. // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
  6622. if (!mParentAnchor && mPositionType == ptPlotCoords)
  6623. setType(ptAbsolute);
  6624. // save pixel position:
  6625. QPointF pixelP;
  6626. if (keepPixelPosition)
  6627. pixelP = pixelPoint();
  6628. // unregister at current parent anchor:
  6629. if (mParentAnchor)
  6630. mParentAnchor->removeChild(this);
  6631. // register at new parent anchor:
  6632. if (parentAnchor)
  6633. parentAnchor->addChild(this);
  6634. mParentAnchor = parentAnchor;
  6635. // restore pixel position under new parent:
  6636. if (keepPixelPosition)
  6637. setPixelPoint(pixelP);
  6638. else
  6639. setCoords(0, 0);
  6640. return true;
  6641. }
  6642. /*!
  6643. Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type
  6644. (\ref setType).
  6645. For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position
  6646. on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the
  6647. QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the
  6648. plot coordinate system defined by the axes set by \ref setAxes. By default those are the
  6649. QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available
  6650. coordinate types and their meaning.
  6651. \see setPixelPoint
  6652. */
  6653. void QCPItemPosition::setCoords(double key, double value)
  6654. {
  6655. mKey = key;
  6656. mValue = value;
  6657. }
  6658. /*! \overload
  6659. Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the
  6660. meaning of \a value of the \ref setCoords(double key, double value) method.
  6661. */
  6662. void QCPItemPosition::setCoords(const QPointF &pos)
  6663. {
  6664. setCoords(pos.x(), pos.y());
  6665. }
  6666. /*!
  6667. Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It
  6668. includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor).
  6669. \see setPixelPoint
  6670. */
  6671. QPointF QCPItemPosition::pixelPoint() const
  6672. {
  6673. switch (mPositionType)
  6674. {
  6675. case ptAbsolute:
  6676. {
  6677. if (mParentAnchor)
  6678. return QPointF(mKey, mValue) + mParentAnchor->pixelPoint();
  6679. else
  6680. return QPointF(mKey, mValue);
  6681. }
  6682. case ptViewportRatio:
  6683. {
  6684. if (mParentAnchor)
  6685. {
  6686. return QPointF(mKey*mParentPlot->viewport().width(),
  6687. mValue*mParentPlot->viewport().height()) + mParentAnchor->pixelPoint();
  6688. } else
  6689. {
  6690. return QPointF(mKey*mParentPlot->viewport().width(),
  6691. mValue*mParentPlot->viewport().height()) + mParentPlot->viewport().topLeft();
  6692. }
  6693. }
  6694. case ptAxisRectRatio:
  6695. {
  6696. if (mAxisRect)
  6697. {
  6698. if (mParentAnchor)
  6699. {
  6700. return QPointF(mKey*mAxisRect.data()->width(),
  6701. mValue*mAxisRect.data()->height()) + mParentAnchor->pixelPoint();
  6702. } else
  6703. {
  6704. return QPointF(mKey*mAxisRect.data()->width(),
  6705. mValue*mAxisRect.data()->height()) + mAxisRect.data()->topLeft();
  6706. }
  6707. } else
  6708. {
  6709. qDebug() << Q_FUNC_INFO << "No axis rect defined";
  6710. return QPointF(mKey, mValue);
  6711. }
  6712. }
  6713. case ptPlotCoords:
  6714. {
  6715. double x, y;
  6716. if (mKeyAxis && mValueAxis)
  6717. {
  6718. // both key and value axis are given, translate key/value to x/y coordinates:
  6719. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  6720. {
  6721. x = mKeyAxis.data()->coordToPixel(mKey);
  6722. y = mValueAxis.data()->coordToPixel(mValue);
  6723. } else
  6724. {
  6725. y = mKeyAxis.data()->coordToPixel(mKey);
  6726. x = mValueAxis.data()->coordToPixel(mValue);
  6727. }
  6728. } else if (mKeyAxis)
  6729. {
  6730. // only key axis is given, depending on orientation only transform x or y to key coordinate, other stays pixel:
  6731. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  6732. {
  6733. x = mKeyAxis.data()->coordToPixel(mKey);
  6734. y = mValue;
  6735. } else
  6736. {
  6737. y = mKeyAxis.data()->coordToPixel(mKey);
  6738. x = mValue;
  6739. }
  6740. } else if (mValueAxis)
  6741. {
  6742. // only value axis is given, depending on orientation only transform x or y to value coordinate, other stays pixel:
  6743. if (mValueAxis.data()->orientation() == Qt::Horizontal)
  6744. {
  6745. x = mValueAxis.data()->coordToPixel(mValue);
  6746. y = mKey;
  6747. } else
  6748. {
  6749. y = mValueAxis.data()->coordToPixel(mValue);
  6750. x = mKey;
  6751. }
  6752. } else
  6753. {
  6754. // no axis given, basically the same as if mPositionType were ptAbsolute
  6755. qDebug() << Q_FUNC_INFO << "No axes defined";
  6756. x = mKey;
  6757. y = mValue;
  6758. }
  6759. return QPointF(x, y);
  6760. }
  6761. }
  6762. return QPointF();
  6763. }
  6764. /*!
  6765. When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the
  6766. coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and
  6767. yAxis of the QCustomPlot.
  6768. */
  6769. void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis)
  6770. {
  6771. mKeyAxis = keyAxis;
  6772. mValueAxis = valueAxis;
  6773. }
  6774. /*!
  6775. When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the
  6776. coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of
  6777. the QCustomPlot.
  6778. */
  6779. void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect)
  6780. {
  6781. mAxisRect = axisRect;
  6782. }
  6783. /*!
  6784. Sets the apparent pixel position. This works no matter what type (\ref setType) this
  6785. QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed
  6786. appropriately, to make the position finally appear at the specified pixel values.
  6787. Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is
  6788. identical to that of \ref setCoords.
  6789. \see pixelPoint, setCoords
  6790. */
  6791. void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint)
  6792. {
  6793. switch (mPositionType)
  6794. {
  6795. case ptAbsolute:
  6796. {
  6797. if (mParentAnchor)
  6798. setCoords(pixelPoint-mParentAnchor->pixelPoint());
  6799. else
  6800. setCoords(pixelPoint);
  6801. break;
  6802. }
  6803. case ptViewportRatio:
  6804. {
  6805. if (mParentAnchor)
  6806. {
  6807. QPointF p(pixelPoint-mParentAnchor->pixelPoint());
  6808. p.rx() /= (double)mParentPlot->viewport().width();
  6809. p.ry() /= (double)mParentPlot->viewport().height();
  6810. setCoords(p);
  6811. } else
  6812. {
  6813. QPointF p(pixelPoint-mParentPlot->viewport().topLeft());
  6814. p.rx() /= (double)mParentPlot->viewport().width();
  6815. p.ry() /= (double)mParentPlot->viewport().height();
  6816. setCoords(p);
  6817. }
  6818. break;
  6819. }
  6820. case ptAxisRectRatio:
  6821. {
  6822. if (mAxisRect)
  6823. {
  6824. if (mParentAnchor)
  6825. {
  6826. QPointF p(pixelPoint-mParentAnchor->pixelPoint());
  6827. p.rx() /= (double)mAxisRect.data()->width();
  6828. p.ry() /= (double)mAxisRect.data()->height();
  6829. setCoords(p);
  6830. } else
  6831. {
  6832. QPointF p(pixelPoint-mAxisRect.data()->topLeft());
  6833. p.rx() /= (double)mAxisRect.data()->width();
  6834. p.ry() /= (double)mAxisRect.data()->height();
  6835. setCoords(p);
  6836. }
  6837. } else
  6838. {
  6839. qDebug() << Q_FUNC_INFO << "No axis rect defined";
  6840. setCoords(pixelPoint);
  6841. }
  6842. break;
  6843. }
  6844. case ptPlotCoords:
  6845. {
  6846. double newKey, newValue;
  6847. if (mKeyAxis && mValueAxis)
  6848. {
  6849. // both key and value axis are given, translate point to key/value coordinates:
  6850. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  6851. {
  6852. newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.x());
  6853. newValue = mValueAxis.data()->pixelToCoord(pixelPoint.y());
  6854. } else
  6855. {
  6856. newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.y());
  6857. newValue = mValueAxis.data()->pixelToCoord(pixelPoint.x());
  6858. }
  6859. } else if (mKeyAxis)
  6860. {
  6861. // only key axis is given, depending on orientation only transform x or y to key coordinate, other stays pixel:
  6862. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  6863. {
  6864. newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.x());
  6865. newValue = pixelPoint.y();
  6866. } else
  6867. {
  6868. newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.y());
  6869. newValue = pixelPoint.x();
  6870. }
  6871. } else if (mValueAxis)
  6872. {
  6873. // only value axis is given, depending on orientation only transform x or y to value coordinate, other stays pixel:
  6874. if (mValueAxis.data()->orientation() == Qt::Horizontal)
  6875. {
  6876. newKey = pixelPoint.y();
  6877. newValue = mValueAxis.data()->pixelToCoord(pixelPoint.x());
  6878. } else
  6879. {
  6880. newKey = pixelPoint.x();
  6881. newValue = mValueAxis.data()->pixelToCoord(pixelPoint.y());
  6882. }
  6883. } else
  6884. {
  6885. // no axis given, basically the same as if mPositionType were ptAbsolute
  6886. qDebug() << Q_FUNC_INFO << "No axes defined";
  6887. newKey = pixelPoint.x();
  6888. newValue = pixelPoint.y();
  6889. }
  6890. setCoords(newKey, newValue);
  6891. break;
  6892. }
  6893. }
  6894. }
  6895. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6896. //////////////////// QCPAbstractItem
  6897. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6898. /*! \class QCPAbstractItem
  6899. \brief The abstract base class for all items in a plot.
  6900. In QCustomPlot, items are supplemental graphical elements that are neither plottables
  6901. (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus
  6902. plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each
  6903. specific item has at least one QCPItemPosition member which controls the positioning. Some items
  6904. are defined by more than one coordinate and thus have two or more QCPItemPosition members (For
  6905. example, QCPItemRect has \a topLeft and \a bottomRight).
  6906. This abstract base class defines a very basic interface like visibility and clipping. Since this
  6907. class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass
  6908. yourself to create new items.
  6909. The built-in items are:
  6910. <table>
  6911. <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>
  6912. <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>
  6913. <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>
  6914. <tr><td>QCPItemRect</td><td>A rectangle</td></tr>
  6915. <tr><td>QCPItemEllipse</td><td>An ellipse</td></tr>
  6916. <tr><td>QCPItemPixmap</td><td>An arbitrary pixmap</td></tr>
  6917. <tr><td>QCPItemText</td><td>A text label</td></tr>
  6918. <tr><td>QCPItemBracket</td><td>A bracket which may be used to reference/highlight certain parts in the plot.</td></tr>
  6919. <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>
  6920. </table>
  6921. Items are by default clipped to the main axis rect. To make an item visible outside that axis
  6922. rect, disable clipping via \ref setClipToAxisRect.
  6923. \section items-using Using items
  6924. First you instantiate the item you want to use and add it to the plot:
  6925. \code
  6926. QCPItemLine *line = new QCPItemLine(customPlot);
  6927. customPlot->addItem(line);
  6928. \endcode
  6929. by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just
  6930. set the plot coordinates where the line should start/end:
  6931. \code
  6932. line->start->setCoords(-0.1, 0.8);
  6933. line->end->setCoords(1.1, 0.2);
  6934. \endcode
  6935. If we don't want the line to be positioned in plot coordinates but a different coordinate system,
  6936. e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like this:
  6937. \code
  6938. line->start->setType(QCPItemPosition::ptAbsolute);
  6939. line->end->setType(QCPItemPosition::ptAbsolute);
  6940. \endcode
  6941. Then we can set the coordinates, this time in pixels:
  6942. \code
  6943. line->start->setCoords(100, 200);
  6944. line->end->setCoords(450, 320);
  6945. \endcode
  6946. \section items-subclassing Creating own items
  6947. To create an own item, you implement a subclass of QCPAbstractItem. These are the pure
  6948. virtual functions, you must implement:
  6949. \li \ref selectTest
  6950. \li \ref draw
  6951. See the documentation of those functions for what they need to do.
  6952. \subsection items-positioning Allowing the item to be positioned
  6953. As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall
  6954. have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add
  6955. a public member of type QCPItemPosition like so:
  6956. \code QCPItemPosition * const myPosition;\endcode
  6957. the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition
  6958. instance it points to, can be modified, of course).
  6959. The initialization of this pointer is made easy with the \ref createPosition function. Just assign
  6960. the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition
  6961. takes a string which is the name of the position, typically this is identical to the variable name.
  6962. For example, the constructor of QCPItemExample could look like this:
  6963. \code
  6964. QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) :
  6965. QCPAbstractItem(parentPlot),
  6966. myPosition(createPosition("myPosition"))
  6967. {
  6968. // other constructor code
  6969. }
  6970. \endcode
  6971. \subsection items-drawing The draw function
  6972. To give your item a visual representation, reimplement the \ref draw function and use the passed
  6973. QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the
  6974. position member(s) via \ref QCPItemPosition::pixelPoint.
  6975. To optimize performance you should calculate a bounding rect first (don't forget to take the pen
  6976. width into account), check whether it intersects the \ref clipRect, and only draw the item at all
  6977. if this is the case.
  6978. \subsection items-selection The selectTest function
  6979. Your implementation of the \ref selectTest function may use the helpers \ref distSqrToLine and
  6980. \ref rectSelectTest. With these, the implementation of the selection test becomes significantly
  6981. simpler for most items. See the documentation of \ref selectTest for what the function parameters
  6982. mean and what the function should return.
  6983. \subsection anchors Providing anchors
  6984. Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public
  6985. member, e.g.
  6986. \code QCPItemAnchor * const bottom;\endcode
  6987. and create it in the constructor with the \ref createAnchor function, assigning it a name and an
  6988. anchor id (an integer enumerating all anchors on the item, you may create an own enum for this).
  6989. Since anchors can be placed anywhere, relative to the item's position(s), your item needs to
  6990. provide the position of every anchor with the reimplementation of the \ref anchorPixelPoint(int
  6991. anchorId) function.
  6992. In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel
  6993. position when anything attached to the anchor needs to know the coordinates.
  6994. */
  6995. /* start of documentation of inline functions */
  6996. /*! \fn QList<QCPItemPosition*> QCPAbstractItem::positions() const
  6997. Returns all positions of the item in a list.
  6998. \see anchors, position
  6999. */
  7000. /*! \fn QList<QCPItemAnchor*> QCPAbstractItem::anchors() const
  7001. Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always
  7002. also an anchor, the list will also contain the positions of this item.
  7003. \see positions, anchor
  7004. */
  7005. /* end of documentation of inline functions */
  7006. /* start documentation of pure virtual functions */
  7007. /*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0
  7008. \internal
  7009. Draws this item with the provided \a painter.
  7010. The cliprect of the provided painter is set to the rect returned by \ref clipRect before this
  7011. function is called. The clipRect depends on the clipping settings defined by \ref
  7012. setClipToAxisRect and \ref setClipAxisRect.
  7013. */
  7014. /* end documentation of pure virtual functions */
  7015. /* start documentation of signals */
  7016. /*! \fn void QCPAbstractItem::selectionChanged(bool selected)
  7017. This signal is emitted when the selection state of this item has changed, either by user interaction
  7018. or by a direct call to \ref setSelected.
  7019. */
  7020. /* end documentation of signals */
  7021. /*!
  7022. Base class constructor which initializes base class members.
  7023. */
  7024. QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) :
  7025. QCPLayerable(parentPlot),
  7026. mClipToAxisRect(false),
  7027. mSelectable(true),
  7028. mSelected(false)
  7029. {
  7030. QList<QCPAxisRect*> rects = parentPlot->axisRects();
  7031. if (rects.size() > 0)
  7032. {
  7033. setClipToAxisRect(true);
  7034. setClipAxisRect(rects.first());
  7035. }
  7036. }
  7037. QCPAbstractItem::~QCPAbstractItem()
  7038. {
  7039. // don't delete mPositions because every position is also an anchor and thus in mAnchors
  7040. qDeleteAll(mAnchors);
  7041. }
  7042. /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
  7043. QCPAxisRect *QCPAbstractItem::clipAxisRect() const
  7044. {
  7045. return mClipAxisRect.data();
  7046. }
  7047. /*!
  7048. Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the
  7049. entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect.
  7050. \see setClipAxisRect
  7051. */
  7052. void QCPAbstractItem::setClipToAxisRect(bool clip)
  7053. {
  7054. mClipToAxisRect = clip;
  7055. if (mClipToAxisRect)
  7056. setParentLayerable(mClipAxisRect.data());
  7057. }
  7058. /*!
  7059. Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref
  7060. setClipToAxisRect is set to true.
  7061. \see setClipToAxisRect
  7062. */
  7063. void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect)
  7064. {
  7065. mClipAxisRect = rect;
  7066. if (mClipToAxisRect)
  7067. setParentLayerable(mClipAxisRect.data());
  7068. }
  7069. /*!
  7070. Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface.
  7071. (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.)
  7072. However, even when \a selectable was set to false, it is possible to set the selection manually,
  7073. by calling \ref setSelected.
  7074. \see QCustomPlot::setInteractions, setSelected
  7075. */
  7076. void QCPAbstractItem::setSelectable(bool selectable)
  7077. {
  7078. if (mSelectable != selectable)
  7079. {
  7080. mSelectable = selectable;
  7081. emit selectableChanged(mSelectable);
  7082. }
  7083. }
  7084. /*!
  7085. Sets whether this item is selected or not. When selected, it might use a different visual
  7086. appearance (e.g. pen and brush), this depends on the specific item though.
  7087. The entire selection mechanism for items is handled automatically when \ref
  7088. QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this
  7089. function when you wish to change the selection state manually.
  7090. This function can change the selection state even when \ref setSelectable was set to false.
  7091. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  7092. \see setSelectable, selectTest
  7093. */
  7094. void QCPAbstractItem::setSelected(bool selected)
  7095. {
  7096. if (mSelected != selected)
  7097. {
  7098. mSelected = selected;
  7099. emit selectionChanged(mSelected);
  7100. }
  7101. }
  7102. /*!
  7103. Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by
  7104. that name, returns 0.
  7105. This function provides an alternative way to access item positions. Normally, you access
  7106. positions direcly by their member pointers (which typically have the same variable name as \a
  7107. name).
  7108. \see positions, anchor
  7109. */
  7110. QCPItemPosition *QCPAbstractItem::position(const QString &name) const
  7111. {
  7112. for (int i=0; i<mPositions.size(); ++i)
  7113. {
  7114. if (mPositions.at(i)->name() == name)
  7115. return mPositions.at(i);
  7116. }
  7117. qDebug() << Q_FUNC_INFO << "position with name not found:" << name;
  7118. return 0;
  7119. }
  7120. /*!
  7121. Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by
  7122. that name, returns 0.
  7123. This function provides an alternative way to access item anchors. Normally, you access
  7124. anchors direcly by their member pointers (which typically have the same variable name as \a
  7125. name).
  7126. \see anchors, position
  7127. */
  7128. QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const
  7129. {
  7130. for (int i=0; i<mAnchors.size(); ++i)
  7131. {
  7132. if (mAnchors.at(i)->name() == name)
  7133. return mAnchors.at(i);
  7134. }
  7135. qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name;
  7136. return 0;
  7137. }
  7138. /*!
  7139. Returns whether this item has an anchor with the specified \a name.
  7140. Note that you can check for positions with this function, too. This is because every position is
  7141. also an anchor (QCPItemPosition inherits from QCPItemAnchor).
  7142. \see anchor, position
  7143. */
  7144. bool QCPAbstractItem::hasAnchor(const QString &name) const
  7145. {
  7146. for (int i=0; i<mAnchors.size(); ++i)
  7147. {
  7148. if (mAnchors.at(i)->name() == name)
  7149. return true;
  7150. }
  7151. return false;
  7152. }
  7153. /*! \internal
  7154. Returns the rect the visual representation of this item is clipped to. This depends on the
  7155. current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect.
  7156. If the item is not clipped to an axis rect, the \ref QCustomPlot::viewport rect is returned.
  7157. \see draw
  7158. */
  7159. QRect QCPAbstractItem::clipRect() const
  7160. {
  7161. if (mClipToAxisRect && mClipAxisRect)
  7162. return mClipAxisRect.data()->rect();
  7163. else
  7164. return mParentPlot->viewport();
  7165. }
  7166. /*! \internal
  7167. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  7168. before drawing item lines.
  7169. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  7170. This function takes into account the local setting of the antialiasing flag as well as the
  7171. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  7172. QCustomPlot::setNotAntialiasedElements.
  7173. \see setAntialiased
  7174. */
  7175. void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
  7176. {
  7177. applyAntialiasingHint(painter, mAntialiased, QCP::aeItems);
  7178. }
  7179. /*! \internal
  7180. Finds the shortest squared distance of \a point to the line segment defined by \a start and \a
  7181. end.
  7182. This function may be used to help with the implementation of the \ref selectTest function for
  7183. specific items.
  7184. \note This function is identical to QCPAbstractPlottable::distSqrToLine
  7185. \see rectSelectTest
  7186. */
  7187. double QCPAbstractItem::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const
  7188. {
  7189. QVector2D a(start);
  7190. QVector2D b(end);
  7191. QVector2D p(point);
  7192. QVector2D v(b-a);
  7193. double vLengthSqr = v.lengthSquared();
  7194. if (!qFuzzyIsNull(vLengthSqr))
  7195. {
  7196. double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr;
  7197. if (mu < 0)
  7198. return (a-p).lengthSquared();
  7199. else if (mu > 1)
  7200. return (b-p).lengthSquared();
  7201. else
  7202. return ((a + mu*v)-p).lengthSquared();
  7203. } else
  7204. return (a-p).lengthSquared();
  7205. }
  7206. /*! \internal
  7207. A convenience function which returns the selectTest value for a specified \a rect and a specified
  7208. click position \a pos. \a filledRect defines whether a click inside the rect should also be
  7209. considered a hit or whether only the rect border is sensitive to hits.
  7210. This function may be used to help with the implementation of the \ref selectTest function for
  7211. specific items.
  7212. For example, if your item consists of four rects, call this function four times, once for each
  7213. rect, in your \ref selectTest reimplementation. Finally, return the minimum of all four returned
  7214. values which were greater or equal to zero. (Because this function may return -1.0 when \a pos
  7215. doesn't hit \a rect at all). If all calls returned -1.0, return -1.0, too, because your item
  7216. wasn't hit.
  7217. \see distSqrToLine
  7218. */
  7219. double QCPAbstractItem::rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const
  7220. {
  7221. double result = -1;
  7222. // distance to border:
  7223. QList<QLineF> lines;
  7224. lines << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight())
  7225. << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight());
  7226. double minDistSqr = std::numeric_limits<double>::max();
  7227. for (int i=0; i<lines.size(); ++i)
  7228. {
  7229. double distSqr = distSqrToLine(lines.at(i).p1(), lines.at(i).p2(), pos);
  7230. if (distSqr < minDistSqr)
  7231. minDistSqr = distSqr;
  7232. }
  7233. result = qSqrt(minDistSqr);
  7234. // filled rect, allow click inside to count as hit:
  7235. if (filledRect && result > mParentPlot->selectionTolerance()*0.99)
  7236. {
  7237. if (rect.contains(pos))
  7238. result = mParentPlot->selectionTolerance()*0.99;
  7239. }
  7240. return result;
  7241. }
  7242. /*! \internal
  7243. Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in
  7244. item subclasses if they want to provide anchors (QCPItemAnchor).
  7245. For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor
  7246. ids and returns the respective pixel points of the specified anchor.
  7247. \see createAnchor
  7248. */
  7249. QPointF QCPAbstractItem::anchorPixelPoint(int anchorId) const
  7250. {
  7251. qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId;
  7252. return QPointF();
  7253. }
  7254. /*! \internal
  7255. Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified
  7256. \a name must be a unique string that is usually identical to the variable name of the position
  7257. member (This is needed to provide the name-based \ref position access to positions).
  7258. Don't delete positions created by this function manually, as the item will take care of it.
  7259. Use this function in the constructor (initialization list) of the specific item subclass to
  7260. create each position member. Don't create QCPItemPositions with \b new yourself, because they
  7261. won't be registered with the item properly.
  7262. \see createAnchor
  7263. */
  7264. QCPItemPosition *QCPAbstractItem::createPosition(const QString &name)
  7265. {
  7266. if (hasAnchor(name))
  7267. qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
  7268. QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name);
  7269. mPositions.append(newPosition);
  7270. mAnchors.append(newPosition); // every position is also an anchor
  7271. newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis);
  7272. newPosition->setType(QCPItemPosition::ptPlotCoords);
  7273. if (mParentPlot->axisRect())
  7274. newPosition->setAxisRect(mParentPlot->axisRect());
  7275. newPosition->setCoords(0, 0);
  7276. return newPosition;
  7277. }
  7278. /*! \internal
  7279. Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified
  7280. \a name must be a unique string that is usually identical to the variable name of the anchor
  7281. member (This is needed to provide the name based \ref anchor access to anchors).
  7282. The \a anchorId must be a number identifying the created anchor. It is recommended to create an
  7283. enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor
  7284. to identify itself when it calls QCPAbstractItem::anchorPixelPoint. That function then returns
  7285. the correct pixel coordinates for the passed anchor id.
  7286. Don't delete anchors created by this function manually, as the item will take care of it.
  7287. Use this function in the constructor (initialization list) of the specific item subclass to
  7288. create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they
  7289. won't be registered with the item properly.
  7290. \see createPosition
  7291. */
  7292. QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId)
  7293. {
  7294. if (hasAnchor(name))
  7295. qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
  7296. QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId);
  7297. mAnchors.append(newAnchor);
  7298. return newAnchor;
  7299. }
  7300. /* inherits documentation from base class */
  7301. void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  7302. {
  7303. Q_UNUSED(event)
  7304. Q_UNUSED(details)
  7305. if (mSelectable)
  7306. {
  7307. bool selBefore = mSelected;
  7308. setSelected(additive ? !mSelected : true);
  7309. if (selectionStateChanged)
  7310. *selectionStateChanged = mSelected != selBefore;
  7311. }
  7312. }
  7313. /* inherits documentation from base class */
  7314. void QCPAbstractItem::deselectEvent(bool *selectionStateChanged)
  7315. {
  7316. if (mSelectable)
  7317. {
  7318. bool selBefore = mSelected;
  7319. setSelected(false);
  7320. if (selectionStateChanged)
  7321. *selectionStateChanged = mSelected != selBefore;
  7322. }
  7323. }
  7324. /* inherits documentation from base class */
  7325. QCP::Interaction QCPAbstractItem::selectionCategory() const
  7326. {
  7327. return QCP::iSelectItems;
  7328. }
  7329. /*! \file */
  7330. /*! \mainpage %QCustomPlot 1.2.1 Documentation
  7331. \image html qcp-doc-logo.png
  7332. Below is a brief overview of and guide to the classes and their relations. If you are new to
  7333. QCustomPlot and just want to start using it, it's recommended to look at the tutorials and
  7334. examples at
  7335. http://www.qcustomplot.com/
  7336. This documentation is especially helpful as a reference, when you're familiar with the basic
  7337. concept of how to use %QCustomPlot and you wish to learn more about specific functionality.
  7338. See the \ref classoverview "class overview" for diagrams explaining the relationships between
  7339. the most important classes of the QCustomPlot library.
  7340. The central widget which displays the plottables and axes on its surface is QCustomPlot. Every
  7341. QCustomPlot contains four axes by default. They can be accessed via the members \ref
  7342. QCustomPlot::xAxis "xAxis", \ref QCustomPlot::yAxis "yAxis", \ref QCustomPlot::xAxis2 "xAxis2"
  7343. and \ref QCustomPlot::yAxis2 "yAxis2", and are of type QCPAxis. QCustomPlot supports an arbitrary
  7344. number of axes and axis rects, see the documentation of QCPAxisRect for details.
  7345. \section mainpage-plottables Plottables
  7346. \a Plottables are classes that display any kind of data inside the QCustomPlot. They all derive
  7347. from QCPAbstractPlottable. For example, the QCPGraph class is a plottable that displays a graph
  7348. inside the plot with different line styles, scatter styles, filling etc.
  7349. Since plotting graphs is such a dominant use case, QCustomPlot has a special interface for working
  7350. with QCPGraph plottables, that makes it very easy to handle them:\n
  7351. You create a new graph with QCustomPlot::addGraph and access them with QCustomPlot::graph.
  7352. For all other plottables, you need to use the normal plottable interface:\n
  7353. First, you create an instance of the plottable you want, e.g.
  7354. \code
  7355. QCPCurve *newCurve = new QCPCurve(customPlot->xAxis, customPlot->yAxis);\endcode
  7356. add it to the customPlot:
  7357. \code
  7358. customPlot->addPlottable(newCurve);\endcode
  7359. and then modify the properties of the newly created plottable via the <tt>newCurve</tt> pointer.
  7360. Plottables (including graphs) can be retrieved via QCustomPlot::plottable. Since the return type
  7361. of that function is the abstract base class of all plottables, QCPAbstractPlottable, you will
  7362. probably want to qobject_cast the returned pointer to the respective plottable subclass. (As
  7363. usual, if the cast returns zero, the plottable wasn't of that specific subclass.)
  7364. All further interfacing with plottables (e.g how to set data) is specific to the plottable type.
  7365. See the documentations of the subclasses: QCPGraph, QCPCurve, QCPBars, QCPStatisticalBox,
  7366. QCPColorMap.
  7367. \section mainpage-axes Controlling the Axes
  7368. As mentioned, QCustomPlot has four axes by default: \a xAxis (bottom), \a yAxis (left), \a xAxis2
  7369. (top), \a yAxis2 (right).
  7370. Their range is handled by the simple QCPRange class. You can set the range with the
  7371. QCPAxis::setRange function. By default, the axes represent a linear scale. To set a logarithmic
  7372. scale, set \ref QCPAxis::setScaleType to \ref QCPAxis::stLogarithmic. The logarithm base can be set freely
  7373. with \ref QCPAxis::setScaleLogBase.
  7374. By default, an axis automatically creates and labels ticks in a sensible manner. See the
  7375. following functions for tick manipulation:\n QCPAxis::setTicks, QCPAxis::setAutoTicks,
  7376. QCPAxis::setAutoTickCount, QCPAxis::setAutoTickStep, QCPAxis::setTickLabels,
  7377. QCPAxis::setTickLabelType, QCPAxis::setTickLabelRotation, QCPAxis::setTickStep,
  7378. QCPAxis::setTickLength,...
  7379. Each axis can be given an axis label (e.g. "Voltage (mV)") with QCPAxis::setLabel.
  7380. The distance of an axis backbone to the respective viewport border is called its margin.
  7381. Normally, the margins are calculated automatically. To change this, set
  7382. \ref QCPAxisRect::setAutoMargins to exclude the respective margin sides, set the margins manually with
  7383. \ref QCPAxisRect::setMargins. The main axis rect can be reached with \ref QCustomPlot::axisRect().
  7384. \section mainpage-legend Plot Legend
  7385. Every QCustomPlot has one QCPLegend (as \ref QCustomPlot::legend) by default. A legend is a small
  7386. layout element inside the plot which lists the plottables with an icon of the plottable
  7387. line/symbol and a name (QCPAbstractPlottable::setName). Plottables can be added and removed from
  7388. the main legend via \ref QCPAbstractPlottable::addToLegend and \ref
  7389. QCPAbstractPlottable::removeFromLegend. By default, adding a plottable to QCustomPlot
  7390. automatically adds it to the legend, too. This behaviour can be modified with the
  7391. QCustomPlot::setAutoAddPlottableToLegend property.
  7392. The QCPLegend provides an interface to access, add and remove legend items directly, too. See
  7393. QCPLegend::item, QCPLegend::itemWithPlottable, QCPLegend::addItem, QCPLegend::removeItem for
  7394. example.
  7395. Multiple legends are supported via the \link thelayoutsystem layout system\endlink (as a
  7396. QCPLegend simply is a normal layout element).
  7397. \section mainpage-userinteraction User Interactions
  7398. QCustomPlot supports dragging axis ranges with the mouse (\ref
  7399. QCPAxisRect::setRangeDrag), zooming axis ranges with the mouse wheel (\ref
  7400. QCPAxisRect::setRangeZoom) and a complete selection mechanism.
  7401. The availability of these interactions is controlled with \ref QCustomPlot::setInteractions. For
  7402. details about the interaction system, see the documentation there.
  7403. Further, QCustomPlot always emits corresponding signals, when objects are clicked or
  7404. doubleClicked. See \ref QCustomPlot::plottableClick, \ref QCustomPlot::plottableDoubleClick
  7405. and \ref QCustomPlot::axisClick for example.
  7406. \section mainpage-items Items
  7407. Apart from plottables there is another category of plot objects that are important: Items. The
  7408. base class of all items is QCPAbstractItem. An item sets itself apart from plottables in that
  7409. it's not necessarily bound to any axes. This means it may also be positioned in absolute pixel
  7410. coordinates or placed at a relative position on an axis rect. Further, it usually doesn't
  7411. represent data directly, but acts as decoration, emphasis, description etc.
  7412. Multiple items can be arranged in a parent-child-hierarchy allowing for dynamical behaviour. For
  7413. example, you could place the head of an arrow at a fixed plot coordinate, so it always points to
  7414. some important area in the plot. The tail of the arrow can be anchored to a text item which
  7415. always resides in the top center of the axis rect, independent of where the user drags the axis
  7416. ranges. This way the arrow stretches and turns so it always points from the label to the
  7417. specified plot coordinate, without any further code necessary.
  7418. For a more detailed introduction, see the QCPAbstractItem documentation, and from there the
  7419. documentations of the individual built-in items, to find out how to use them.
  7420. \section mainpage-layoutelements Layout elements and layouts
  7421. QCustomPlot uses an internal layout system to provide dynamic sizing and positioning of objects like
  7422. the axis rect(s), legends and the plot title. They are all based on \ref QCPLayoutElement and are arranged by
  7423. placing them inside a \ref QCPLayout.
  7424. Details on this topic are given on the dedicated page about \link thelayoutsystem the layout system\endlink.
  7425. \section mainpage-performancetweaks Performance Tweaks
  7426. Although QCustomPlot is quite fast, some features like translucent fills, antialiasing and thick
  7427. lines can cause a significant slow down. If you notice this in your application, here are some
  7428. thoughts on how to increase performance. By far the most time is spent in the drawing functions,
  7429. specifically the drawing of graphs. For maximum performance, consider the following (most
  7430. recommended/effective measures first):
  7431. \li use Qt 4.8.0 and up. Performance has doubled or tripled with respect to Qt 4.7.4. However
  7432. QPainter was broken and drawing pixel precise things, e.g. scatters, isn't possible with Qt >=
  7433. 4.8.0. So it's a performance vs. plot quality tradeoff when switching to Qt 4.8.
  7434. \li To increase responsiveness during dragging, consider setting \ref QCustomPlot::setNoAntialiasingOnDrag to true.
  7435. \li On X11 (GNU/Linux), avoid the slow native drawing system, use raster by supplying
  7436. "-graphicssystem raster" as command line argument or calling QApplication::setGraphicsSystem("raster")
  7437. before creating the QApplication object. (Only available for Qt versions before 5.0)
  7438. \li On all operating systems, use OpenGL hardware acceleration by supplying "-graphicssystem
  7439. opengl" as command line argument or calling QApplication::setGraphicsSystem("opengl") (Only
  7440. available for Qt versions before 5.0). If OpenGL is available, this will slightly decrease the
  7441. quality of antialiasing, but extremely increase performance especially with alpha
  7442. (semi-transparent) fills, much antialiasing and a large QCustomPlot drawing surface. Note
  7443. however, that the maximum frame rate might be constrained by the vertical sync frequency of your
  7444. monitor (VSync can be disabled in the graphics card driver configuration). So for simple plots
  7445. (where the potential framerate is far above 60 frames per second), OpenGL acceleration might
  7446. achieve numerically lower frame rates than the other graphics systems, because they are not
  7447. capped at the VSync frequency.
  7448. \li Avoid any kind of alpha (transparency), especially in fills
  7449. \li Avoid lines with a pen width greater than one
  7450. \li Avoid any kind of antialiasing, especially in graph lines (see \ref QCustomPlot::setNotAntialiasedElements)
  7451. \li Avoid repeatedly setting the complete data set with \ref QCPGraph::setData. Use \ref QCPGraph::addData instead, if most
  7452. data points stay unchanged, e.g. in a running measurement.
  7453. \li Set the \a copy parameter of the setData functions to false, so only pointers get
  7454. transferred. (Relevant only if preparing data maps with a large number of points, i.e. over 10000)
  7455. \section mainpage-flags Preprocessor Define Flags
  7456. QCustomPlot understands some preprocessor defines that are useful for debugging and compilation:
  7457. <dl>
  7458. <dt>\c QCUSTOMPLOT_COMPILE_LIBRARY
  7459. <dd>Define this flag when you compile QCustomPlot as a shared library (.so/.dll)
  7460. <dt>\c QCUSTOMPLOT_USE_LIBRARY
  7461. <dd>Define this flag before including the header, when using QCustomPlot as a shared library
  7462. <dt>\c QCUSTOMPLOT_CHECK_DATA
  7463. <dd>If this flag is defined, the QCustomPlot plottables will perform data validity checks on every redraw.
  7464. This means they will give qDebug output when you plot \e inf or \e nan values, they will not
  7465. fix your data.
  7466. </dl>
  7467. */
  7468. /*! \page classoverview Class Overview
  7469. The following diagrams may help to gain a deeper understanding of the relationships between classes that make up
  7470. the QCustomPlot library. The diagrams are not exhaustive, so only the classes deemed most relevant are shown.
  7471. \section classoverview-relations Class Relationship Diagram
  7472. \image html RelationOverview.png "Overview of most important classes and their relations"
  7473. \section classoverview-inheritance Class Inheritance Tree
  7474. \image html InheritanceOverview.png "Inheritance tree of most important classes"
  7475. */
  7476. ////////////////////////////////////////////////////////////////////////////////////////////////////
  7477. //////////////////// QCustomPlot
  7478. ////////////////////////////////////////////////////////////////////////////////////////////////////
  7479. /*! \class QCustomPlot
  7480. \brief The central class of the library. This is the QWidget which displays the plot and
  7481. interacts with the user.
  7482. For tutorials on how to use QCustomPlot, see the website\n
  7483. http://www.qcustomplot.com/
  7484. */
  7485. /* start of documentation of inline functions */
  7486. /*! \fn QRect QCustomPlot::viewport() const
  7487. Returns the viewport rect of this QCustomPlot instance. The viewport is the area the plot is
  7488. drawn in, all mechanisms, e.g. margin caluclation take the viewport to be the outer border of the
  7489. plot. The viewport normally is the rect() of the QCustomPlot widget, i.e. a rect with top left
  7490. (0, 0) and size of the QCustomPlot widget.
  7491. Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically
  7492. an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger
  7493. and contains also the axes themselves, their tick numbers, their labels, the plot title etc.
  7494. Only when saving to a file (see \ref savePng, savePdf etc.) the viewport is temporarily modified
  7495. to allow saving plots with sizes independent of the current widget size.
  7496. */
  7497. /*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const
  7498. Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just
  7499. one cell with the main QCPAxisRect inside.
  7500. */
  7501. /* end of documentation of inline functions */
  7502. /* start of documentation of signals */
  7503. /*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event)
  7504. This signal is emitted when the QCustomPlot receives a mouse double click event.
  7505. */
  7506. /*! \fn void QCustomPlot::mousePress(QMouseEvent *event)
  7507. This signal is emitted when the QCustomPlot receives a mouse press event.
  7508. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
  7509. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
  7510. QCPAxisRect::setRangeDragAxes.
  7511. */
  7512. /*! \fn void QCustomPlot::mouseMove(QMouseEvent *event)
  7513. This signal is emitted when the QCustomPlot receives a mouse move event.
  7514. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
  7515. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
  7516. QCPAxisRect::setRangeDragAxes.
  7517. \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here,
  7518. because the dragging starting point was saved the moment the mouse was pressed. Thus it only has
  7519. a meaning for the range drag axes that were set at that moment. If you want to change the drag
  7520. axes, consider doing this in the \ref mousePress signal instead.
  7521. */
  7522. /*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event)
  7523. This signal is emitted when the QCustomPlot receives a mouse release event.
  7524. It is emitted before QCustomPlot handles any other mechanisms like object selection. So a
  7525. slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or
  7526. \ref QCPAbstractPlottable::setSelectable.
  7527. */
  7528. /*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event)
  7529. This signal is emitted when the QCustomPlot receives a mouse wheel event.
  7530. It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot
  7531. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref
  7532. QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor.
  7533. */
  7534. /*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event)
  7535. This signal is emitted when a plottable is clicked.
  7536. \a event is the mouse event that caused the click and \a plottable is the plottable that received
  7537. the click.
  7538. \see plottableDoubleClick
  7539. */
  7540. /*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event)
  7541. This signal is emitted when a plottable is double clicked.
  7542. \a event is the mouse event that caused the click and \a plottable is the plottable that received
  7543. the click.
  7544. \see plottableClick
  7545. */
  7546. /*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event)
  7547. This signal is emitted when an item is clicked.
  7548. \a event is the mouse event that caused the click and \a item is the item that received the
  7549. click.
  7550. \see itemDoubleClick
  7551. */
  7552. /*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event)
  7553. This signal is emitted when an item is double clicked.
  7554. \a event is the mouse event that caused the click and \a item is the item that received the
  7555. click.
  7556. \see itemClick
  7557. */
  7558. /*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
  7559. This signal is emitted when an axis is clicked.
  7560. \a event is the mouse event that caused the click, \a axis is the axis that received the click and
  7561. \a part indicates the part of the axis that was clicked.
  7562. \see axisDoubleClick
  7563. */
  7564. /*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
  7565. This signal is emitted when an axis is double clicked.
  7566. \a event is the mouse event that caused the click, \a axis is the axis that received the click and
  7567. \a part indicates the part of the axis that was clicked.
  7568. \see axisClick
  7569. */
  7570. /*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
  7571. This signal is emitted when a legend (item) is clicked.
  7572. \a event is the mouse event that caused the click, \a legend is the legend that received the
  7573. click and \a item is the legend item that received the click. If only the legend and no item is
  7574. clicked, \a item is 0. This happens for a click inside the legend padding or the space between
  7575. two items.
  7576. \see legendDoubleClick
  7577. */
  7578. /*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
  7579. This signal is emitted when a legend (item) is double clicked.
  7580. \a event is the mouse event that caused the click, \a legend is the legend that received the
  7581. click and \a item is the legend item that received the click. If only the legend and no item is
  7582. clicked, \a item is 0. This happens for a click inside the legend padding or the space between
  7583. two items.
  7584. \see legendClick
  7585. */
  7586. /*! \fn void QCustomPlot:: titleClick(QMouseEvent *event, QCPPlotTitle *title)
  7587. This signal is emitted when a plot title is clicked.
  7588. \a event is the mouse event that caused the click and \a title is the plot title that received
  7589. the click.
  7590. \see titleDoubleClick
  7591. */
  7592. /*! \fn void QCustomPlot::titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title)
  7593. This signal is emitted when a plot title is double clicked.
  7594. \a event is the mouse event that caused the click and \a title is the plot title that received
  7595. the click.
  7596. \see titleClick
  7597. */
  7598. /*! \fn void QCustomPlot::selectionChangedByUser()
  7599. This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by
  7600. clicking. It is not emitted when the selection state of an object has changed programmatically by
  7601. a direct call to setSelected() on an object or by calling \ref deselectAll.
  7602. In addition to this signal, selectable objects also provide individual signals, for example
  7603. QCPAxis::selectionChanged or QCPAbstractPlottable::selectionChanged. Note that those signals are
  7604. emitted even if the selection state is changed programmatically.
  7605. See the documentation of \ref setInteractions for details about the selection mechanism.
  7606. \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends
  7607. */
  7608. /*! \fn void QCustomPlot::beforeReplot()
  7609. This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref
  7610. replot).
  7611. It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
  7612. replot synchronously, it won't cause an infinite recursion.
  7613. \see replot, afterReplot
  7614. */
  7615. /*! \fn void QCustomPlot::afterReplot()
  7616. This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref
  7617. replot).
  7618. It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
  7619. replot synchronously, it won't cause an infinite recursion.
  7620. \see replot, beforeReplot
  7621. */
  7622. /* end of documentation of signals */
  7623. /* start of documentation of public members */
  7624. /*! \var QCPAxis *QCustomPlot::xAxis
  7625. A pointer to the primary x Axis (bottom) of the main axis rect of the plot.
  7626. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  7627. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  7628. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  7629. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  7630. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  7631. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  7632. axis rect), the corresponding pointers become 0.
  7633. */
  7634. /*! \var QCPAxis *QCustomPlot::yAxis
  7635. A pointer to the primary y Axis (left) of the main axis rect of the plot.
  7636. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  7637. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  7638. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  7639. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  7640. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  7641. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  7642. axis rect), the corresponding pointers become 0.
  7643. */
  7644. /*! \var QCPAxis *QCustomPlot::xAxis2
  7645. A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are
  7646. invisible by default. Use QCPAxis::setVisible to change this (or use \ref
  7647. QCPAxisRect::setupFullAxesBox).
  7648. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  7649. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  7650. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  7651. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  7652. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  7653. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  7654. axis rect), the corresponding pointers become 0.
  7655. */
  7656. /*! \var QCPAxis *QCustomPlot::yAxis2
  7657. A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are
  7658. invisible by default. Use QCPAxis::setVisible to change this (or use \ref
  7659. QCPAxisRect::setupFullAxesBox).
  7660. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  7661. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  7662. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  7663. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  7664. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  7665. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  7666. axis rect), the corresponding pointers become 0.
  7667. */
  7668. /*! \var QCPLegend *QCustomPlot::legend
  7669. A pointer to the default legend of the main axis rect. The legend is invisible by default. Use
  7670. QCPLegend::setVisible to change this.
  7671. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  7672. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  7673. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  7674. layout system\endlink to add multiple legends to the plot, use the layout system interface to
  7675. access the new legend. For example, legends can be placed inside an axis rect's \ref
  7676. QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If
  7677. the default legend is removed due to manipulation of the layout system (e.g. by removing the main
  7678. axis rect), the corresponding pointer becomes 0.
  7679. */
  7680. /* end of documentation of public members */
  7681. /*!
  7682. Constructs a QCustomPlot and sets reasonable default values.
  7683. */
  7684. QCustomPlot::QCustomPlot(QWidget *parent) :
  7685. QWidget(parent),
  7686. xAxis(0),
  7687. yAxis(0),
  7688. xAxis2(0),
  7689. yAxis2(0),
  7690. legend(0),
  7691. mPlotLayout(0),
  7692. mAutoAddPlottableToLegend(true),
  7693. mAntialiasedElements(QCP::aeNone),
  7694. mNotAntialiasedElements(QCP::aeNone),
  7695. mInteractions(0),
  7696. mSelectionTolerance(8),
  7697. mNoAntialiasingOnDrag(false),
  7698. mBackgroundBrush(Qt::white, Qt::SolidPattern),
  7699. mBackgroundScaled(true),
  7700. mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
  7701. mCurrentLayer(0),
  7702. mPlottingHints(QCP::phCacheLabels|QCP::phForceRepaint),
  7703. mMultiSelectModifier(Qt::ControlModifier),
  7704. mPaintBuffer(size()),
  7705. mMouseEventElement(0),
  7706. mReplotting(false)
  7707. {
  7708. setAttribute(Qt::WA_NoMousePropagation);
  7709. setAttribute(Qt::WA_OpaquePaintEvent);
  7710. setMouseTracking(true);
  7711. QLocale currentLocale = locale();
  7712. currentLocale.setNumberOptions(QLocale::OmitGroupSeparator);
  7713. setLocale(currentLocale);
  7714. // create initial layers:
  7715. mLayers.append(new QCPLayer(this, "background"));
  7716. mLayers.append(new QCPLayer(this, "grid"));
  7717. mLayers.append(new QCPLayer(this, "main"));
  7718. mLayers.append(new QCPLayer(this, "axes"));
  7719. mLayers.append(new QCPLayer(this, "legend"));
  7720. updateLayerIndices();
  7721. setCurrentLayer("main");
  7722. // create initial layout, axis rect and legend:
  7723. mPlotLayout = new QCPLayoutGrid;
  7724. mPlotLayout->initializeParentPlot(this);
  7725. mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry
  7726. mPlotLayout->setLayer("main");
  7727. QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true);
  7728. mPlotLayout->addElement(0, 0, defaultAxisRect);
  7729. xAxis = defaultAxisRect->axis(QCPAxis::atBottom);
  7730. yAxis = defaultAxisRect->axis(QCPAxis::atLeft);
  7731. xAxis2 = defaultAxisRect->axis(QCPAxis::atTop);
  7732. yAxis2 = defaultAxisRect->axis(QCPAxis::atRight);
  7733. legend = new QCPLegend;
  7734. legend->setVisible(false);
  7735. defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop);
  7736. defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12));
  7737. defaultAxisRect->setLayer("background");
  7738. xAxis->setLayer("axes");
  7739. yAxis->setLayer("axes");
  7740. xAxis2->setLayer("axes");
  7741. yAxis2->setLayer("axes");
  7742. xAxis->grid()->setLayer("grid");
  7743. yAxis->grid()->setLayer("grid");
  7744. xAxis2->grid()->setLayer("grid");
  7745. yAxis2->grid()->setLayer("grid");
  7746. legend->setLayer("legend");
  7747. setViewport(rect()); // needs to be called after mPlotLayout has been created
  7748. replot();
  7749. }
  7750. QCustomPlot::~QCustomPlot()
  7751. {
  7752. clearPlottables();
  7753. clearItems();
  7754. if (mPlotLayout)
  7755. {
  7756. delete mPlotLayout;
  7757. mPlotLayout = 0;
  7758. }
  7759. mCurrentLayer = 0;
  7760. qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed
  7761. mLayers.clear();
  7762. }
  7763. /*!
  7764. Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement.
  7765. This overrides the antialiasing settings for whole element groups, normally controlled with the
  7766. \a setAntialiasing function on the individual elements. If an element is neither specified in
  7767. \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
  7768. each individual element instance is used.
  7769. For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be
  7770. drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
  7771. to.
  7772. if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is
  7773. removed from there.
  7774. \see setNotAntialiasedElements
  7775. */
  7776. void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements)
  7777. {
  7778. mAntialiasedElements = antialiasedElements;
  7779. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  7780. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  7781. mNotAntialiasedElements |= ~mAntialiasedElements;
  7782. }
  7783. /*!
  7784. Sets whether the specified \a antialiasedElement is forcibly drawn antialiased.
  7785. See \ref setAntialiasedElements for details.
  7786. \see setNotAntialiasedElement
  7787. */
  7788. void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled)
  7789. {
  7790. if (!enabled && mAntialiasedElements.testFlag(antialiasedElement))
  7791. mAntialiasedElements &= ~antialiasedElement;
  7792. else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement))
  7793. mAntialiasedElements |= antialiasedElement;
  7794. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  7795. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  7796. mNotAntialiasedElements |= ~mAntialiasedElements;
  7797. }
  7798. /*!
  7799. Sets which elements are forcibly drawn not antialiased as an \a or combination of
  7800. QCP::AntialiasedElement.
  7801. This overrides the antialiasing settings for whole element groups, normally controlled with the
  7802. \a setAntialiasing function on the individual elements. If an element is neither specified in
  7803. \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
  7804. each individual element instance is used.
  7805. For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be
  7806. drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
  7807. to.
  7808. if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is
  7809. removed from there.
  7810. \see setAntialiasedElements
  7811. */
  7812. void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements &notAntialiasedElements)
  7813. {
  7814. mNotAntialiasedElements = notAntialiasedElements;
  7815. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  7816. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  7817. mAntialiasedElements |= ~mNotAntialiasedElements;
  7818. }
  7819. /*!
  7820. Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased.
  7821. See \ref setNotAntialiasedElements for details.
  7822. \see setAntialiasedElement
  7823. */
  7824. void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled)
  7825. {
  7826. if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement))
  7827. mNotAntialiasedElements &= ~notAntialiasedElement;
  7828. else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement))
  7829. mNotAntialiasedElements |= notAntialiasedElement;
  7830. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  7831. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  7832. mAntialiasedElements |= ~mNotAntialiasedElements;
  7833. }
  7834. /*!
  7835. If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the
  7836. plottable to the legend (QCustomPlot::legend).
  7837. \see addPlottable, addGraph, QCPLegend::addItem
  7838. */
  7839. void QCustomPlot::setAutoAddPlottableToLegend(bool on)
  7840. {
  7841. mAutoAddPlottableToLegend = on;
  7842. }
  7843. /*!
  7844. Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction
  7845. enums. There are the following types of interactions:
  7846. <b>Axis range manipulation</b> is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the
  7847. respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel.
  7848. For details how to control which axes the user may drag/zoom and in what orientations, see \ref
  7849. QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes,
  7850. \ref QCPAxisRect::setRangeZoomAxes.
  7851. <b>Plottable selection</b> is controlled by \ref QCP::iSelectPlottables. If \ref QCP::iSelectPlottables is
  7852. set, the user may select plottables (graphs, curves, bars,...) by clicking on them or in their
  7853. vicinity (\ref setSelectionTolerance). Whether the user can actually select a plottable can
  7854. further be restricted with the \ref QCPAbstractPlottable::setSelectable function on the specific
  7855. plottable. To find out whether a specific plottable is selected, call
  7856. QCPAbstractPlottable::selected(). To retrieve a list of all currently selected plottables, call
  7857. \ref selectedPlottables. If you're only interested in QCPGraphs, you may use the convenience
  7858. function \ref selectedGraphs.
  7859. <b>Item selection</b> is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user
  7860. may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find
  7861. out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of
  7862. all currently selected items, call \ref selectedItems.
  7863. <b>Axis selection</b> is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user
  7864. may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick
  7865. labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for
  7866. each axis. To retrieve a list of all axes that currently contain selected parts, call \ref
  7867. selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts().
  7868. <b>Legend selection</b> is controlled with \ref QCP::iSelectLegend. If this is set, the user may
  7869. select the legend itself or individual items by clicking on them. What parts exactly are
  7870. selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the
  7871. legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To
  7872. find out which child items are selected, call \ref QCPLegend::selectedItems.
  7873. <b>All other selectable elements</b> The selection of all other selectable objects (e.g.
  7874. QCPPlotTitle, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the
  7875. user may select those objects by clicking on them. To find out which are currently selected, you
  7876. need to check their selected state explicitly.
  7877. If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is
  7878. emitted. Each selectable object additionally emits an individual selectionChanged signal whenever
  7879. their selection state has changed, i.e. not only by user interaction.
  7880. To allow multiple objects to be selected by holding the selection modifier (\ref
  7881. setMultiSelectModifier), set the flag \ref QCP::iMultiSelect.
  7882. \note In addition to the selection mechanism presented here, QCustomPlot always emits
  7883. corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and
  7884. \ref plottableDoubleClick for example.
  7885. \see setInteraction, setSelectionTolerance
  7886. */
  7887. void QCustomPlot::setInteractions(const QCP::Interactions &interactions)
  7888. {
  7889. mInteractions = interactions;
  7890. }
  7891. /*!
  7892. Sets the single \a interaction of this QCustomPlot to \a enabled.
  7893. For details about the interaction system, see \ref setInteractions.
  7894. \see setInteractions
  7895. */
  7896. void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled)
  7897. {
  7898. if (!enabled && mInteractions.testFlag(interaction))
  7899. mInteractions &= ~interaction;
  7900. else if (enabled && !mInteractions.testFlag(interaction))
  7901. mInteractions |= interaction;
  7902. }
  7903. /*!
  7904. Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or
  7905. not.
  7906. If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a
  7907. potential selection when the minimum distance between the click position and the graph line is
  7908. smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks
  7909. directly inside the area and ignore this selection tolerance. In other words, it only has meaning
  7910. for parts of objects that are too thin to exactly hit with a click and thus need such a
  7911. tolerance.
  7912. \see setInteractions, QCPLayerable::selectTest
  7913. */
  7914. void QCustomPlot::setSelectionTolerance(int pixels)
  7915. {
  7916. mSelectionTolerance = pixels;
  7917. }
  7918. /*!
  7919. Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes
  7920. ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves
  7921. performance during dragging. Thus it creates a more responsive user experience. As soon as the
  7922. user stops dragging, the last replot is done with normal antialiasing, to restore high image
  7923. quality.
  7924. \see setAntialiasedElements, setNotAntialiasedElements
  7925. */
  7926. void QCustomPlot::setNoAntialiasingOnDrag(bool enabled)
  7927. {
  7928. mNoAntialiasingOnDrag = enabled;
  7929. }
  7930. /*!
  7931. Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint.
  7932. \see setPlottingHint
  7933. */
  7934. void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints)
  7935. {
  7936. mPlottingHints = hints;
  7937. }
  7938. /*!
  7939. Sets the specified plotting \a hint to \a enabled.
  7940. \see setPlottingHints
  7941. */
  7942. void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled)
  7943. {
  7944. QCP::PlottingHints newHints = mPlottingHints;
  7945. if (!enabled)
  7946. newHints &= ~hint;
  7947. else
  7948. newHints |= hint;
  7949. if (newHints != mPlottingHints)
  7950. setPlottingHints(newHints);
  7951. }
  7952. /*!
  7953. Sets the keyboard modifier that will be recognized as multi-select-modifier.
  7954. If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple objects
  7955. by clicking on them one after the other while holding down \a modifier.
  7956. By default the multi-select-modifier is set to Qt::ControlModifier.
  7957. \see setInteractions
  7958. */
  7959. void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier)
  7960. {
  7961. mMultiSelectModifier = modifier;
  7962. }
  7963. /*!
  7964. Sets the viewport of this QCustomPlot. The Viewport is the area that the top level layout
  7965. (QCustomPlot::plotLayout()) uses as its rect. Normally, the viewport is the entire widget rect.
  7966. This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref
  7967. savePdf, etc. by temporarily changing the viewport size.
  7968. */
  7969. void QCustomPlot::setViewport(const QRect &rect)
  7970. {
  7971. mViewport = rect;
  7972. if (mPlotLayout)
  7973. mPlotLayout->setOuterRect(mViewport);
  7974. }
  7975. /*!
  7976. Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn
  7977. below all other objects in the plot.
  7978. For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be
  7979. enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is
  7980. preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  7981. consider using the overloaded version of this function.
  7982. If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will
  7983. first be filled with that brush, before drawing the background pixmap. This can be useful for
  7984. background pixmaps with translucent areas.
  7985. \see setBackgroundScaled, setBackgroundScaledMode
  7986. */
  7987. void QCustomPlot::setBackground(const QPixmap &pm)
  7988. {
  7989. mBackgroundPixmap = pm;
  7990. mScaledBackgroundPixmap = QPixmap();
  7991. }
  7992. /*!
  7993. Sets the background brush of the viewport (see \ref setViewport).
  7994. Before drawing everything else, the background is filled with \a brush. If a background pixmap
  7995. was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport
  7996. before the background pixmap is drawn. This can be useful for background pixmaps with translucent
  7997. areas.
  7998. Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be
  7999. useful for exporting to image formats which support transparency, e.g. \ref savePng.
  8000. \see setBackgroundScaled, setBackgroundScaledMode
  8001. */
  8002. void QCustomPlot::setBackground(const QBrush &brush)
  8003. {
  8004. mBackgroundBrush = brush;
  8005. }
  8006. /*! \overload
  8007. Allows setting the background pixmap of the viewport, whether it shall be scaled and how it
  8008. shall be scaled in one call.
  8009. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  8010. */
  8011. void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
  8012. {
  8013. mBackgroundPixmap = pm;
  8014. mScaledBackgroundPixmap = QPixmap();
  8015. mBackgroundScaled = scaled;
  8016. mBackgroundScaledMode = mode;
  8017. }
  8018. /*!
  8019. Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is
  8020. set to true, control whether and how the aspect ratio of the original pixmap is preserved with
  8021. \ref setBackgroundScaledMode.
  8022. Note that the scaled version of the original pixmap is buffered, so there is no performance
  8023. penalty on replots. (Except when the viewport dimensions are changed continuously.)
  8024. \see setBackground, setBackgroundScaledMode
  8025. */
  8026. void QCustomPlot::setBackgroundScaled(bool scaled)
  8027. {
  8028. mBackgroundScaled = scaled;
  8029. }
  8030. /*!
  8031. If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this
  8032. function to define whether and how the aspect ratio of the original pixmap is preserved.
  8033. \see setBackground, setBackgroundScaled
  8034. */
  8035. void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  8036. {
  8037. mBackgroundScaledMode = mode;
  8038. }
  8039. /*!
  8040. Returns the plottable with \a index. If the index is invalid, returns 0.
  8041. There is an overloaded version of this function with no parameter which returns the last added
  8042. plottable, see QCustomPlot::plottable()
  8043. \see plottableCount, addPlottable
  8044. */
  8045. QCPAbstractPlottable *QCustomPlot::plottable(int index)
  8046. {
  8047. if (index >= 0 && index < mPlottables.size())
  8048. {
  8049. return mPlottables.at(index);
  8050. } else
  8051. {
  8052. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  8053. return 0;
  8054. }
  8055. }
  8056. /*! \overload
  8057. Returns the last plottable that was added with \ref addPlottable. If there are no plottables in
  8058. the plot, returns 0.
  8059. \see plottableCount, addPlottable
  8060. */
  8061. QCPAbstractPlottable *QCustomPlot::plottable()
  8062. {
  8063. if (!mPlottables.isEmpty())
  8064. {
  8065. return mPlottables.last();
  8066. } else
  8067. return 0;
  8068. }
  8069. /*!
  8070. Adds the specified plottable to the plot and, if \ref setAutoAddPlottableToLegend is enabled, to
  8071. the legend (QCustomPlot::legend). QCustomPlot takes ownership of the plottable.
  8072. Returns true on success, i.e. when \a plottable isn't already in the plot and the parent plot of
  8073. \a plottable is this QCustomPlot (the latter is controlled by what axes were passed in the
  8074. plottable's constructor).
  8075. \see plottable, plottableCount, removePlottable, clearPlottables
  8076. */
  8077. bool QCustomPlot::addPlottable(QCPAbstractPlottable *plottable)
  8078. {
  8079. if (mPlottables.contains(plottable))
  8080. {
  8081. qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast<quintptr>(plottable);
  8082. return false;
  8083. }
  8084. if (plottable->parentPlot() != this)
  8085. {
  8086. qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(plottable);
  8087. return false;
  8088. }
  8089. mPlottables.append(plottable);
  8090. // possibly add plottable to legend:
  8091. if (mAutoAddPlottableToLegend)
  8092. plottable->addToLegend();
  8093. // special handling for QCPGraphs to maintain the simple graph interface:
  8094. if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable))
  8095. mGraphs.append(graph);
  8096. if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
  8097. plottable->setLayer(currentLayer());
  8098. return true;
  8099. }
  8100. /*!
  8101. Removes the specified plottable from the plot and, if necessary, from the legend (QCustomPlot::legend).
  8102. Returns true on success.
  8103. \see addPlottable, clearPlottables
  8104. */
  8105. bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable)
  8106. {
  8107. if (!mPlottables.contains(plottable))
  8108. {
  8109. qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast<quintptr>(plottable);
  8110. return false;
  8111. }
  8112. // remove plottable from legend:
  8113. plottable->removeFromLegend();
  8114. // special handling for QCPGraphs to maintain the simple graph interface:
  8115. if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable))
  8116. mGraphs.removeOne(graph);
  8117. // remove plottable:
  8118. delete plottable;
  8119. mPlottables.removeOne(plottable);
  8120. return true;
  8121. }
  8122. /*! \overload
  8123. Removes the plottable by its \a index.
  8124. */
  8125. bool QCustomPlot::removePlottable(int index)
  8126. {
  8127. if (index >= 0 && index < mPlottables.size())
  8128. return removePlottable(mPlottables[index]);
  8129. else
  8130. {
  8131. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  8132. return false;
  8133. }
  8134. }
  8135. /*!
  8136. Removes all plottables from the plot (and the QCustomPlot::legend, if necessary).
  8137. Returns the number of plottables removed.
  8138. \see removePlottable
  8139. */
  8140. int QCustomPlot::clearPlottables()
  8141. {
  8142. int c = mPlottables.size();
  8143. for (int i=c-1; i >= 0; --i)
  8144. removePlottable(mPlottables[i]);
  8145. return c;
  8146. }
  8147. /*!
  8148. Returns the number of currently existing plottables in the plot
  8149. \see plottable, addPlottable
  8150. */
  8151. int QCustomPlot::plottableCount() const
  8152. {
  8153. return mPlottables.size();
  8154. }
  8155. /*!
  8156. Returns a list of the selected plottables. If no plottables are currently selected, the list is empty.
  8157. There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs.
  8158. \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected
  8159. */
  8160. QList<QCPAbstractPlottable*> QCustomPlot::selectedPlottables() const
  8161. {
  8162. QList<QCPAbstractPlottable*> result;
  8163. foreach (QCPAbstractPlottable *plottable, mPlottables)
  8164. {
  8165. if (plottable->selected())
  8166. result.append(plottable);
  8167. }
  8168. return result;
  8169. }
  8170. /*!
  8171. Returns the plottable at the pixel position \a pos. Plottables that only consist of single lines
  8172. (like graphs) have a tolerance band around them, see \ref setSelectionTolerance. If multiple
  8173. plottables come into consideration, the one closest to \a pos is returned.
  8174. If \a onlySelectable is true, only plottables that are selectable
  8175. (QCPAbstractPlottable::setSelectable) are considered.
  8176. If there is no plottable at \a pos, the return value is 0.
  8177. \see itemAt, layoutElementAt
  8178. */
  8179. QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable) const
  8180. {
  8181. QCPAbstractPlottable *resultPlottable = 0;
  8182. double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value
  8183. foreach (QCPAbstractPlottable *plottable, mPlottables)
  8184. {
  8185. 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
  8186. continue;
  8187. 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
  8188. {
  8189. double currentDistance = plottable->selectTest(pos, false);
  8190. if (currentDistance >= 0 && currentDistance < resultDistance)
  8191. {
  8192. resultPlottable = plottable;
  8193. resultDistance = currentDistance;
  8194. }
  8195. }
  8196. }
  8197. return resultPlottable;
  8198. }
  8199. /*!
  8200. Returns whether this QCustomPlot instance contains the \a plottable.
  8201. \see addPlottable
  8202. */
  8203. bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const
  8204. {
  8205. return mPlottables.contains(plottable);
  8206. }
  8207. /*!
  8208. Returns the graph with \a index. If the index is invalid, returns 0.
  8209. There is an overloaded version of this function with no parameter which returns the last created
  8210. graph, see QCustomPlot::graph()
  8211. \see graphCount, addGraph
  8212. */
  8213. QCPGraph *QCustomPlot::graph(int index) const
  8214. {
  8215. if (index >= 0 && index < mGraphs.size())
  8216. {
  8217. return mGraphs.at(index);
  8218. } else
  8219. {
  8220. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  8221. return 0;
  8222. }
  8223. }
  8224. /*! \overload
  8225. Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot,
  8226. returns 0.
  8227. \see graphCount, addGraph
  8228. */
  8229. QCPGraph *QCustomPlot::graph() const
  8230. {
  8231. if (!mGraphs.isEmpty())
  8232. {
  8233. return mGraphs.last();
  8234. } else
  8235. return 0;
  8236. }
  8237. /*!
  8238. Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the
  8239. bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a
  8240. keyAxis and \a valueAxis must reside in this QCustomPlot.
  8241. \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically
  8242. "y") for the graph.
  8243. Returns a pointer to the newly created graph, or 0 if adding the graph failed.
  8244. \see graph, graphCount, removeGraph, clearGraphs
  8245. */
  8246. QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis)
  8247. {
  8248. if (!keyAxis) keyAxis = xAxis;
  8249. if (!valueAxis) valueAxis = yAxis;
  8250. if (!keyAxis || !valueAxis)
  8251. {
  8252. qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)";
  8253. return 0;
  8254. }
  8255. if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this)
  8256. {
  8257. qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent";
  8258. return 0;
  8259. }
  8260. QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis);
  8261. if (addPlottable(newGraph))
  8262. {
  8263. newGraph->setName("Graph "+QString::number(mGraphs.size()));
  8264. return newGraph;
  8265. } else
  8266. {
  8267. delete newGraph;
  8268. return 0;
  8269. }
  8270. }
  8271. /*!
  8272. Removes the specified \a graph from the plot and, if necessary, from the QCustomPlot::legend. If
  8273. any other graphs in the plot have a channel fill set towards the removed graph, the channel fill
  8274. property of those graphs is reset to zero (no channel fill).
  8275. Returns true on success.
  8276. \see clearGraphs
  8277. */
  8278. bool QCustomPlot::removeGraph(QCPGraph *graph)
  8279. {
  8280. return removePlottable(graph);
  8281. }
  8282. /*! \overload
  8283. Removes the graph by its \a index.
  8284. */
  8285. bool QCustomPlot::removeGraph(int index)
  8286. {
  8287. if (index >= 0 && index < mGraphs.size())
  8288. return removeGraph(mGraphs[index]);
  8289. else
  8290. return false;
  8291. }
  8292. /*!
  8293. Removes all graphs from the plot (and the QCustomPlot::legend, if necessary).
  8294. Returns the number of graphs removed.
  8295. \see removeGraph
  8296. */
  8297. int QCustomPlot::clearGraphs()
  8298. {
  8299. int c = mGraphs.size();
  8300. for (int i=c-1; i >= 0; --i)
  8301. removeGraph(mGraphs[i]);
  8302. return c;
  8303. }
  8304. /*!
  8305. Returns the number of currently existing graphs in the plot
  8306. \see graph, addGraph
  8307. */
  8308. int QCustomPlot::graphCount() const
  8309. {
  8310. return mGraphs.size();
  8311. }
  8312. /*!
  8313. Returns a list of the selected graphs. If no graphs are currently selected, the list is empty.
  8314. If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars,
  8315. etc., use \ref selectedPlottables.
  8316. \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected
  8317. */
  8318. QList<QCPGraph*> QCustomPlot::selectedGraphs() const
  8319. {
  8320. QList<QCPGraph*> result;
  8321. foreach (QCPGraph *graph, mGraphs)
  8322. {
  8323. if (graph->selected())
  8324. result.append(graph);
  8325. }
  8326. return result;
  8327. }
  8328. /*!
  8329. Returns the item with \a index. If the index is invalid, returns 0.
  8330. There is an overloaded version of this function with no parameter which returns the last added
  8331. item, see QCustomPlot::item()
  8332. \see itemCount, addItem
  8333. */
  8334. QCPAbstractItem *QCustomPlot::item(int index) const
  8335. {
  8336. if (index >= 0 && index < mItems.size())
  8337. {
  8338. return mItems.at(index);
  8339. } else
  8340. {
  8341. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  8342. return 0;
  8343. }
  8344. }
  8345. /*! \overload
  8346. Returns the last item, that was added with \ref addItem. If there are no items in the plot,
  8347. returns 0.
  8348. \see itemCount, addItem
  8349. */
  8350. QCPAbstractItem *QCustomPlot::item() const
  8351. {
  8352. if (!mItems.isEmpty())
  8353. {
  8354. return mItems.last();
  8355. } else
  8356. return 0;
  8357. }
  8358. /*!
  8359. Adds the specified item to the plot. QCustomPlot takes ownership of the item.
  8360. Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a
  8361. item is this QCustomPlot.
  8362. \see item, itemCount, removeItem, clearItems
  8363. */
  8364. bool QCustomPlot::addItem(QCPAbstractItem *item)
  8365. {
  8366. if (!mItems.contains(item) && item->parentPlot() == this)
  8367. {
  8368. mItems.append(item);
  8369. return true;
  8370. } else
  8371. {
  8372. qDebug() << Q_FUNC_INFO << "item either already in list or not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(item);
  8373. return false;
  8374. }
  8375. }
  8376. /*!
  8377. Removes the specified item from the plot.
  8378. Returns true on success.
  8379. \see addItem, clearItems
  8380. */
  8381. bool QCustomPlot::removeItem(QCPAbstractItem *item)
  8382. {
  8383. if (mItems.contains(item))
  8384. {
  8385. delete item;
  8386. mItems.removeOne(item);
  8387. return true;
  8388. } else
  8389. {
  8390. qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast<quintptr>(item);
  8391. return false;
  8392. }
  8393. }
  8394. /*! \overload
  8395. Removes the item by its \a index.
  8396. */
  8397. bool QCustomPlot::removeItem(int index)
  8398. {
  8399. if (index >= 0 && index < mItems.size())
  8400. return removeItem(mItems[index]);
  8401. else
  8402. {
  8403. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  8404. return false;
  8405. }
  8406. }
  8407. /*!
  8408. Removes all items from the plot.
  8409. Returns the number of items removed.
  8410. \see removeItem
  8411. */
  8412. int QCustomPlot::clearItems()
  8413. {
  8414. int c = mItems.size();
  8415. for (int i=c-1; i >= 0; --i)
  8416. removeItem(mItems[i]);
  8417. return c;
  8418. }
  8419. /*!
  8420. Returns the number of currently existing items in the plot
  8421. \see item, addItem
  8422. */
  8423. int QCustomPlot::itemCount() const
  8424. {
  8425. return mItems.size();
  8426. }
  8427. /*!
  8428. Returns a list of the selected items. If no items are currently selected, the list is empty.
  8429. \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected
  8430. */
  8431. QList<QCPAbstractItem*> QCustomPlot::selectedItems() const
  8432. {
  8433. QList<QCPAbstractItem*> result;
  8434. foreach (QCPAbstractItem *item, mItems)
  8435. {
  8436. if (item->selected())
  8437. result.append(item);
  8438. }
  8439. return result;
  8440. }
  8441. /*!
  8442. Returns the item at the pixel position \a pos. Items that only consist of single lines (e.g. \ref
  8443. QCPItemLine or \ref QCPItemCurve) have a tolerance band around them, see \ref
  8444. setSelectionTolerance. If multiple items come into consideration, the one closest to \a pos is
  8445. returned.
  8446. If \a onlySelectable is true, only items that are selectable (QCPAbstractItem::setSelectable) are
  8447. considered.
  8448. If there is no item at \a pos, the return value is 0.
  8449. \see plottableAt, layoutElementAt
  8450. */
  8451. QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const
  8452. {
  8453. QCPAbstractItem *resultItem = 0;
  8454. double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value
  8455. foreach (QCPAbstractItem *item, mItems)
  8456. {
  8457. 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
  8458. continue;
  8459. if (!item->clipToAxisRect() || item->clipRect().contains(pos.toPoint())) // only consider clicks inside axis cliprect of the item if actually clipped to it
  8460. {
  8461. double currentDistance = item->selectTest(pos, false);
  8462. if (currentDistance >= 0 && currentDistance < resultDistance)
  8463. {
  8464. resultItem = item;
  8465. resultDistance = currentDistance;
  8466. }
  8467. }
  8468. }
  8469. return resultItem;
  8470. }
  8471. /*!
  8472. Returns whether this QCustomPlot contains the \a item.
  8473. \see addItem
  8474. */
  8475. bool QCustomPlot::hasItem(QCPAbstractItem *item) const
  8476. {
  8477. return mItems.contains(item);
  8478. }
  8479. /*!
  8480. Returns the layer with the specified \a name. If there is no layer with the specified name, 0 is
  8481. returned.
  8482. Layer names are case-sensitive.
  8483. \see addLayer, moveLayer, removeLayer
  8484. */
  8485. QCPLayer *QCustomPlot::layer(const QString &name) const
  8486. {
  8487. foreach (QCPLayer *layer, mLayers)
  8488. {
  8489. if (layer->name() == name)
  8490. return layer;
  8491. }
  8492. return 0;
  8493. }
  8494. /*! \overload
  8495. Returns the layer by \a index. If the index is invalid, 0 is returned.
  8496. \see addLayer, moveLayer, removeLayer
  8497. */
  8498. QCPLayer *QCustomPlot::layer(int index) const
  8499. {
  8500. if (index >= 0 && index < mLayers.size())
  8501. {
  8502. return mLayers.at(index);
  8503. } else
  8504. {
  8505. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  8506. return 0;
  8507. }
  8508. }
  8509. /*!
  8510. Returns the layer that is set as current layer (see \ref setCurrentLayer).
  8511. */
  8512. QCPLayer *QCustomPlot::currentLayer() const
  8513. {
  8514. return mCurrentLayer;
  8515. }
  8516. /*!
  8517. Sets the layer with the specified \a name to be the current layer. All layerables (\ref
  8518. QCPLayerable), e.g. plottables and items, are created on the current layer.
  8519. Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot.
  8520. Layer names are case-sensitive.
  8521. \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer
  8522. */
  8523. bool QCustomPlot::setCurrentLayer(const QString &name)
  8524. {
  8525. if (QCPLayer *newCurrentLayer = layer(name))
  8526. {
  8527. return setCurrentLayer(newCurrentLayer);
  8528. } else
  8529. {
  8530. qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name;
  8531. return false;
  8532. }
  8533. }
  8534. /*! \overload
  8535. Sets the provided \a layer to be the current layer.
  8536. Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot.
  8537. \see addLayer, moveLayer, removeLayer
  8538. */
  8539. bool QCustomPlot::setCurrentLayer(QCPLayer *layer)
  8540. {
  8541. if (!mLayers.contains(layer))
  8542. {
  8543. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  8544. return false;
  8545. }
  8546. mCurrentLayer = layer;
  8547. return true;
  8548. }
  8549. /*!
  8550. Returns the number of currently existing layers in the plot
  8551. \see layer, addLayer
  8552. */
  8553. int QCustomPlot::layerCount() const
  8554. {
  8555. return mLayers.size();
  8556. }
  8557. /*!
  8558. Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which
  8559. must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer.
  8560. Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a
  8561. valid layer inside this QCustomPlot.
  8562. If \a otherLayer is 0, the highest layer in the QCustomPlot will be used.
  8563. For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer.
  8564. \see layer, moveLayer, removeLayer
  8565. */
  8566. bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
  8567. {
  8568. if (!otherLayer)
  8569. otherLayer = mLayers.last();
  8570. if (!mLayers.contains(otherLayer))
  8571. {
  8572. qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
  8573. return false;
  8574. }
  8575. if (layer(name))
  8576. {
  8577. qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name;
  8578. return false;
  8579. }
  8580. QCPLayer *newLayer = new QCPLayer(this, name);
  8581. mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer);
  8582. updateLayerIndices();
  8583. return true;
  8584. }
  8585. /*!
  8586. Removes the specified \a layer and returns true on success.
  8587. All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below
  8588. \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both
  8589. cases, the total rendering order of all layerables in the QCustomPlot is preserved.
  8590. If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom
  8591. layer) becomes the new current layer.
  8592. It is not possible to remove the last layer of the plot.
  8593. \see layer, addLayer, moveLayer
  8594. */
  8595. bool QCustomPlot::removeLayer(QCPLayer *layer)
  8596. {
  8597. if (!mLayers.contains(layer))
  8598. {
  8599. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  8600. return false;
  8601. }
  8602. if (mLayers.size() < 2)
  8603. {
  8604. qDebug() << Q_FUNC_INFO << "can't remove last layer";
  8605. return false;
  8606. }
  8607. // append all children of this layer to layer below (if this is lowest layer, prepend to layer above)
  8608. int removedIndex = layer->index();
  8609. bool isFirstLayer = removedIndex==0;
  8610. QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1);
  8611. QList<QCPLayerable*> children = layer->children();
  8612. if (isFirstLayer) // prepend in reverse order (so order relative to each other stays the same)
  8613. {
  8614. for (int i=children.size()-1; i>=0; --i)
  8615. children.at(i)->moveToLayer(targetLayer, true);
  8616. } else // append normally
  8617. {
  8618. for (int i=0; i<children.size(); ++i)
  8619. children.at(i)->moveToLayer(targetLayer, false);
  8620. }
  8621. // if removed layer is current layer, change current layer to layer below/above:
  8622. if (layer == mCurrentLayer)
  8623. setCurrentLayer(targetLayer);
  8624. // remove layer:
  8625. delete layer;
  8626. mLayers.removeOne(layer);
  8627. updateLayerIndices();
  8628. return true;
  8629. }
  8630. /*!
  8631. Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or
  8632. below is controlled with \a insertMode.
  8633. Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the
  8634. QCustomPlot.
  8635. \see layer, addLayer, moveLayer
  8636. */
  8637. bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
  8638. {
  8639. if (!mLayers.contains(layer))
  8640. {
  8641. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  8642. return false;
  8643. }
  8644. if (!mLayers.contains(otherLayer))
  8645. {
  8646. qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
  8647. return false;
  8648. }
  8649. mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0));
  8650. updateLayerIndices();
  8651. return true;
  8652. }
  8653. /*!
  8654. Returns the number of axis rects in the plot.
  8655. All axis rects can be accessed via QCustomPlot::axisRect().
  8656. Initially, only one axis rect exists in the plot.
  8657. \see axisRect, axisRects
  8658. */
  8659. int QCustomPlot::axisRectCount() const
  8660. {
  8661. return axisRects().size();
  8662. }
  8663. /*!
  8664. Returns the axis rect with \a index.
  8665. Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were
  8666. added, all of them may be accessed with this function in a linear fashion (even when they are
  8667. nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout).
  8668. \see axisRectCount, axisRects
  8669. */
  8670. QCPAxisRect *QCustomPlot::axisRect(int index) const
  8671. {
  8672. const QList<QCPAxisRect*> rectList = axisRects();
  8673. if (index >= 0 && index < rectList.size())
  8674. {
  8675. return rectList.at(index);
  8676. } else
  8677. {
  8678. qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index;
  8679. return 0;
  8680. }
  8681. }
  8682. /*!
  8683. Returns all axis rects in the plot.
  8684. \see axisRectCount, axisRect
  8685. */
  8686. QList<QCPAxisRect*> QCustomPlot::axisRects() const
  8687. {
  8688. QList<QCPAxisRect*> result;
  8689. QStack<QCPLayoutElement*> elementStack;
  8690. if (mPlotLayout)
  8691. elementStack.push(mPlotLayout);
  8692. while (!elementStack.isEmpty())
  8693. {
  8694. foreach (QCPLayoutElement *element, elementStack.pop()->elements(false))
  8695. {
  8696. if (element)
  8697. {
  8698. elementStack.push(element);
  8699. if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(element))
  8700. result.append(ar);
  8701. }
  8702. }
  8703. }
  8704. return result;
  8705. }
  8706. /*!
  8707. Returns the layout element at pixel position \a pos. If there is no element at that position,
  8708. returns 0.
  8709. Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on
  8710. any of its parent elements is set to false, it will not be considered.
  8711. \see itemAt, plottableAt
  8712. */
  8713. QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const
  8714. {
  8715. QCPLayoutElement *currentElement = mPlotLayout;
  8716. bool searchSubElements = true;
  8717. while (searchSubElements && currentElement)
  8718. {
  8719. searchSubElements = false;
  8720. foreach (QCPLayoutElement *subElement, currentElement->elements(false))
  8721. {
  8722. if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
  8723. {
  8724. currentElement = subElement;
  8725. searchSubElements = true;
  8726. break;
  8727. }
  8728. }
  8729. }
  8730. return currentElement;
  8731. }
  8732. /*!
  8733. Returns the axes that currently have selected parts, i.e. whose selection state is not \ref
  8734. QCPAxis::spNone.
  8735. \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts,
  8736. QCPAxis::setSelectableParts
  8737. */
  8738. QList<QCPAxis*> QCustomPlot::selectedAxes() const
  8739. {
  8740. QList<QCPAxis*> result, allAxes;
  8741. foreach (QCPAxisRect *rect, axisRects())
  8742. allAxes << rect->axes();
  8743. foreach (QCPAxis *axis, allAxes)
  8744. {
  8745. if (axis->selectedParts() != QCPAxis::spNone)
  8746. result.append(axis);
  8747. }
  8748. return result;
  8749. }
  8750. /*!
  8751. Returns the legends that currently have selected parts, i.e. whose selection state is not \ref
  8752. QCPLegend::spNone.
  8753. \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts,
  8754. QCPLegend::setSelectableParts, QCPLegend::selectedItems
  8755. */
  8756. QList<QCPLegend*> QCustomPlot::selectedLegends() const
  8757. {
  8758. QList<QCPLegend*> result;
  8759. QStack<QCPLayoutElement*> elementStack;
  8760. if (mPlotLayout)
  8761. elementStack.push(mPlotLayout);
  8762. while (!elementStack.isEmpty())
  8763. {
  8764. foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false))
  8765. {
  8766. if (subElement)
  8767. {
  8768. elementStack.push(subElement);
  8769. if (QCPLegend *leg = qobject_cast<QCPLegend*>(subElement))
  8770. {
  8771. if (leg->selectedParts() != QCPLegend::spNone)
  8772. result.append(leg);
  8773. }
  8774. }
  8775. }
  8776. }
  8777. return result;
  8778. }
  8779. /*!
  8780. Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot.
  8781. Since calling this function is not a user interaction, this does not emit the \ref
  8782. selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the
  8783. objects were previously selected.
  8784. \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends
  8785. */
  8786. void QCustomPlot::deselectAll()
  8787. {
  8788. foreach (QCPLayer *layer, mLayers)
  8789. {
  8790. foreach (QCPLayerable *layerable, layer->children())
  8791. layerable->deselectEvent(0);
  8792. }
  8793. }
  8794. /*!
  8795. Causes a complete replot into the internal buffer. Finally, update() is called, to redraw the
  8796. buffer on the QCustomPlot widget surface. This is the method that must be called to make changes,
  8797. for example on the axis ranges or data points of graphs, visible.
  8798. Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the
  8799. QCustomPlot widget and user interactions (object selection and range dragging/zooming).
  8800. Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref
  8801. afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two
  8802. signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite
  8803. recursion.
  8804. */
  8805. void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority)
  8806. {
  8807. if (mReplotting) // incase signals loop back to replot slot
  8808. return;
  8809. mReplotting = true;
  8810. emit beforeReplot();
  8811. mPaintBuffer.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent);
  8812. QCPPainter painter;
  8813. painter.begin(&mPaintBuffer);
  8814. if (painter.isActive())
  8815. {
  8816. painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem
  8817. if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush)
  8818. painter.fillRect(mViewport, mBackgroundBrush);
  8819. draw(&painter);
  8820. painter.end();
  8821. if ((refreshPriority == rpHint && mPlottingHints.testFlag(QCP::phForceRepaint)) || refreshPriority==rpImmediate)
  8822. repaint();
  8823. else
  8824. update();
  8825. } else // might happen if QCustomPlot has width or height zero
  8826. qDebug() << Q_FUNC_INFO << "Couldn't activate painter on buffer";
  8827. emit afterReplot();
  8828. mReplotting = false;
  8829. }
  8830. /*!
  8831. Rescales the axes such that all plottables (like graphs) in the plot are fully visible.
  8832. if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true
  8833. (QCPLayerable::setVisible), will be used to rescale the axes.
  8834. \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale
  8835. */
  8836. void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables)
  8837. {
  8838. QList<QCPAxis*> allAxes;
  8839. foreach (QCPAxisRect *rect, axisRects())
  8840. allAxes << rect->axes();
  8841. foreach (QCPAxis *axis, allAxes)
  8842. axis->rescale(onlyVisiblePlottables);
  8843. }
  8844. /*!
  8845. Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale
  8846. of texts and lines will be derived from the specified \a width and \a height. This means, the
  8847. output will look like the normal on-screen output of a QCustomPlot widget with the corresponding
  8848. pixel width and height. If either \a width or \a height is zero, the exported image will have the
  8849. same dimensions as the QCustomPlot widget currently has.
  8850. \a noCosmeticPen disables the use of cosmetic pens when drawing to the PDF file. Cosmetic pens
  8851. are pens with numerical width 0, which are always drawn as a one pixel wide line, no matter what
  8852. zoom factor is set in the PDF-Viewer. For more information about cosmetic pens, see the QPainter
  8853. and QPen documentation.
  8854. The objects of the plot will appear in the current selection state. If you don't want any
  8855. selected objects to be painted in their selected look, deselect everything with \ref deselectAll
  8856. before calling this function.
  8857. Returns true on success.
  8858. \warning
  8859. \li If you plan on editing the exported PDF file with a vector graphics editor like
  8860. Inkscape, it is advised to set \a noCosmeticPen to true to avoid losing those cosmetic lines
  8861. (which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks).
  8862. \li If calling this function inside the constructor of the parent of the QCustomPlot widget
  8863. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  8864. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  8865. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  8866. aren't defined yet inside the constructor, so you would get an image that has strange
  8867. widths/heights.
  8868. \a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting
  8869. PDF file.
  8870. \note On Android systems, this method does nothing and issues an according qDebug warning
  8871. message. This is also the case if for other reasons the define flag QT_NO_PRINTER is set.
  8872. \see savePng, saveBmp, saveJpg, saveRastered
  8873. */
  8874. bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width, int height, const QString &pdfCreator, const QString &pdfTitle)
  8875. {
  8876. bool success = false;
  8877. #ifdef QT_NO_PRINTER
  8878. Q_UNUSED(fileName)
  8879. Q_UNUSED(noCosmeticPen)
  8880. Q_UNUSED(width)
  8881. Q_UNUSED(height)
  8882. qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created.";
  8883. #else
  8884. int newWidth, newHeight;
  8885. if (width == 0 || height == 0)
  8886. {
  8887. newWidth = this->width();
  8888. newHeight = this->height();
  8889. } else
  8890. {
  8891. newWidth = width;
  8892. newHeight = height;
  8893. }
  8894. QPrinter printer(QPrinter::ScreenResolution);
  8895. printer.setOutputFileName(fileName);
  8896. printer.setOutputFormat(QPrinter::PdfFormat);
  8897. printer.setFullPage(true);
  8898. printer.setColorMode(QPrinter::Color);
  8899. printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator);
  8900. printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle);
  8901. QRect oldViewport = viewport();
  8902. setViewport(QRect(0, 0, newWidth, newHeight));
  8903. printer.setPaperSize(viewport().size(), QPrinter::DevicePixel);
  8904. QCPPainter printpainter;
  8905. if (printpainter.begin(&printer))
  8906. {
  8907. printpainter.setMode(QCPPainter::pmVectorized);
  8908. printpainter.setMode(QCPPainter::pmNoCaching);
  8909. printpainter.setMode(QCPPainter::pmNonCosmetic, noCosmeticPen);
  8910. printpainter.setWindow(mViewport);
  8911. if (mBackgroundBrush.style() != Qt::NoBrush &&
  8912. mBackgroundBrush.color() != Qt::white &&
  8913. mBackgroundBrush.color() != Qt::transparent &&
  8914. mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent
  8915. printpainter.fillRect(viewport(), mBackgroundBrush);
  8916. draw(&printpainter);
  8917. printpainter.end();
  8918. success = true;
  8919. }
  8920. setViewport(oldViewport);
  8921. #endif // QT_NO_PRINTER
  8922. return success;
  8923. }
  8924. /*!
  8925. Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width
  8926. and \a height in pixels. If either \a width or \a height is zero, the exported image will have
  8927. the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not
  8928. scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter.
  8929. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  8930. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  8931. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  8932. 200*200 pixel resolution.
  8933. If you use a high scaling factor, it is recommended to enable antialiasing for all elements via
  8934. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  8935. QCustomPlot to place objects with sub-pixel accuracy.
  8936. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  8937. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  8938. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  8939. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  8940. aren't defined yet inside the constructor, so you would get an image that has strange
  8941. widths/heights.
  8942. The objects of the plot will appear in the current selection state. If you don't want any selected
  8943. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  8944. this function.
  8945. If you want the PNG to have a transparent background, call \ref setBackground(const QBrush
  8946. &brush) with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving.
  8947. PNG compression can be controlled with the \a quality parameter which must be between 0 and 100 or
  8948. -1 to use the default setting.
  8949. Returns true on success. If this function fails, most likely the PNG format isn't supported by
  8950. the system, see Qt docs about QImageWriter::supportedImageFormats().
  8951. \see savePdf, saveBmp, saveJpg, saveRastered
  8952. */
  8953. bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality)
  8954. {
  8955. return saveRastered(fileName, width, height, scale, "PNG", quality);
  8956. }
  8957. /*!
  8958. Saves a JPG image file to \a fileName on disc. The output plot will have the dimensions \a width
  8959. and \a height in pixels. If either \a width or \a height is zero, the exported image will have
  8960. the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not
  8961. scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter.
  8962. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  8963. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  8964. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  8965. 200*200 pixel resolution.
  8966. If you use a high scaling factor, it is recommended to enable antialiasing for all elements via
  8967. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  8968. QCustomPlot to place objects with sub-pixel accuracy.
  8969. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  8970. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  8971. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  8972. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  8973. aren't defined yet inside the constructor, so you would get an image that has strange
  8974. widths/heights.
  8975. The objects of the plot will appear in the current selection state. If you don't want any selected
  8976. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  8977. this function.
  8978. JPG compression can be controlled with the \a quality parameter which must be between 0 and 100 or
  8979. -1 to use the default setting.
  8980. Returns true on success. If this function fails, most likely the JPG format isn't supported by
  8981. the system, see Qt docs about QImageWriter::supportedImageFormats().
  8982. \see savePdf, savePng, saveBmp, saveRastered
  8983. */
  8984. bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality)
  8985. {
  8986. return saveRastered(fileName, width, height, scale, "JPG", quality);
  8987. }
  8988. /*!
  8989. Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width
  8990. and \a height in pixels. If either \a width or \a height is zero, the exported image will have
  8991. the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not
  8992. scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter.
  8993. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  8994. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  8995. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  8996. 200*200 pixel resolution.
  8997. If you use a high scaling factor, it is recommended to enable antialiasing for all elements via
  8998. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  8999. QCustomPlot to place objects with sub-pixel accuracy.
  9000. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  9001. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  9002. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  9003. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  9004. aren't defined yet inside the constructor, so you would get an image that has strange
  9005. widths/heights.
  9006. The objects of the plot will appear in the current selection state. If you don't want any selected
  9007. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  9008. this function.
  9009. Returns true on success. If this function fails, most likely the BMP format isn't supported by
  9010. the system, see Qt docs about QImageWriter::supportedImageFormats().
  9011. \see savePdf, savePng, saveJpg, saveRastered
  9012. */
  9013. bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale)
  9014. {
  9015. return saveRastered(fileName, width, height, scale, "BMP");
  9016. }
  9017. /*! \internal
  9018. Returns a minimum size hint that corresponds to the minimum size of the top level layout
  9019. (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum
  9020. size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot.
  9021. This is especially important, when placed in a QLayout where other components try to take in as
  9022. much space as possible (e.g. QMdiArea).
  9023. */
  9024. QSize QCustomPlot::minimumSizeHint() const
  9025. {
  9026. return mPlotLayout->minimumSizeHint();
  9027. }
  9028. /*! \internal
  9029. Returns a size hint that is the same as \ref minimumSizeHint.
  9030. */
  9031. QSize QCustomPlot::sizeHint() const
  9032. {
  9033. return mPlotLayout->minimumSizeHint();
  9034. }
  9035. /*! \internal
  9036. Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but
  9037. draws the internal buffer on the widget surface.
  9038. */
  9039. void QCustomPlot::paintEvent(QPaintEvent *event)
  9040. {
  9041. Q_UNUSED(event);
  9042. QPainter painter(this);
  9043. painter.drawPixmap(0, 0, mPaintBuffer);
  9044. }
  9045. /*! \internal
  9046. Event handler for a resize of the QCustomPlot widget. Causes the internal buffer to be resized to
  9047. the new size. The viewport (which becomes the outer rect of mPlotLayout) is resized
  9048. appropriately. Finally a \ref replot is performed.
  9049. */
  9050. void QCustomPlot::resizeEvent(QResizeEvent *event)
  9051. {
  9052. // resize and repaint the buffer:
  9053. mPaintBuffer = QPixmap(event->size());
  9054. setViewport(rect());
  9055. replot(rpQueued); // queued update is important here, to prevent painting issues in some contexts
  9056. }
  9057. /*! \internal
  9058. Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then emits
  9059. the specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref
  9060. axisDoubleClick, etc.). Finally determines the affected layout element and forwards the event to
  9061. it.
  9062. \see mousePressEvent, mouseReleaseEvent
  9063. */
  9064. void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event)
  9065. {
  9066. emit mouseDoubleClick(event);
  9067. QVariant details;
  9068. QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details);
  9069. // emit specialized object double click signals:
  9070. if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(clickedLayerable))
  9071. emit plottableDoubleClick(ap, event);
  9072. else if (QCPAxis *ax = qobject_cast<QCPAxis*>(clickedLayerable))
  9073. emit axisDoubleClick(ax, details.value<QCPAxis::SelectablePart>(), event);
  9074. else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(clickedLayerable))
  9075. emit itemDoubleClick(ai, event);
  9076. else if (QCPLegend *lg = qobject_cast<QCPLegend*>(clickedLayerable))
  9077. emit legendDoubleClick(lg, 0, event);
  9078. else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(clickedLayerable))
  9079. emit legendDoubleClick(li->parentLegend(), li, event);
  9080. else if (QCPPlotTitle *pt = qobject_cast<QCPPlotTitle*>(clickedLayerable))
  9081. emit titleDoubleClick(event, pt);
  9082. // call double click event of affected layout element:
  9083. if (QCPLayoutElement *el = layoutElementAt(event->pos()))
  9084. el->mouseDoubleClickEvent(event);
  9085. // call release event of affected layout element (as in mouseReleaseEvent, since the mouseDoubleClick replaces the second release event in double click case):
  9086. if (mMouseEventElement)
  9087. {
  9088. mMouseEventElement->mouseReleaseEvent(event);
  9089. mMouseEventElement = 0;
  9090. }
  9091. //QWidget::mouseDoubleClickEvent(event); don't call base class implementation because it would just cause a mousePress/ReleaseEvent, which we don't want.
  9092. }
  9093. /*! \internal
  9094. Event handler for when a mouse button is pressed. Emits the mousePress signal. Then determines
  9095. the affected layout element and forwards the event to it.
  9096. \see mouseMoveEvent, mouseReleaseEvent
  9097. */
  9098. void QCustomPlot::mousePressEvent(QMouseEvent *event)
  9099. {
  9100. emit mousePress(event);
  9101. mMousePressPos = event->pos(); // need this to determine in releaseEvent whether it was a click (no position change between press and release)
  9102. // call event of affected layout element:
  9103. mMouseEventElement = layoutElementAt(event->pos());
  9104. if (mMouseEventElement)
  9105. mMouseEventElement->mousePressEvent(event);
  9106. QWidget::mousePressEvent(event);
  9107. }
  9108. /*! \internal
  9109. Event handler for when the cursor is moved. Emits the \ref mouseMove signal.
  9110. If a layout element has mouse capture focus (a mousePressEvent happened on top of the layout
  9111. element before), the mouseMoveEvent is forwarded to that element.
  9112. \see mousePressEvent, mouseReleaseEvent
  9113. */
  9114. void QCustomPlot::mouseMoveEvent(QMouseEvent *event)
  9115. {
  9116. emit mouseMove(event);
  9117. // call event of affected layout element:
  9118. if (mMouseEventElement)
  9119. mMouseEventElement->mouseMoveEvent(event);
  9120. QWidget::mouseMoveEvent(event);
  9121. }
  9122. /*! \internal
  9123. Event handler for when a mouse button is released. Emits the \ref mouseRelease signal.
  9124. If the mouse was moved less than a certain threshold in any direction since the \ref
  9125. mousePressEvent, it is considered a click which causes the selection mechanism (if activated via
  9126. \ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse
  9127. click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.)
  9128. If a layout element has mouse capture focus (a \ref mousePressEvent happened on top of the layout
  9129. element before), the \ref mouseReleaseEvent is forwarded to that element.
  9130. \see mousePressEvent, mouseMoveEvent
  9131. */
  9132. void QCustomPlot::mouseReleaseEvent(QMouseEvent *event)
  9133. {
  9134. emit mouseRelease(event);
  9135. bool doReplot = false;
  9136. if ((mMousePressPos-event->pos()).manhattanLength() < 5) // determine whether it was a click operation
  9137. {
  9138. if (event->button() == Qt::LeftButton)
  9139. {
  9140. // handle selection mechanism:
  9141. QVariant details;
  9142. QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details);
  9143. bool selectionStateChanged = false;
  9144. bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier);
  9145. // deselect all other layerables if not additive selection:
  9146. if (!additive)
  9147. {
  9148. foreach (QCPLayer *layer, mLayers)
  9149. {
  9150. foreach (QCPLayerable *layerable, layer->children())
  9151. {
  9152. if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory()))
  9153. {
  9154. bool selChanged = false;
  9155. layerable->deselectEvent(&selChanged);
  9156. selectionStateChanged |= selChanged;
  9157. }
  9158. }
  9159. }
  9160. }
  9161. if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory()))
  9162. {
  9163. // a layerable was actually clicked, call its selectEvent:
  9164. bool selChanged = false;
  9165. clickedLayerable->selectEvent(event, additive, details, &selChanged);
  9166. selectionStateChanged |= selChanged;
  9167. }
  9168. doReplot = true;
  9169. if (selectionStateChanged)
  9170. emit selectionChangedByUser();
  9171. }
  9172. // emit specialized object click signals:
  9173. QVariant details;
  9174. QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details); // for these signals, selectability is ignored, that's why we call this again with onlySelectable set to false
  9175. if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(clickedLayerable))
  9176. emit plottableClick(ap, event);
  9177. else if (QCPAxis *ax = qobject_cast<QCPAxis*>(clickedLayerable))
  9178. emit axisClick(ax, details.value<QCPAxis::SelectablePart>(), event);
  9179. else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(clickedLayerable))
  9180. emit itemClick(ai, event);
  9181. else if (QCPLegend *lg = qobject_cast<QCPLegend*>(clickedLayerable))
  9182. emit legendClick(lg, 0, event);
  9183. else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(clickedLayerable))
  9184. emit legendClick(li->parentLegend(), li, event);
  9185. else if (QCPPlotTitle *pt = qobject_cast<QCPPlotTitle*>(clickedLayerable))
  9186. emit titleClick(event, pt);
  9187. }
  9188. // call event of affected layout element:
  9189. if (mMouseEventElement)
  9190. {
  9191. mMouseEventElement->mouseReleaseEvent(event);
  9192. mMouseEventElement = 0;
  9193. }
  9194. if (doReplot || noAntialiasingOnDrag())
  9195. replot();
  9196. QWidget::mouseReleaseEvent(event);
  9197. }
  9198. /*! \internal
  9199. Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then
  9200. determines the affected layout element and forwards the event to it.
  9201. */
  9202. void QCustomPlot::wheelEvent(QWheelEvent *event)
  9203. {
  9204. emit mouseWheel(event);
  9205. // call event of affected layout element:
  9206. if (QCPLayoutElement *el = layoutElementAt(event->pos()))
  9207. el->wheelEvent(event);
  9208. QWidget::wheelEvent(event);
  9209. }
  9210. /*! \internal
  9211. This is the main draw function. It draws the entire plot, including background pixmap, with the
  9212. specified \a painter. Note that it does not fill the background with the background brush (as the
  9213. user may specify with \ref setBackground(const QBrush &brush)), this is up to the respective
  9214. functions calling this method (e.g. \ref replot, \ref toPixmap and \ref toPainter).
  9215. */
  9216. void QCustomPlot::draw(QCPPainter *painter)
  9217. {
  9218. // run through layout phases:
  9219. mPlotLayout->update(QCPLayoutElement::upPreparation);
  9220. mPlotLayout->update(QCPLayoutElement::upMargins);
  9221. mPlotLayout->update(QCPLayoutElement::upLayout);
  9222. // draw viewport background pixmap:
  9223. drawBackground(painter);
  9224. // draw all layered objects (grid, axes, plottables, items, legend,...):
  9225. foreach (QCPLayer *layer, mLayers)
  9226. {
  9227. foreach (QCPLayerable *child, layer->children())
  9228. {
  9229. if (child->realVisibility())
  9230. {
  9231. painter->save();
  9232. painter->setClipRect(child->clipRect().translated(0, -1));
  9233. child->applyDefaultAntialiasingHint(painter);
  9234. child->draw(painter);
  9235. painter->restore();
  9236. }
  9237. }
  9238. }
  9239. /* Debug code to draw all layout element rects
  9240. foreach (QCPLayoutElement* el, findChildren<QCPLayoutElement*>())
  9241. {
  9242. painter->setBrush(Qt::NoBrush);
  9243. painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine));
  9244. painter->drawRect(el->rect());
  9245. painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine));
  9246. painter->drawRect(el->outerRect());
  9247. }
  9248. */
  9249. }
  9250. /*! \internal
  9251. Draws the viewport background pixmap of the plot.
  9252. If a pixmap was provided via \ref setBackground, this function buffers the scaled version
  9253. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  9254. the viewport with the provided \a painter. The scaled version is buffered in
  9255. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  9256. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  9257. dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
  9258. set.
  9259. Note that this function does not draw a fill with the background brush (\ref setBackground(const
  9260. QBrush &brush)) beneath the pixmap.
  9261. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  9262. */
  9263. void QCustomPlot::drawBackground(QCPPainter *painter)
  9264. {
  9265. // Note: background color is handled in individual replot/save functions
  9266. // draw background pixmap (on top of fill, if brush specified):
  9267. if (!mBackgroundPixmap.isNull())
  9268. {
  9269. if (mBackgroundScaled)
  9270. {
  9271. // check whether mScaledBackground needs to be updated:
  9272. QSize scaledSize(mBackgroundPixmap.size());
  9273. scaledSize.scale(mViewport.size(), mBackgroundScaledMode);
  9274. if (mScaledBackgroundPixmap.size() != scaledSize)
  9275. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
  9276. painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect());
  9277. } else
  9278. {
  9279. painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()));
  9280. }
  9281. }
  9282. }
  9283. /*! \internal
  9284. This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot
  9285. so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly.
  9286. */
  9287. void QCustomPlot::axisRemoved(QCPAxis *axis)
  9288. {
  9289. if (xAxis == axis)
  9290. xAxis = 0;
  9291. if (xAxis2 == axis)
  9292. xAxis2 = 0;
  9293. if (yAxis == axis)
  9294. yAxis = 0;
  9295. if (yAxis2 == axis)
  9296. yAxis2 = 0;
  9297. // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers
  9298. }
  9299. /*! \internal
  9300. This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so
  9301. it may clear its QCustomPlot::legend member accordingly.
  9302. */
  9303. void QCustomPlot::legendRemoved(QCPLegend *legend)
  9304. {
  9305. if (this->legend == legend)
  9306. this->legend = 0;
  9307. }
  9308. /*! \internal
  9309. Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called
  9310. after every operation that changes the layer indices, like layer removal, layer creation, layer
  9311. moving.
  9312. */
  9313. void QCustomPlot::updateLayerIndices() const
  9314. {
  9315. for (int i=0; i<mLayers.size(); ++i)
  9316. mLayers.at(i)->mIndex = i;
  9317. }
  9318. /*! \internal
  9319. Returns the layerable at pixel position \a pos. If \a onlySelectable is set to true, only those
  9320. layerables that are selectable will be considered. (Layerable subclasses communicate their
  9321. selectability via the QCPLayerable::selectTest method, by returning -1.)
  9322. \a selectionDetails is an output parameter that contains selection specifics of the affected
  9323. layerable. This is useful if the respective layerable shall be given a subsequent
  9324. QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
  9325. information about which part of the layerable was hit, in multi-part layerables (e.g.
  9326. QCPAxis::SelectablePart).
  9327. */
  9328. QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const
  9329. {
  9330. for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex)
  9331. {
  9332. const QList<QCPLayerable*> layerables = mLayers.at(layerIndex)->children();
  9333. double minimumDistance = selectionTolerance()*1.1;
  9334. QCPLayerable *minimumDistanceLayerable = 0;
  9335. for (int i=layerables.size()-1; i>=0; --i)
  9336. {
  9337. if (!layerables.at(i)->realVisibility())
  9338. continue;
  9339. QVariant details;
  9340. double dist = layerables.at(i)->selectTest(pos, onlySelectable, &details);
  9341. if (dist >= 0 && dist < minimumDistance)
  9342. {
  9343. minimumDistance = dist;
  9344. minimumDistanceLayerable = layerables.at(i);
  9345. if (selectionDetails) *selectionDetails = details;
  9346. }
  9347. }
  9348. if (minimumDistance < selectionTolerance())
  9349. return minimumDistanceLayerable;
  9350. }
  9351. return 0;
  9352. }
  9353. /*!
  9354. Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is
  9355. sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead
  9356. to a full resolution file with width 200.) If the \a format supports compression, \a quality may
  9357. be between 0 and 100 to control it.
  9358. Returns true on success. If this function fails, most likely the given \a format isn't supported
  9359. by the system, see Qt docs about QImageWriter::supportedImageFormats().
  9360. \see saveBmp, saveJpg, savePng, savePdf
  9361. */
  9362. bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality)
  9363. {
  9364. QPixmap buffer = toPixmap(width, height, scale);
  9365. if (!buffer.isNull())
  9366. return buffer.save(fileName, format, quality);
  9367. else
  9368. return false;
  9369. }
  9370. /*!
  9371. Renders the plot to a pixmap and returns it.
  9372. The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and
  9373. scale 2.0 lead to a full resolution pixmap with width 200.)
  9374. \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf
  9375. */
  9376. QPixmap QCustomPlot::toPixmap(int width, int height, double scale)
  9377. {
  9378. // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too.
  9379. int newWidth, newHeight;
  9380. if (width == 0 || height == 0)
  9381. {
  9382. newWidth = this->width();
  9383. newHeight = this->height();
  9384. } else
  9385. {
  9386. newWidth = width;
  9387. newHeight = height;
  9388. }
  9389. int scaledWidth = qRound(scale*newWidth);
  9390. int scaledHeight = qRound(scale*newHeight);
  9391. QPixmap result(scaledWidth, scaledHeight);
  9392. result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later
  9393. QCPPainter painter;
  9394. painter.begin(&result);
  9395. if (painter.isActive())
  9396. {
  9397. QRect oldViewport = viewport();
  9398. setViewport(QRect(0, 0, newWidth, newHeight));
  9399. painter.setMode(QCPPainter::pmNoCaching);
  9400. if (!qFuzzyCompare(scale, 1.0))
  9401. {
  9402. if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales
  9403. painter.setMode(QCPPainter::pmNonCosmetic);
  9404. painter.scale(scale, scale);
  9405. }
  9406. if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush)
  9407. painter.fillRect(mViewport, mBackgroundBrush);
  9408. draw(&painter);
  9409. setViewport(oldViewport);
  9410. painter.end();
  9411. } else // might happen if pixmap has width or height zero
  9412. {
  9413. qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap";
  9414. return QPixmap();
  9415. }
  9416. return result;
  9417. }
  9418. /*!
  9419. Renders the plot using the passed \a painter.
  9420. 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
  9421. appear scaled accordingly.
  9422. \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter
  9423. on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with
  9424. the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter.
  9425. \see toPixmap
  9426. */
  9427. void QCustomPlot::toPainter(QCPPainter *painter, int width, int height)
  9428. {
  9429. // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too.
  9430. int newWidth, newHeight;
  9431. if (width == 0 || height == 0)
  9432. {
  9433. newWidth = this->width();
  9434. newHeight = this->height();
  9435. } else
  9436. {
  9437. newWidth = width;
  9438. newHeight = height;
  9439. }
  9440. if (painter->isActive())
  9441. {
  9442. QRect oldViewport = viewport();
  9443. setViewport(QRect(0, 0, newWidth, newHeight));
  9444. painter->setMode(QCPPainter::pmNoCaching);
  9445. // warning: the following is different in toPixmap, because a solid background color is applied there via QPixmap::fill
  9446. // here, we need to do this via QPainter::fillRect.
  9447. if (mBackgroundBrush.style() != Qt::NoBrush)
  9448. painter->fillRect(mViewport, mBackgroundBrush);
  9449. draw(painter);
  9450. setViewport(oldViewport);
  9451. } else
  9452. qDebug() << Q_FUNC_INFO << "Passed painter is not active";
  9453. }
  9454. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9455. //////////////////// QCPColorGradient
  9456. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9457. /*! \class QCPColorGradient
  9458. \brief Defines a color gradient for use with e.g. \ref QCPColorMap
  9459. This class describes a color gradient which can be used to encode data with color. For example,
  9460. QCPColorMap and QCPColorScale have a \ref QCPColorMap::setGradient "setGradient" method which
  9461. takes an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color)
  9462. with a \a position from 0 to 1. In between these defined color positions, the
  9463. color will be interpolated linearly either in RGB or HSV space, see \ref setColorInterpolation.
  9464. Alternatively, load one of the preset color gradients shown in the image below, with \ref
  9465. loadPreset, or by directly specifying the preset in the constructor.
  9466. \image html QCPColorGradient.png
  9467. The fact that the \ref QCPColorGradient(GradientPreset preset) constructor allows directly
  9468. converting a \ref GradientPreset to a QCPColorGradient, you can also directly pass \ref
  9469. GradientPreset to all the \a setGradient methods, e.g.:
  9470. \code
  9471. colorMap->setGradient(QCPColorGradient::gpHot);
  9472. \endcode
  9473. The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the
  9474. color gradient shall be applied periodically (wrapping around) to data values that lie outside
  9475. the data range specified on the plottable instance can be controlled with \ref setPeriodic.
  9476. */
  9477. /*!
  9478. Constructs a new QCPColorGradient initialized with the colors and color interpolation according
  9479. to \a preset.
  9480. The color level count is initialized to 350.
  9481. */
  9482. QCPColorGradient::QCPColorGradient(GradientPreset preset) :
  9483. mLevelCount(350),
  9484. mColorInterpolation(ciRGB),
  9485. mPeriodic(false),
  9486. mColorBufferInvalidated(true)
  9487. {
  9488. mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
  9489. loadPreset(preset);
  9490. }
  9491. /* undocumented operator */
  9492. bool QCPColorGradient::operator==(const QCPColorGradient &other) const
  9493. {
  9494. return ((other.mLevelCount == this->mLevelCount) &&
  9495. (other.mColorInterpolation == this->mColorInterpolation) &&
  9496. (other.mPeriodic == this->mPeriodic) &&
  9497. (other.mColorStops == this->mColorStops));
  9498. }
  9499. /*!
  9500. Sets the number of discretization levels of the color gradient to \a n. The default is 350 which
  9501. is typically enough to create a smooth appearance.
  9502. \image html QCPColorGradient-levelcount.png
  9503. */
  9504. void QCPColorGradient::setLevelCount(int n)
  9505. {
  9506. if (n < 2)
  9507. {
  9508. qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n;
  9509. n = 2;
  9510. }
  9511. if (n != mLevelCount)
  9512. {
  9513. mLevelCount = n;
  9514. mColorBufferInvalidated = true;
  9515. }
  9516. }
  9517. /*!
  9518. Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the
  9519. colors are the values of the passed QMap \a colorStops. In between these color stops, the color
  9520. is interpolated according to \ref setColorInterpolation.
  9521. A more convenient way to create a custom gradient may be to clear all color stops with \ref
  9522. clearColorStops and then adding them one by one with \ref setColorStopAt.
  9523. \see clearColorStops
  9524. */
  9525. void QCPColorGradient::setColorStops(const QMap<double, QColor> &colorStops)
  9526. {
  9527. mColorStops = colorStops;
  9528. mColorBufferInvalidated = true;
  9529. }
  9530. /*!
  9531. Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between
  9532. these color stops, the color is interpolated according to \ref setColorInterpolation.
  9533. \see setColorStops, clearColorStops
  9534. */
  9535. void QCPColorGradient::setColorStopAt(double position, const QColor &color)
  9536. {
  9537. mColorStops.insert(position, color);
  9538. mColorBufferInvalidated = true;
  9539. }
  9540. /*!
  9541. Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be
  9542. interpolated linearly in RGB or in HSV color space.
  9543. For example, a sweep in RGB space from red to green will have a muddy brown intermediate color,
  9544. whereas in HSV space the intermediate color is yellow.
  9545. */
  9546. void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation)
  9547. {
  9548. if (interpolation != mColorInterpolation)
  9549. {
  9550. mColorInterpolation = interpolation;
  9551. mColorBufferInvalidated = true;
  9552. }
  9553. }
  9554. /*!
  9555. Sets whether data points that are outside the configured data range (e.g. \ref
  9556. QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether
  9557. they all have the same color, corresponding to the respective gradient boundary color.
  9558. \image html QCPColorGradient-periodic.png
  9559. As shown in the image above, gradients that have the same start and end color are especially
  9560. suitable for a periodic gradient mapping, since they produce smooth color transitions throughout
  9561. the color map. A preset that has this property is \ref gpHues.
  9562. In practice, using periodic color gradients makes sense when the data corresponds to a periodic
  9563. dimension, such as an angle or a phase. If this is not the case, the color encoding might become
  9564. ambiguous, because multiple different data values are shown as the same color.
  9565. */
  9566. void QCPColorGradient::setPeriodic(bool enabled)
  9567. {
  9568. mPeriodic = enabled;
  9569. }
  9570. /*!
  9571. This method is used to quickly convert a \a data array to colors. The colors will be output in
  9572. the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this
  9573. function. The data range that shall be used for mapping the data value to the gradient is passed
  9574. in \a range. \a logarithmic indicates whether the data values shall be mapped to colors
  9575. logarithmically.
  9576. if \a data actually contains 2D-data linearized via <tt>[row*columnCount + column]</tt>, you can
  9577. set \a dataIndexFactor to <tt>columnCount</tt> to convert a column instead of a row of the data
  9578. array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data
  9579. is addressed <tt>data[i*dataIndexFactor]</tt>.
  9580. */
  9581. void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
  9582. {
  9583. // If you change something here, make sure to also adapt ::color()
  9584. if (!data)
  9585. {
  9586. qDebug() << Q_FUNC_INFO << "null pointer given as data";
  9587. return;
  9588. }
  9589. if (!scanLine)
  9590. {
  9591. qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
  9592. return;
  9593. }
  9594. if (mColorBufferInvalidated)
  9595. updateColorBuffer();
  9596. if (!logarithmic)
  9597. {
  9598. const double posToIndexFactor = mLevelCount/range.size();
  9599. if (mPeriodic)
  9600. {
  9601. for (int i=0; i<n; ++i)
  9602. {
  9603. int index = (int)((data[dataIndexFactor*i]-range.lower)*posToIndexFactor) % mLevelCount;
  9604. if (index < 0)
  9605. index += mLevelCount;
  9606. scanLine[i] = mColorBuffer.at(index);
  9607. }
  9608. } else
  9609. {
  9610. for (int i=0; i<n; ++i)
  9611. {
  9612. int index = (data[dataIndexFactor*i]-range.lower)*posToIndexFactor;
  9613. if (index < 0)
  9614. index = 0;
  9615. else if (index >= mLevelCount)
  9616. index = mLevelCount-1;
  9617. scanLine[i] = mColorBuffer.at(index);
  9618. }
  9619. }
  9620. } else // logarithmic == true
  9621. {
  9622. if (mPeriodic)
  9623. {
  9624. for (int i=0; i<n; ++i)
  9625. {
  9626. int index = (int)(qLn(data[dataIndexFactor*i]/range.lower)/qLn(range.upper/range.lower)*mLevelCount) % mLevelCount;
  9627. if (index < 0)
  9628. index += mLevelCount;
  9629. scanLine[i] = mColorBuffer.at(index);
  9630. }
  9631. } else
  9632. {
  9633. for (int i=0; i<n; ++i)
  9634. {
  9635. int index = qLn(data[dataIndexFactor*i]/range.lower)/qLn(range.upper/range.lower)*mLevelCount;
  9636. if (index < 0)
  9637. index = 0;
  9638. else if (index >= mLevelCount)
  9639. index = mLevelCount-1;
  9640. scanLine[i] = mColorBuffer.at(index);
  9641. }
  9642. }
  9643. }
  9644. }
  9645. /*! \internal
  9646. This method is used to colorize a single data value given in \a position, to colors. The data
  9647. range that shall be used for mapping the data value to the gradient is passed in \a range. \a
  9648. logarithmic indicates whether the data value shall be mapped to a color logarithmically.
  9649. If an entire array of data values shall be converted, rather use \ref colorize, for better
  9650. performance.
  9651. */
  9652. QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic)
  9653. {
  9654. // If you change something here, make sure to also adapt ::colorize()
  9655. if (mColorBufferInvalidated)
  9656. updateColorBuffer();
  9657. int index = 0;
  9658. if (!logarithmic)
  9659. index = (position-range.lower)*mLevelCount/range.size();
  9660. else
  9661. index = qLn(position/range.lower)/qLn(range.upper/range.lower)*mLevelCount;
  9662. if (mPeriodic)
  9663. {
  9664. index = index % mLevelCount;
  9665. if (index < 0)
  9666. index += mLevelCount;
  9667. } else
  9668. {
  9669. if (index < 0)
  9670. index = 0;
  9671. else if (index >= mLevelCount)
  9672. index = mLevelCount-1;
  9673. }
  9674. return mColorBuffer.at(index);
  9675. }
  9676. /*!
  9677. Clears the current color stops and loads the specified \a preset. A preset consists of predefined
  9678. color stops and the corresponding color interpolation method.
  9679. The available presets are:
  9680. \image html QCPColorGradient.png
  9681. */
  9682. void QCPColorGradient::loadPreset(GradientPreset preset)
  9683. {
  9684. clearColorStops();
  9685. switch (preset)
  9686. {
  9687. case gpGrayscale:
  9688. setColorInterpolation(ciRGB);
  9689. setColorStopAt(0, Qt::black);
  9690. setColorStopAt(1, Qt::white);
  9691. break;
  9692. case gpHot:
  9693. setColorInterpolation(ciRGB);
  9694. setColorStopAt(0, QColor(50, 0, 0));
  9695. setColorStopAt(0.2, QColor(180, 10, 0));
  9696. setColorStopAt(0.4, QColor(245, 50, 0));
  9697. setColorStopAt(0.6, QColor(255, 150, 10));
  9698. setColorStopAt(0.8, QColor(255, 255, 50));
  9699. setColorStopAt(1, QColor(255, 255, 255));
  9700. break;
  9701. case gpCold:
  9702. setColorInterpolation(ciRGB);
  9703. setColorStopAt(0, QColor(0, 0, 50));
  9704. setColorStopAt(0.2, QColor(0, 10, 180));
  9705. setColorStopAt(0.4, QColor(0, 50, 245));
  9706. setColorStopAt(0.6, QColor(10, 150, 255));
  9707. setColorStopAt(0.8, QColor(50, 255, 255));
  9708. setColorStopAt(1, QColor(255, 255, 255));
  9709. break;
  9710. case gpNight:
  9711. setColorInterpolation(ciHSV);
  9712. setColorStopAt(0, QColor(10, 20, 30));
  9713. setColorStopAt(1, QColor(250, 255, 250));
  9714. break;
  9715. case gpCandy:
  9716. setColorInterpolation(ciHSV);
  9717. setColorStopAt(0, QColor(0, 0, 255));
  9718. setColorStopAt(1, QColor(255, 250, 250));
  9719. break;
  9720. case gpGeography:
  9721. setColorInterpolation(ciRGB);
  9722. setColorStopAt(0, QColor(70, 170, 210));
  9723. setColorStopAt(0.20, QColor(90, 160, 180));
  9724. setColorStopAt(0.25, QColor(45, 130, 175));
  9725. setColorStopAt(0.30, QColor(100, 140, 125));
  9726. setColorStopAt(0.5, QColor(100, 140, 100));
  9727. setColorStopAt(0.6, QColor(130, 145, 120));
  9728. setColorStopAt(0.7, QColor(140, 130, 120));
  9729. setColorStopAt(0.9, QColor(180, 190, 190));
  9730. setColorStopAt(1, QColor(210, 210, 230));
  9731. break;
  9732. case gpIon:
  9733. setColorInterpolation(ciHSV);
  9734. setColorStopAt(0, QColor(50, 10, 10));
  9735. setColorStopAt(0.45, QColor(0, 0, 255));
  9736. setColorStopAt(0.8, QColor(0, 255, 255));
  9737. setColorStopAt(1, QColor(0, 255, 0));
  9738. break;
  9739. case gpThermal:
  9740. setColorInterpolation(ciRGB);
  9741. setColorStopAt(0, QColor(0, 0, 50));
  9742. setColorStopAt(0.15, QColor(20, 0, 120));
  9743. setColorStopAt(0.33, QColor(200, 30, 140));
  9744. setColorStopAt(0.6, QColor(255, 100, 0));
  9745. setColorStopAt(0.85, QColor(255, 255, 40));
  9746. setColorStopAt(1, QColor(255, 255, 255));
  9747. break;
  9748. case gpPolar:
  9749. setColorInterpolation(ciRGB);
  9750. setColorStopAt(0, QColor(50, 255, 255));
  9751. setColorStopAt(0.18, QColor(10, 70, 255));
  9752. setColorStopAt(0.28, QColor(10, 10, 190));
  9753. setColorStopAt(0.5, QColor(0, 0, 0));
  9754. setColorStopAt(0.72, QColor(190, 10, 10));
  9755. setColorStopAt(0.82, QColor(255, 70, 10));
  9756. setColorStopAt(1, QColor(255, 255, 50));
  9757. break;
  9758. case gpSpectrum:
  9759. setColorInterpolation(ciHSV);
  9760. setColorStopAt(0, QColor(50, 0, 50));
  9761. setColorStopAt(0.15, QColor(0, 0, 255));
  9762. setColorStopAt(0.35, QColor(0, 255, 255));
  9763. setColorStopAt(0.6, QColor(255, 255, 0));
  9764. setColorStopAt(0.75, QColor(255, 30, 0));
  9765. setColorStopAt(1, QColor(50, 0, 0));
  9766. break;
  9767. case gpJet:
  9768. setColorInterpolation(ciRGB);
  9769. setColorStopAt(0, QColor(0, 0, 100));
  9770. setColorStopAt(0.15, QColor(0, 50, 255));
  9771. setColorStopAt(0.35, QColor(0, 255, 255));
  9772. setColorStopAt(0.65, QColor(255, 255, 0));
  9773. setColorStopAt(0.85, QColor(255, 30, 0));
  9774. setColorStopAt(1, QColor(100, 0, 0));
  9775. break;
  9776. case gpHues:
  9777. setColorInterpolation(ciHSV);
  9778. setColorStopAt(0, QColor(255, 0, 0));
  9779. setColorStopAt(1.0/3.0, QColor(0, 0, 255));
  9780. setColorStopAt(2.0/3.0, QColor(0, 255, 0));
  9781. setColorStopAt(1, QColor(255, 0, 0));
  9782. break;
  9783. }
  9784. }
  9785. /*!
  9786. Clears all color stops.
  9787. \see setColorStops, setColorStopAt
  9788. */
  9789. void QCPColorGradient::clearColorStops()
  9790. {
  9791. mColorStops.clear();
  9792. mColorBufferInvalidated = true;
  9793. }
  9794. /*!
  9795. Returns an inverted gradient. The inverted gradient has all properties as this \ref
  9796. QCPColorGradient, but the order of the color stops is inverted.
  9797. \see setColorStops, setColorStopAt
  9798. */
  9799. QCPColorGradient QCPColorGradient::inverted() const
  9800. {
  9801. QCPColorGradient result(*this);
  9802. result.clearColorStops();
  9803. for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
  9804. result.setColorStopAt(1.0-it.key(), it.value());
  9805. return result;
  9806. }
  9807. /*! \internal
  9808. Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly
  9809. convert positions to colors. This is where the interpolation between color stops is calculated.
  9810. */
  9811. void QCPColorGradient::updateColorBuffer()
  9812. {
  9813. if (mColorBuffer.size() != mLevelCount)
  9814. mColorBuffer.resize(mLevelCount);
  9815. if (mColorStops.size() > 1)
  9816. {
  9817. double indexToPosFactor = 1.0/(double)(mLevelCount-1);
  9818. for (int i=0; i<mLevelCount; ++i)
  9819. {
  9820. double position = i*indexToPosFactor;
  9821. QMap<double, QColor>::const_iterator it = mColorStops.lowerBound(position);
  9822. if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop
  9823. {
  9824. mColorBuffer[i] = (it-1).value().rgb();
  9825. } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop
  9826. {
  9827. mColorBuffer[i] = it.value().rgb();
  9828. } else // position is in between stops (or on an intermediate stop), interpolate color
  9829. {
  9830. QMap<double, QColor>::const_iterator high = it;
  9831. QMap<double, QColor>::const_iterator low = it-1;
  9832. double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1
  9833. switch (mColorInterpolation)
  9834. {
  9835. case ciRGB:
  9836. {
  9837. mColorBuffer[i] = qRgb((1-t)*low.value().red() + t*high.value().red(),
  9838. (1-t)*low.value().green() + t*high.value().green(),
  9839. (1-t)*low.value().blue() + t*high.value().blue());
  9840. break;
  9841. }
  9842. case ciHSV:
  9843. {
  9844. QColor lowHsv = low.value().toHsv();
  9845. QColor highHsv = high.value().toHsv();
  9846. double hue = 0;
  9847. double hueDiff = highHsv.hueF()-lowHsv.hueF();
  9848. if (hueDiff > 0.5)
  9849. hue = lowHsv.hueF() - t*(1.0-hueDiff);
  9850. else if (hueDiff < -0.5)
  9851. hue = lowHsv.hueF() + t*(1.0+hueDiff);
  9852. else
  9853. hue = lowHsv.hueF() + t*hueDiff;
  9854. if (hue < 0) hue += 1.0;
  9855. else if (hue >= 1.0) hue -= 1.0;
  9856. mColorBuffer[i] = QColor::fromHsvF(hue, (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(), (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
  9857. break;
  9858. }
  9859. }
  9860. }
  9861. }
  9862. } else if (mColorStops.size() == 1)
  9863. {
  9864. mColorBuffer.fill(mColorStops.constBegin().value().rgb());
  9865. } else // mColorStops is empty, fill color buffer with black
  9866. {
  9867. mColorBuffer.fill(qRgb(0, 0, 0));
  9868. }
  9869. mColorBufferInvalidated = false;
  9870. }
  9871. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9872. //////////////////// QCPAxisRect
  9873. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9874. /*! \class QCPAxisRect
  9875. \brief Holds multiple axes and arranges them in a rectangular shape.
  9876. This class represents an axis rect, a rectangular area that is bounded on all sides with an
  9877. arbitrary number of axes.
  9878. Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the
  9879. layout system allows to have multiple axis rects, e.g. arranged in a grid layout
  9880. (QCustomPlot::plotLayout).
  9881. By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be
  9882. accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index.
  9883. If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be
  9884. invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref
  9885. addAxes. To remove an axis, use \ref removeAxis.
  9886. The axis rect layerable itself only draws a background pixmap or color, if specified (\ref
  9887. setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an
  9888. explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be
  9889. placed on other layers, independently of the axis rect.
  9890. Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref
  9891. insetLayout and can be used to have other layout elements (or even other layouts with multiple
  9892. elements) hovering inside the axis rect.
  9893. If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The
  9894. behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel
  9895. is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable
  9896. via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are
  9897. only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref
  9898. QCP::iRangeZoom.
  9899. \image html AxisRectSpacingOverview.png
  9900. <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed
  9901. line on the far left indicates the viewport/widget border.</center>
  9902. */
  9903. /* start documentation of inline functions */
  9904. /*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const
  9905. Returns the inset layout of this axis rect. It can be used to place other layout elements (or
  9906. even layouts with multiple other elements) inside/on top of an axis rect.
  9907. \see QCPLayoutInset
  9908. */
  9909. /*! \fn int QCPAxisRect::left() const
  9910. Returns the pixel position of the left border of this axis rect. Margins are not taken into
  9911. account here, so the returned value is with respect to the inner \ref rect.
  9912. */
  9913. /*! \fn int QCPAxisRect::right() const
  9914. Returns the pixel position of the right border of this axis rect. Margins are not taken into
  9915. account here, so the returned value is with respect to the inner \ref rect.
  9916. */
  9917. /*! \fn int QCPAxisRect::top() const
  9918. Returns the pixel position of the top border of this axis rect. Margins are not taken into
  9919. account here, so the returned value is with respect to the inner \ref rect.
  9920. */
  9921. /*! \fn int QCPAxisRect::bottom() const
  9922. Returns the pixel position of the bottom border of this axis rect. Margins are not taken into
  9923. account here, so the returned value is with respect to the inner \ref rect.
  9924. */
  9925. /*! \fn int QCPAxisRect::width() const
  9926. Returns the pixel width of this axis rect. Margins are not taken into account here, so the
  9927. returned value is with respect to the inner \ref rect.
  9928. */
  9929. /*! \fn int QCPAxisRect::height() const
  9930. Returns the pixel height of this axis rect. Margins are not taken into account here, so the
  9931. returned value is with respect to the inner \ref rect.
  9932. */
  9933. /*! \fn QSize QCPAxisRect::size() const
  9934. Returns the pixel size of this axis rect. Margins are not taken into account here, so the
  9935. returned value is with respect to the inner \ref rect.
  9936. */
  9937. /*! \fn QPoint QCPAxisRect::topLeft() const
  9938. Returns the top left corner of this axis rect in pixels. Margins are not taken into account here,
  9939. so the returned value is with respect to the inner \ref rect.
  9940. */
  9941. /*! \fn QPoint QCPAxisRect::topRight() const
  9942. Returns the top right corner of this axis rect in pixels. Margins are not taken into account
  9943. here, so the returned value is with respect to the inner \ref rect.
  9944. */
  9945. /*! \fn QPoint QCPAxisRect::bottomLeft() const
  9946. Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account
  9947. here, so the returned value is with respect to the inner \ref rect.
  9948. */
  9949. /*! \fn QPoint QCPAxisRect::bottomRight() const
  9950. Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account
  9951. here, so the returned value is with respect to the inner \ref rect.
  9952. */
  9953. /*! \fn QPoint QCPAxisRect::center() const
  9954. Returns the center of this axis rect in pixels. Margins are not taken into account here, so the
  9955. returned value is with respect to the inner \ref rect.
  9956. */
  9957. /* end documentation of inline functions */
  9958. /*!
  9959. Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four
  9960. sides, the top and right axes are set invisible initially.
  9961. */
  9962. QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) :
  9963. QCPLayoutElement(parentPlot),
  9964. mBackgroundBrush(Qt::NoBrush),
  9965. mBackgroundScaled(true),
  9966. mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
  9967. mInsetLayout(new QCPLayoutInset),
  9968. mRangeDrag(Qt::Horizontal|Qt::Vertical),
  9969. mRangeZoom(Qt::Horizontal|Qt::Vertical),
  9970. mRangeZoomFactorHorz(0.85),
  9971. mRangeZoomFactorVert(0.85),
  9972. mDragging(false)
  9973. {
  9974. mInsetLayout->initializeParentPlot(mParentPlot);
  9975. mInsetLayout->setParentLayerable(this);
  9976. mInsetLayout->setParent(this);
  9977. setMinimumSize(50, 50);
  9978. setMinimumMargins(QMargins(15, 15, 15, 15));
  9979. mAxes.insert(QCPAxis::atLeft, QList<QCPAxis*>());
  9980. mAxes.insert(QCPAxis::atRight, QList<QCPAxis*>());
  9981. mAxes.insert(QCPAxis::atTop, QList<QCPAxis*>());
  9982. mAxes.insert(QCPAxis::atBottom, QList<QCPAxis*>());
  9983. if (setupDefaultAxes)
  9984. {
  9985. QCPAxis *xAxis = addAxis(QCPAxis::atBottom);
  9986. QCPAxis *yAxis = addAxis(QCPAxis::atLeft);
  9987. QCPAxis *xAxis2 = addAxis(QCPAxis::atTop);
  9988. QCPAxis *yAxis2 = addAxis(QCPAxis::atRight);
  9989. setRangeDragAxes(xAxis, yAxis);
  9990. setRangeZoomAxes(xAxis, yAxis);
  9991. xAxis2->setVisible(false);
  9992. yAxis2->setVisible(false);
  9993. xAxis->grid()->setVisible(true);
  9994. yAxis->grid()->setVisible(true);
  9995. xAxis2->grid()->setVisible(false);
  9996. yAxis2->grid()->setVisible(false);
  9997. xAxis2->grid()->setZeroLinePen(Qt::NoPen);
  9998. yAxis2->grid()->setZeroLinePen(Qt::NoPen);
  9999. xAxis2->grid()->setVisible(false);
  10000. yAxis2->grid()->setVisible(false);
  10001. }
  10002. }
  10003. QCPAxisRect::~QCPAxisRect()
  10004. {
  10005. delete mInsetLayout;
  10006. mInsetLayout = 0;
  10007. QList<QCPAxis*> axesList = axes();
  10008. for (int i=0; i<axesList.size(); ++i)
  10009. removeAxis(axesList.at(i));
  10010. }
  10011. /*!
  10012. Returns the number of axes on the axis rect side specified with \a type.
  10013. \see axis
  10014. */
  10015. int QCPAxisRect::axisCount(QCPAxis::AxisType type) const
  10016. {
  10017. return mAxes.value(type).size();
  10018. }
  10019. /*!
  10020. Returns the axis with the given \a index on the axis rect side specified with \a type.
  10021. \see axisCount, axes
  10022. */
  10023. QCPAxis *QCPAxisRect::axis(QCPAxis::AxisType type, int index) const
  10024. {
  10025. QList<QCPAxis*> ax(mAxes.value(type));
  10026. if (index >= 0 && index < ax.size())
  10027. {
  10028. return ax.at(index);
  10029. } else
  10030. {
  10031. qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index;
  10032. return 0;
  10033. }
  10034. }
  10035. /*!
  10036. Returns all axes on the axis rect sides specified with \a types.
  10037. \a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of
  10038. multiple sides.
  10039. \see axis
  10040. */
  10041. QList<QCPAxis*> QCPAxisRect::axes(QCPAxis::AxisTypes types) const
  10042. {
  10043. QList<QCPAxis*> result;
  10044. if (types.testFlag(QCPAxis::atLeft))
  10045. result << mAxes.value(QCPAxis::atLeft);
  10046. if (types.testFlag(QCPAxis::atRight))
  10047. result << mAxes.value(QCPAxis::atRight);
  10048. if (types.testFlag(QCPAxis::atTop))
  10049. result << mAxes.value(QCPAxis::atTop);
  10050. if (types.testFlag(QCPAxis::atBottom))
  10051. result << mAxes.value(QCPAxis::atBottom);
  10052. return result;
  10053. }
  10054. /*! \overload
  10055. Returns all axes of this axis rect.
  10056. */
  10057. QList<QCPAxis*> QCPAxisRect::axes() const
  10058. {
  10059. QList<QCPAxis*> result;
  10060. QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
  10061. while (it.hasNext())
  10062. {
  10063. it.next();
  10064. result << it.value();
  10065. }
  10066. return result;
  10067. }
  10068. /*!
  10069. Adds a new axis to the axis rect side specified with \a type, and returns it.
  10070. If an axis rect side already contains one or more axes, the lower and upper endings of the new
  10071. axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are initialized to \ref
  10072. QCPLineEnding::esHalfBar.
  10073. \see addAxes, setupFullAxesBox
  10074. */
  10075. QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type)
  10076. {
  10077. QCPAxis *newAxis = new QCPAxis(this, type);
  10078. if (mAxes[type].size() > 0) // multiple axes on one side, add half-bar axis ending to additional axes with offset
  10079. {
  10080. bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom);
  10081. newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert));
  10082. newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert));
  10083. }
  10084. mAxes[type].append(newAxis);
  10085. return newAxis;
  10086. }
  10087. /*!
  10088. Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an
  10089. <tt>or</tt>-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once.
  10090. Returns a list of the added axes.
  10091. \see addAxis, setupFullAxesBox
  10092. */
  10093. QList<QCPAxis*> QCPAxisRect::addAxes(QCPAxis::AxisTypes types)
  10094. {
  10095. QList<QCPAxis*> result;
  10096. if (types.testFlag(QCPAxis::atLeft))
  10097. result << addAxis(QCPAxis::atLeft);
  10098. if (types.testFlag(QCPAxis::atRight))
  10099. result << addAxis(QCPAxis::atRight);
  10100. if (types.testFlag(QCPAxis::atTop))
  10101. result << addAxis(QCPAxis::atTop);
  10102. if (types.testFlag(QCPAxis::atBottom))
  10103. result << addAxis(QCPAxis::atBottom);
  10104. return result;
  10105. }
  10106. /*!
  10107. Removes the specified \a axis from the axis rect and deletes it.
  10108. Returns true on success, i.e. if \a axis was a valid axis in this axis rect.
  10109. \see addAxis
  10110. */
  10111. bool QCPAxisRect::removeAxis(QCPAxis *axis)
  10112. {
  10113. // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers:
  10114. QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
  10115. while (it.hasNext())
  10116. {
  10117. it.next();
  10118. if (it.value().contains(axis))
  10119. {
  10120. mAxes[it.key()].removeOne(axis);
  10121. 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)
  10122. parentPlot()->axisRemoved(axis);
  10123. delete axis;
  10124. return true;
  10125. }
  10126. }
  10127. qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast<quintptr>(axis);
  10128. return false;
  10129. }
  10130. /*!
  10131. Convenience function to create an axis on each side that doesn't have any axes yet and set their
  10132. visibility to true. Further, the top/right axes are assigned the following properties of the
  10133. bottom/left axes:
  10134. \li range (\ref QCPAxis::setRange)
  10135. \li range reversed (\ref QCPAxis::setRangeReversed)
  10136. \li scale type (\ref QCPAxis::setScaleType)
  10137. \li scale log base (\ref QCPAxis::setScaleLogBase)
  10138. \li ticks (\ref QCPAxis::setTicks)
  10139. \li auto (major) tick count (\ref QCPAxis::setAutoTickCount)
  10140. \li sub tick count (\ref QCPAxis::setSubTickCount)
  10141. \li auto sub ticks (\ref QCPAxis::setAutoSubTicks)
  10142. \li tick step (\ref QCPAxis::setTickStep)
  10143. \li auto tick step (\ref QCPAxis::setAutoTickStep)
  10144. \li number format (\ref QCPAxis::setNumberFormat)
  10145. \li number precision (\ref QCPAxis::setNumberPrecision)
  10146. \li tick label type (\ref QCPAxis::setTickLabelType)
  10147. \li date time format (\ref QCPAxis::setDateTimeFormat)
  10148. \li date time spec (\ref QCPAxis::setDateTimeSpec)
  10149. Tick labels (\ref QCPAxis::setTickLabels) of the right and top axes are set to false.
  10150. If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom
  10151. and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes.
  10152. */
  10153. void QCPAxisRect::setupFullAxesBox(bool connectRanges)
  10154. {
  10155. QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2;
  10156. if (axisCount(QCPAxis::atBottom) == 0)
  10157. xAxis = addAxis(QCPAxis::atBottom);
  10158. else
  10159. xAxis = axis(QCPAxis::atBottom);
  10160. if (axisCount(QCPAxis::atLeft) == 0)
  10161. yAxis = addAxis(QCPAxis::atLeft);
  10162. else
  10163. yAxis = axis(QCPAxis::atLeft);
  10164. if (axisCount(QCPAxis::atTop) == 0)
  10165. xAxis2 = addAxis(QCPAxis::atTop);
  10166. else
  10167. xAxis2 = axis(QCPAxis::atTop);
  10168. if (axisCount(QCPAxis::atRight) == 0)
  10169. yAxis2 = addAxis(QCPAxis::atRight);
  10170. else
  10171. yAxis2 = axis(QCPAxis::atRight);
  10172. xAxis->setVisible(true);
  10173. yAxis->setVisible(true);
  10174. xAxis2->setVisible(true);
  10175. yAxis2->setVisible(true);
  10176. xAxis2->setTickLabels(false);
  10177. yAxis2->setTickLabels(false);
  10178. xAxis2->setRange(xAxis->range());
  10179. xAxis2->setRangeReversed(xAxis->rangeReversed());
  10180. xAxis2->setScaleType(xAxis->scaleType());
  10181. xAxis2->setScaleLogBase(xAxis->scaleLogBase());
  10182. xAxis2->setTicks(xAxis->ticks());
  10183. xAxis2->setAutoTickCount(xAxis->autoTickCount());
  10184. xAxis2->setSubTickCount(xAxis->subTickCount());
  10185. xAxis2->setAutoSubTicks(xAxis->autoSubTicks());
  10186. xAxis2->setTickStep(xAxis->tickStep());
  10187. xAxis2->setAutoTickStep(xAxis->autoTickStep());
  10188. xAxis2->setNumberFormat(xAxis->numberFormat());
  10189. xAxis2->setNumberPrecision(xAxis->numberPrecision());
  10190. xAxis2->setTickLabelType(xAxis->tickLabelType());
  10191. xAxis2->setDateTimeFormat(xAxis->dateTimeFormat());
  10192. xAxis2->setDateTimeSpec(xAxis->dateTimeSpec());
  10193. yAxis2->setRange(yAxis->range());
  10194. yAxis2->setRangeReversed(yAxis->rangeReversed());
  10195. yAxis2->setScaleType(yAxis->scaleType());
  10196. yAxis2->setScaleLogBase(yAxis->scaleLogBase());
  10197. yAxis2->setTicks(yAxis->ticks());
  10198. yAxis2->setAutoTickCount(yAxis->autoTickCount());
  10199. yAxis2->setSubTickCount(yAxis->subTickCount());
  10200. yAxis2->setAutoSubTicks(yAxis->autoSubTicks());
  10201. yAxis2->setTickStep(yAxis->tickStep());
  10202. yAxis2->setAutoTickStep(yAxis->autoTickStep());
  10203. yAxis2->setNumberFormat(yAxis->numberFormat());
  10204. yAxis2->setNumberPrecision(yAxis->numberPrecision());
  10205. yAxis2->setTickLabelType(yAxis->tickLabelType());
  10206. yAxis2->setDateTimeFormat(yAxis->dateTimeFormat());
  10207. yAxis2->setDateTimeSpec(yAxis->dateTimeSpec());
  10208. if (connectRanges)
  10209. {
  10210. connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange)));
  10211. connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange)));
  10212. }
  10213. }
  10214. /*!
  10215. Returns a list of all the plottables that are associated with this axis rect.
  10216. A plottable is considered associated with an axis rect if its key or value axis (or both) is in
  10217. this axis rect.
  10218. \see graphs, items
  10219. */
  10220. QList<QCPAbstractPlottable*> QCPAxisRect::plottables() const
  10221. {
  10222. // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries
  10223. QList<QCPAbstractPlottable*> result;
  10224. for (int i=0; i<mParentPlot->mPlottables.size(); ++i)
  10225. {
  10226. if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this ||mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this)
  10227. result.append(mParentPlot->mPlottables.at(i));
  10228. }
  10229. return result;
  10230. }
  10231. /*!
  10232. Returns a list of all the graphs that are associated with this axis rect.
  10233. A graph is considered associated with an axis rect if its key or value axis (or both) is in
  10234. this axis rect.
  10235. \see plottables, items
  10236. */
  10237. QList<QCPGraph*> QCPAxisRect::graphs() const
  10238. {
  10239. // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries
  10240. QList<QCPGraph*> result;
  10241. for (int i=0; i<mParentPlot->mGraphs.size(); ++i)
  10242. {
  10243. if (mParentPlot->mGraphs.at(i)->keyAxis()->axisRect() == this || mParentPlot->mGraphs.at(i)->valueAxis()->axisRect() == this)
  10244. result.append(mParentPlot->mGraphs.at(i));
  10245. }
  10246. return result;
  10247. }
  10248. /*!
  10249. Returns a list of all the items that are associated with this axis rect.
  10250. An item is considered associated with an axis rect if any of its positions has key or value axis
  10251. set to an axis that is in this axis rect, or if any of its positions has \ref
  10252. QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref
  10253. QCPAbstractItem::setClipAxisRect) is set to this axis rect.
  10254. \see plottables, graphs
  10255. */
  10256. QList<QCPAbstractItem *> QCPAxisRect::items() const
  10257. {
  10258. // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries
  10259. // and miss those items that have this axis rect as clipAxisRect.
  10260. QList<QCPAbstractItem*> result;
  10261. for (int itemId=0; itemId<mParentPlot->mItems.size(); ++itemId)
  10262. {
  10263. if (mParentPlot->mItems.at(itemId)->clipAxisRect() == this)
  10264. {
  10265. result.append(mParentPlot->mItems.at(itemId));
  10266. continue;
  10267. }
  10268. QList<QCPItemPosition*> positions = mParentPlot->mItems.at(itemId)->positions();
  10269. for (int posId=0; posId<positions.size(); ++posId)
  10270. {
  10271. if (positions.at(posId)->axisRect() == this ||
  10272. positions.at(posId)->keyAxis()->axisRect() == this ||
  10273. positions.at(posId)->valueAxis()->axisRect() == this)
  10274. {
  10275. result.append(mParentPlot->mItems.at(itemId));
  10276. break;
  10277. }
  10278. }
  10279. }
  10280. return result;
  10281. }
  10282. /*!
  10283. This method is called automatically upon replot and doesn't need to be called by users of
  10284. QCPAxisRect.
  10285. Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
  10286. and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
  10287. QCPInsetLayout::update function.
  10288. */
  10289. void QCPAxisRect::update(UpdatePhase phase)
  10290. {
  10291. QCPLayoutElement::update(phase);
  10292. switch (phase)
  10293. {
  10294. case upPreparation:
  10295. {
  10296. QList<QCPAxis*> allAxes = axes();
  10297. for (int i=0; i<allAxes.size(); ++i)
  10298. allAxes.at(i)->setupTickVectors();
  10299. break;
  10300. }
  10301. case upLayout:
  10302. {
  10303. mInsetLayout->setOuterRect(rect());
  10304. break;
  10305. }
  10306. default: break;
  10307. }
  10308. // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout):
  10309. mInsetLayout->update(phase);
  10310. }
  10311. /* inherits documentation from base class */
  10312. QList<QCPLayoutElement*> QCPAxisRect::elements(bool recursive) const
  10313. {
  10314. QList<QCPLayoutElement*> result;
  10315. if (mInsetLayout)
  10316. {
  10317. result << mInsetLayout;
  10318. if (recursive)
  10319. result << mInsetLayout->elements(recursive);
  10320. }
  10321. return result;
  10322. }
  10323. /* inherits documentation from base class */
  10324. void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const
  10325. {
  10326. painter->setAntialiasing(false);
  10327. }
  10328. /* inherits documentation from base class */
  10329. void QCPAxisRect::draw(QCPPainter *painter)
  10330. {
  10331. drawBackground(painter);
  10332. }
  10333. /*!
  10334. Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the
  10335. axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect
  10336. backgrounds are usually drawn below everything else.
  10337. For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be
  10338. enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio
  10339. is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  10340. consider using the overloaded version of this function.
  10341. Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref
  10342. setBackground(const QBrush &brush).
  10343. \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush)
  10344. */
  10345. void QCPAxisRect::setBackground(const QPixmap &pm)
  10346. {
  10347. mBackgroundPixmap = pm;
  10348. mScaledBackgroundPixmap = QPixmap();
  10349. }
  10350. /*! \overload
  10351. Sets \a brush as the background brush. The axis rect background will be filled with this brush.
  10352. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds
  10353. are usually drawn below everything else.
  10354. The brush will be drawn before (under) any background pixmap, which may be specified with \ref
  10355. setBackground(const QPixmap &pm).
  10356. To disable drawing of a background brush, set \a brush to Qt::NoBrush.
  10357. \see setBackground(const QPixmap &pm)
  10358. */
  10359. void QCPAxisRect::setBackground(const QBrush &brush)
  10360. {
  10361. mBackgroundBrush = brush;
  10362. }
  10363. /*! \overload
  10364. Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it
  10365. shall be scaled in one call.
  10366. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  10367. */
  10368. void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
  10369. {
  10370. mBackgroundPixmap = pm;
  10371. mScaledBackgroundPixmap = QPixmap();
  10372. mBackgroundScaled = scaled;
  10373. mBackgroundScaledMode = mode;
  10374. }
  10375. /*!
  10376. Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled
  10377. is set to true, you may control whether and how the aspect ratio of the original pixmap is
  10378. preserved with \ref setBackgroundScaledMode.
  10379. Note that the scaled version of the original pixmap is buffered, so there is no performance
  10380. penalty on replots. (Except when the axis rect dimensions are changed continuously.)
  10381. \see setBackground, setBackgroundScaledMode
  10382. */
  10383. void QCPAxisRect::setBackgroundScaled(bool scaled)
  10384. {
  10385. mBackgroundScaled = scaled;
  10386. }
  10387. /*!
  10388. If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to
  10389. define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved.
  10390. \see setBackground, setBackgroundScaled
  10391. */
  10392. void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  10393. {
  10394. mBackgroundScaledMode = mode;
  10395. }
  10396. /*!
  10397. Returns the range drag axis of the \a orientation provided.
  10398. \see setRangeDragAxes
  10399. */
  10400. QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation)
  10401. {
  10402. return (orientation == Qt::Horizontal ? mRangeDragHorzAxis.data() : mRangeDragVertAxis.data());
  10403. }
  10404. /*!
  10405. Returns the range zoom axis of the \a orientation provided.
  10406. \see setRangeZoomAxes
  10407. */
  10408. QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation)
  10409. {
  10410. return (orientation == Qt::Horizontal ? mRangeZoomHorzAxis.data() : mRangeZoomVertAxis.data());
  10411. }
  10412. /*!
  10413. Returns the range zoom factor of the \a orientation provided.
  10414. \see setRangeZoomFactor
  10415. */
  10416. double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation)
  10417. {
  10418. return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert);
  10419. }
  10420. /*!
  10421. Sets which axis orientation may be range dragged by the user with mouse interaction.
  10422. What orientation corresponds to which specific axis can be set with
  10423. \ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By
  10424. default, the horizontal axis is the bottom axis (xAxis) and the vertical axis
  10425. is the left axis (yAxis).
  10426. To disable range dragging entirely, pass 0 as \a orientations or remove \ref QCP::iRangeDrag from \ref
  10427. QCustomPlot::setInteractions. To enable range dragging for both directions, pass <tt>Qt::Horizontal |
  10428. Qt::Vertical</tt> as \a orientations.
  10429. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
  10430. contains \ref QCP::iRangeDrag to enable the range dragging interaction.
  10431. \see setRangeZoom, setRangeDragAxes, setNoAntialiasingOnDrag
  10432. */
  10433. void QCPAxisRect::setRangeDrag(Qt::Orientations orientations)
  10434. {
  10435. mRangeDrag = orientations;
  10436. }
  10437. /*!
  10438. Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation
  10439. corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal,
  10440. QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical
  10441. axis is the left axis (yAxis).
  10442. To disable range zooming entirely, pass 0 as \a orientations or remove \ref QCP::iRangeZoom from \ref
  10443. QCustomPlot::setInteractions. To enable range zooming for both directions, pass <tt>Qt::Horizontal |
  10444. Qt::Vertical</tt> as \a orientations.
  10445. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
  10446. contains \ref QCP::iRangeZoom to enable the range zooming interaction.
  10447. \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag
  10448. */
  10449. void QCPAxisRect::setRangeZoom(Qt::Orientations orientations)
  10450. {
  10451. mRangeZoom = orientations;
  10452. }
  10453. /*!
  10454. Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging
  10455. on the QCustomPlot widget.
  10456. \see setRangeZoomAxes
  10457. */
  10458. void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical)
  10459. {
  10460. mRangeDragHorzAxis = horizontal;
  10461. mRangeDragVertAxis = vertical;
  10462. }
  10463. /*!
  10464. Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on the
  10465. QCustomPlot widget. The two axes can be zoomed with different strengths, when different factors
  10466. are passed to \ref setRangeZoomFactor(double horizontalFactor, double verticalFactor).
  10467. \see setRangeDragAxes
  10468. */
  10469. void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical)
  10470. {
  10471. mRangeZoomHorzAxis = horizontal;
  10472. mRangeZoomVertAxis = vertical;
  10473. }
  10474. /*!
  10475. Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with
  10476. \ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to
  10477. let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal
  10478. and which is vertical, can be set with \ref setRangeZoomAxes.
  10479. When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user)
  10480. will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the
  10481. same scrolling direction will zoom out.
  10482. */
  10483. void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor)
  10484. {
  10485. mRangeZoomFactorHorz = horizontalFactor;
  10486. mRangeZoomFactorVert = verticalFactor;
  10487. }
  10488. /*! \overload
  10489. Sets both the horizontal and vertical zoom \a factor.
  10490. */
  10491. void QCPAxisRect::setRangeZoomFactor(double factor)
  10492. {
  10493. mRangeZoomFactorHorz = factor;
  10494. mRangeZoomFactorVert = factor;
  10495. }
  10496. /*! \internal
  10497. Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a
  10498. pixmap.
  10499. If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an
  10500. according filling inside the axis rect with the provided \a painter.
  10501. Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version
  10502. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  10503. the axis rect with the provided \a painter. The scaled version is buffered in
  10504. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  10505. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  10506. dependant on the \ref setBackgroundScaledMode), or when a differend axis backgroud pixmap was
  10507. set.
  10508. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  10509. */
  10510. void QCPAxisRect::drawBackground(QCPPainter *painter)
  10511. {
  10512. // draw background fill:
  10513. if (mBackgroundBrush != Qt::NoBrush)
  10514. painter->fillRect(mRect, mBackgroundBrush);
  10515. // draw background pixmap (on top of fill, if brush specified):
  10516. if (!mBackgroundPixmap.isNull())
  10517. {
  10518. if (mBackgroundScaled)
  10519. {
  10520. // check whether mScaledBackground needs to be updated:
  10521. QSize scaledSize(mBackgroundPixmap.size());
  10522. scaledSize.scale(mRect.size(), mBackgroundScaledMode);
  10523. if (mScaledBackgroundPixmap.size() != scaledSize)
  10524. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
  10525. painter->drawPixmap(mRect.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect());
  10526. } else
  10527. {
  10528. painter->drawPixmap(mRect.topLeft(), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()));
  10529. }
  10530. }
  10531. }
  10532. /*! \internal
  10533. This function makes sure multiple axes on the side specified with \a type don't collide, but are
  10534. distributed according to their respective space requirement (QCPAxis::calculateMargin).
  10535. It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the
  10536. one with index zero.
  10537. This function is called by \ref calculateAutoMargin.
  10538. */
  10539. void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type)
  10540. {
  10541. const QList<QCPAxis*> axesList = mAxes.value(type);
  10542. if (axesList.isEmpty())
  10543. return;
  10544. 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
  10545. for (int i=1; i<axesList.size(); ++i)
  10546. {
  10547. int offset = axesList.at(i-1)->offset() + axesList.at(i-1)->calculateMargin();
  10548. 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)
  10549. {
  10550. if (!isFirstVisible)
  10551. offset += axesList.at(i)->tickLengthIn();
  10552. isFirstVisible = false;
  10553. }
  10554. axesList.at(i)->setOffset(offset);
  10555. }
  10556. }
  10557. /* inherits documentation from base class */
  10558. int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side)
  10559. {
  10560. if (!mAutoMargins.testFlag(side))
  10561. qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin";
  10562. updateAxesOffset(QCPAxis::marginSideToAxisType(side));
  10563. // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call
  10564. const QList<QCPAxis*> axesList = mAxes.value(QCPAxis::marginSideToAxisType(side));
  10565. if (axesList.size() > 0)
  10566. return axesList.last()->offset() + axesList.last()->calculateMargin();
  10567. else
  10568. return 0;
  10569. }
  10570. /*! \internal
  10571. Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
  10572. pressed, the range dragging interaction is initialized (the actual range manipulation happens in
  10573. the \ref mouseMoveEvent).
  10574. The mDragging flag is set to true and some anchor points are set that are needed to determine the
  10575. distance the mouse was dragged in the mouse move/release events later.
  10576. \see mouseMoveEvent, mouseReleaseEvent
  10577. */
  10578. void QCPAxisRect::mousePressEvent(QMouseEvent *event)
  10579. {
  10580. mDragStart = event->pos(); // need this even when not LeftButton is pressed, to determine in releaseEvent whether it was a full click (no position change between press and release)
  10581. if (event->buttons() & Qt::LeftButton)
  10582. {
  10583. mDragging = true;
  10584. // initialize antialiasing backup in case we start dragging:
  10585. if (mParentPlot->noAntialiasingOnDrag())
  10586. {
  10587. mAADragBackup = mParentPlot->antialiasedElements();
  10588. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  10589. }
  10590. // Mouse range dragging interaction:
  10591. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  10592. {
  10593. if (mRangeDragHorzAxis)
  10594. mDragStartHorzRange = mRangeDragHorzAxis.data()->range();
  10595. if (mRangeDragVertAxis)
  10596. mDragStartVertRange = mRangeDragVertAxis.data()->range();
  10597. }
  10598. }
  10599. }
  10600. /*! \internal
  10601. Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a
  10602. preceding \ref mousePressEvent, the range is moved accordingly.
  10603. \see mousePressEvent, mouseReleaseEvent
  10604. */
  10605. void QCPAxisRect::mouseMoveEvent(QMouseEvent *event)
  10606. {
  10607. // Mouse range dragging interaction:
  10608. if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  10609. {
  10610. if (mRangeDrag.testFlag(Qt::Horizontal))
  10611. {
  10612. if (QCPAxis *rangeDragHorzAxis = mRangeDragHorzAxis.data())
  10613. {
  10614. if (rangeDragHorzAxis->mScaleType == QCPAxis::stLinear)
  10615. {
  10616. double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) - rangeDragHorzAxis->pixelToCoord(event->pos().x());
  10617. rangeDragHorzAxis->setRange(mDragStartHorzRange.lower+diff, mDragStartHorzRange.upper+diff);
  10618. } else if (rangeDragHorzAxis->mScaleType == QCPAxis::stLogarithmic)
  10619. {
  10620. double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) / rangeDragHorzAxis->pixelToCoord(event->pos().x());
  10621. rangeDragHorzAxis->setRange(mDragStartHorzRange.lower*diff, mDragStartHorzRange.upper*diff);
  10622. }
  10623. }
  10624. }
  10625. if (mRangeDrag.testFlag(Qt::Vertical))
  10626. {
  10627. if (QCPAxis *rangeDragVertAxis = mRangeDragVertAxis.data())
  10628. {
  10629. if (rangeDragVertAxis->mScaleType == QCPAxis::stLinear)
  10630. {
  10631. double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) - rangeDragVertAxis->pixelToCoord(event->pos().y());
  10632. rangeDragVertAxis->setRange(mDragStartVertRange.lower+diff, mDragStartVertRange.upper+diff);
  10633. } else if (rangeDragVertAxis->mScaleType == QCPAxis::stLogarithmic)
  10634. {
  10635. double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) / rangeDragVertAxis->pixelToCoord(event->pos().y());
  10636. rangeDragVertAxis->setRange(mDragStartVertRange.lower*diff, mDragStartVertRange.upper*diff);
  10637. }
  10638. }
  10639. }
  10640. if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot
  10641. {
  10642. if (mParentPlot->noAntialiasingOnDrag())
  10643. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  10644. mParentPlot->replot();
  10645. }
  10646. }
  10647. }
  10648. /* inherits documentation from base class */
  10649. void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event)
  10650. {
  10651. Q_UNUSED(event)
  10652. mDragging = false;
  10653. if (mParentPlot->noAntialiasingOnDrag())
  10654. {
  10655. mParentPlot->setAntialiasedElements(mAADragBackup);
  10656. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  10657. }
  10658. }
  10659. /*! \internal
  10660. Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
  10661. ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
  10662. the scaling operation is the current cursor position inside the axis rect. The scaling factor is
  10663. dependant on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
  10664. zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
  10665. Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse
  10666. wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be
  10667. multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as
  10668. exponent of the range zoom factor. This takes care of the wheel direction automatically, by
  10669. inverting the factor, when the wheel step is negative (f^-1 = 1/f).
  10670. */
  10671. void QCPAxisRect::wheelEvent(QWheelEvent *event)
  10672. {
  10673. // Mouse range zooming interaction:
  10674. if (mParentPlot->interactions().testFlag(QCP::iRangeZoom))
  10675. {
  10676. if (mRangeZoom != 0)
  10677. {
  10678. double factor;
  10679. double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually
  10680. if (mRangeZoom.testFlag(Qt::Horizontal))
  10681. {
  10682. factor = pow(mRangeZoomFactorHorz, wheelSteps);
  10683. if (mRangeZoomHorzAxis.data())
  10684. mRangeZoomHorzAxis.data()->scaleRange(factor, mRangeZoomHorzAxis.data()->pixelToCoord(event->pos().x()));
  10685. }
  10686. if (mRangeZoom.testFlag(Qt::Vertical))
  10687. {
  10688. factor = pow(mRangeZoomFactorVert, wheelSteps);
  10689. if (mRangeZoomVertAxis.data())
  10690. mRangeZoomVertAxis.data()->scaleRange(factor, mRangeZoomVertAxis.data()->pixelToCoord(event->pos().y()));
  10691. }
  10692. mParentPlot->replot();
  10693. }
  10694. }
  10695. }
  10696. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10697. //////////////////// QCPAbstractLegendItem
  10698. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10699. /*! \class QCPAbstractLegendItem
  10700. \brief The abstract base class for all entries in a QCPLegend.
  10701. It defines a very basic interface for entries in a QCPLegend. For representing plottables in the
  10702. legend, the subclass \ref QCPPlottableLegendItem is more suitable.
  10703. Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry
  10704. that's not even associated with a plottable).
  10705. You must implement the following pure virtual functions:
  10706. \li \ref draw (from QCPLayerable)
  10707. You inherit the following members you may use:
  10708. <table>
  10709. <tr>
  10710. <td>QCPLegend *\b mParentLegend</td>
  10711. <td>A pointer to the parent QCPLegend.</td>
  10712. </tr><tr>
  10713. <td>QFont \b mFont</td>
  10714. <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>
  10715. </tr>
  10716. </table>
  10717. */
  10718. /* start of documentation of signals */
  10719. /*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected)
  10720. This signal is emitted when the selection state of this legend item has changed, either by user
  10721. interaction or by a direct call to \ref setSelected.
  10722. */
  10723. /* end of documentation of signals */
  10724. /*!
  10725. Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not
  10726. cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately.
  10727. */
  10728. QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) :
  10729. QCPLayoutElement(parent->parentPlot()),
  10730. mParentLegend(parent),
  10731. mFont(parent->font()),
  10732. mTextColor(parent->textColor()),
  10733. mSelectedFont(parent->selectedFont()),
  10734. mSelectedTextColor(parent->selectedTextColor()),
  10735. mSelectable(true),
  10736. mSelected(false)
  10737. {
  10738. setLayer("legend");
  10739. setMargins(QMargins(8, 2, 8, 2));
  10740. }
  10741. /*!
  10742. Sets the default font of this specific legend item to \a font.
  10743. \see setTextColor, QCPLegend::setFont
  10744. */
  10745. void QCPAbstractLegendItem::setFont(const QFont &font)
  10746. {
  10747. mFont = font;
  10748. }
  10749. /*!
  10750. Sets the default text color of this specific legend item to \a color.
  10751. \see setFont, QCPLegend::setTextColor
  10752. */
  10753. void QCPAbstractLegendItem::setTextColor(const QColor &color)
  10754. {
  10755. mTextColor = color;
  10756. }
  10757. /*!
  10758. When this legend item is selected, \a font is used to draw generic text, instead of the normal
  10759. font set with \ref setFont.
  10760. \see setFont, QCPLegend::setSelectedFont
  10761. */
  10762. void QCPAbstractLegendItem::setSelectedFont(const QFont &font)
  10763. {
  10764. mSelectedFont = font;
  10765. }
  10766. /*!
  10767. When this legend item is selected, \a color is used to draw generic text, instead of the normal
  10768. color set with \ref setTextColor.
  10769. \see setTextColor, QCPLegend::setSelectedTextColor
  10770. */
  10771. void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color)
  10772. {
  10773. mSelectedTextColor = color;
  10774. }
  10775. /*!
  10776. Sets whether this specific legend item is selectable.
  10777. \see setSelectedParts, QCustomPlot::setInteractions
  10778. */
  10779. void QCPAbstractLegendItem::setSelectable(bool selectable)
  10780. {
  10781. if (mSelectable != selectable)
  10782. {
  10783. mSelectable = selectable;
  10784. emit selectableChanged(mSelectable);
  10785. }
  10786. }
  10787. /*!
  10788. Sets whether this specific legend item is selected.
  10789. It is possible to set the selection state of this item by calling this function directly, even if
  10790. setSelectable is set to false.
  10791. \see setSelectableParts, QCustomPlot::setInteractions
  10792. */
  10793. void QCPAbstractLegendItem::setSelected(bool selected)
  10794. {
  10795. if (mSelected != selected)
  10796. {
  10797. mSelected = selected;
  10798. emit selectionChanged(mSelected);
  10799. }
  10800. }
  10801. /* inherits documentation from base class */
  10802. double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  10803. {
  10804. Q_UNUSED(details)
  10805. if (!mParentPlot) return -1;
  10806. if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems)))
  10807. return -1;
  10808. if (mRect.contains(pos.toPoint()))
  10809. return mParentPlot->selectionTolerance()*0.99;
  10810. else
  10811. return -1;
  10812. }
  10813. /* inherits documentation from base class */
  10814. void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
  10815. {
  10816. applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems);
  10817. }
  10818. /* inherits documentation from base class */
  10819. QRect QCPAbstractLegendItem::clipRect() const
  10820. {
  10821. return mOuterRect;
  10822. }
  10823. /* inherits documentation from base class */
  10824. void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  10825. {
  10826. Q_UNUSED(event)
  10827. Q_UNUSED(details)
  10828. if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
  10829. {
  10830. bool selBefore = mSelected;
  10831. setSelected(additive ? !mSelected : true);
  10832. if (selectionStateChanged)
  10833. *selectionStateChanged = mSelected != selBefore;
  10834. }
  10835. }
  10836. /* inherits documentation from base class */
  10837. void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged)
  10838. {
  10839. if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
  10840. {
  10841. bool selBefore = mSelected;
  10842. setSelected(false);
  10843. if (selectionStateChanged)
  10844. *selectionStateChanged = mSelected != selBefore;
  10845. }
  10846. }
  10847. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10848. //////////////////// QCPPlottableLegendItem
  10849. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10850. /*! \class QCPPlottableLegendItem
  10851. \brief A legend item representing a plottable with an icon and the plottable name.
  10852. This is the standard legend item for plottables. It displays an icon of the plottable next to the
  10853. plottable name. The icon is drawn by the respective plottable itself (\ref
  10854. QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable.
  10855. For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the
  10856. middle.
  10857. Legend items of this type are always associated with one plottable (retrievable via the
  10858. plottable() function and settable with the constructor). You may change the font of the plottable
  10859. name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref
  10860. QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding.
  10861. The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend
  10862. creates/removes legend items of this type in the default implementation. However, these functions
  10863. may be reimplemented such that a different kind of legend item (e.g a direct subclass of
  10864. QCPAbstractLegendItem) is used for that plottable.
  10865. Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of
  10866. QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout
  10867. interface, QCPLegend has specialized functions for handling legend items conveniently, see the
  10868. documentation of \ref QCPLegend.
  10869. */
  10870. /*!
  10871. Creates a new legend item associated with \a plottable.
  10872. Once it's created, it can be added to the legend via \ref QCPLegend::addItem.
  10873. A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref
  10874. QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend.
  10875. */
  10876. QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) :
  10877. QCPAbstractLegendItem(parent),
  10878. mPlottable(plottable)
  10879. {
  10880. }
  10881. /*! \internal
  10882. Returns the pen that shall be used to draw the icon border, taking into account the selection
  10883. state of this item.
  10884. */
  10885. QPen QCPPlottableLegendItem::getIconBorderPen() const
  10886. {
  10887. return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen();
  10888. }
  10889. /*! \internal
  10890. Returns the text color that shall be used to draw text, taking into account the selection state
  10891. of this item.
  10892. */
  10893. QColor QCPPlottableLegendItem::getTextColor() const
  10894. {
  10895. return mSelected ? mSelectedTextColor : mTextColor;
  10896. }
  10897. /*! \internal
  10898. Returns the font that shall be used to draw text, taking into account the selection state of this
  10899. item.
  10900. */
  10901. QFont QCPPlottableLegendItem::getFont() const
  10902. {
  10903. return mSelected ? mSelectedFont : mFont;
  10904. }
  10905. /*! \internal
  10906. Draws the item with \a painter. The size and position of the drawn legend item is defined by the
  10907. parent layout (typically a \ref QCPLegend) and the \ref minimumSizeHint and \ref maximumSizeHint
  10908. of this legend item.
  10909. */
  10910. void QCPPlottableLegendItem::draw(QCPPainter *painter)
  10911. {
  10912. if (!mPlottable) return;
  10913. painter->setFont(getFont());
  10914. painter->setPen(QPen(getTextColor()));
  10915. QSizeF iconSize = mParentLegend->iconSize();
  10916. QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
  10917. QRectF iconRect(mRect.topLeft(), iconSize);
  10918. int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops
  10919. painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name());
  10920. // draw icon:
  10921. painter->save();
  10922. painter->setClipRect(iconRect, Qt::IntersectClip);
  10923. mPlottable->drawLegendIcon(painter, iconRect);
  10924. painter->restore();
  10925. // draw icon border:
  10926. if (getIconBorderPen().style() != Qt::NoPen)
  10927. {
  10928. painter->setPen(getIconBorderPen());
  10929. painter->setBrush(Qt::NoBrush);
  10930. painter->drawRect(iconRect);
  10931. }
  10932. }
  10933. /*! \internal
  10934. Calculates and returns the size of this item. This includes the icon, the text and the padding in
  10935. between.
  10936. */
  10937. QSize QCPPlottableLegendItem::minimumSizeHint() const
  10938. {
  10939. if (!mPlottable) return QSize();
  10940. QSize result(0, 0);
  10941. QRect textRect;
  10942. QFontMetrics fontMetrics(getFont());
  10943. QSize iconSize = mParentLegend->iconSize();
  10944. textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
  10945. result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width() + mMargins.left() + mMargins.right());
  10946. result.setHeight(qMax(textRect.height(), iconSize.height()) + mMargins.top() + mMargins.bottom());
  10947. return result;
  10948. }
  10949. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10950. //////////////////// QCPLegend
  10951. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10952. /*! \class QCPLegend
  10953. \brief Manages a legend inside a QCustomPlot.
  10954. A legend is a small box somewhere in the plot which lists plottables with their name and icon.
  10955. Normally, the legend is populated by calling \ref QCPAbstractPlottable::addToLegend. The
  10956. respective legend item can be removed with \ref QCPAbstractPlottable::removeFromLegend. However,
  10957. QCPLegend also offers an interface to add and manipulate legend items directly: \ref item, \ref
  10958. itemWithPlottable, \ref itemCount, \ref addItem, \ref removeItem, etc.
  10959. The QCPLegend derives from QCPLayoutGrid and as such can be placed in any position a
  10960. QCPLayoutElement may be positioned. The legend items are themselves QCPLayoutElements which are
  10961. placed in the grid layout of the legend. QCPLegend only adds an interface specialized for
  10962. handling child elements of type QCPAbstractLegendItem, as mentioned above. In principle, any
  10963. other layout elements may also be added to a legend via the normal \ref QCPLayoutGrid interface.
  10964. However, the QCPAbstractLegendItem-Interface will ignore those elements (e.g. \ref itemCount will
  10965. only return the number of items with QCPAbstractLegendItems type).
  10966. By default, every QCustomPlot has one legend (QCustomPlot::legend) which is placed in the inset
  10967. layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another
  10968. position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend
  10969. outside of the axis rect, place it anywhere else with the QCPLayout/QCPLayoutElement interface.
  10970. */
  10971. /* start of documentation of signals */
  10972. /*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection);
  10973. This signal is emitted when the selection state of this legend has changed.
  10974. \see setSelectedParts, setSelectableParts
  10975. */
  10976. /* end of documentation of signals */
  10977. /*!
  10978. Constructs a new QCPLegend instance with \a parentPlot as the containing plot and default values.
  10979. Note that by default, QCustomPlot already contains a legend ready to be used as
  10980. QCustomPlot::legend
  10981. */
  10982. QCPLegend::QCPLegend()
  10983. {
  10984. setRowSpacing(0);
  10985. setColumnSpacing(10);
  10986. setMargins(QMargins(2, 3, 2, 2));
  10987. setAntialiased(false);
  10988. setIconSize(32, 18);
  10989. setIconTextPadding(7);
  10990. setSelectableParts(spLegendBox | spItems);
  10991. setSelectedParts(spNone);
  10992. setBorderPen(QPen(Qt::black));
  10993. setSelectedBorderPen(QPen(Qt::blue, 2));
  10994. setIconBorderPen(Qt::NoPen);
  10995. setSelectedIconBorderPen(QPen(Qt::blue, 2));
  10996. setBrush(Qt::white);
  10997. setSelectedBrush(Qt::white);
  10998. setTextColor(Qt::black);
  10999. setSelectedTextColor(Qt::blue);
  11000. }
  11001. QCPLegend::~QCPLegend()
  11002. {
  11003. clearItems();
  11004. if (mParentPlot)
  11005. mParentPlot->legendRemoved(this);
  11006. }
  11007. /* no doc for getter, see setSelectedParts */
  11008. QCPLegend::SelectableParts QCPLegend::selectedParts() const
  11009. {
  11010. // check whether any legend elements selected, if yes, add spItems to return value
  11011. bool hasSelectedItems = false;
  11012. for (int i=0; i<itemCount(); ++i)
  11013. {
  11014. if (item(i) && item(i)->selected())
  11015. {
  11016. hasSelectedItems = true;
  11017. break;
  11018. }
  11019. }
  11020. if (hasSelectedItems)
  11021. return mSelectedParts | spItems;
  11022. else
  11023. return mSelectedParts & ~spItems;
  11024. }
  11025. /*!
  11026. Sets the pen, the border of the entire legend is drawn with.
  11027. */
  11028. void QCPLegend::setBorderPen(const QPen &pen)
  11029. {
  11030. mBorderPen = pen;
  11031. }
  11032. /*!
  11033. Sets the brush of the legend background.
  11034. */
  11035. void QCPLegend::setBrush(const QBrush &brush)
  11036. {
  11037. mBrush = brush;
  11038. }
  11039. /*!
  11040. Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will
  11041. use this font by default. However, a different font can be specified on a per-item-basis by
  11042. accessing the specific legend item.
  11043. This function will also set \a font on all already existing legend items.
  11044. \see QCPAbstractLegendItem::setFont
  11045. */
  11046. void QCPLegend::setFont(const QFont &font)
  11047. {
  11048. mFont = font;
  11049. for (int i=0; i<itemCount(); ++i)
  11050. {
  11051. if (item(i))
  11052. item(i)->setFont(mFont);
  11053. }
  11054. }
  11055. /*!
  11056. Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph)
  11057. will use this color by default. However, a different colors can be specified on a per-item-basis
  11058. by accessing the specific legend item.
  11059. This function will also set \a color on all already existing legend items.
  11060. \see QCPAbstractLegendItem::setTextColor
  11061. */
  11062. void QCPLegend::setTextColor(const QColor &color)
  11063. {
  11064. mTextColor = color;
  11065. for (int i=0; i<itemCount(); ++i)
  11066. {
  11067. if (item(i))
  11068. item(i)->setTextColor(color);
  11069. }
  11070. }
  11071. /*!
  11072. Sets the size of legend icons. Legend items that draw an icon (e.g. a visual
  11073. representation of the graph) will use this size by default.
  11074. */
  11075. void QCPLegend::setIconSize(const QSize &size)
  11076. {
  11077. mIconSize = size;
  11078. }
  11079. /*! \overload
  11080. */
  11081. void QCPLegend::setIconSize(int width, int height)
  11082. {
  11083. mIconSize.setWidth(width);
  11084. mIconSize.setHeight(height);
  11085. }
  11086. /*!
  11087. Sets the horizontal space in pixels between the legend icon and the text next to it.
  11088. Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the
  11089. name of the graph) will use this space by default.
  11090. */
  11091. void QCPLegend::setIconTextPadding(int padding)
  11092. {
  11093. mIconTextPadding = padding;
  11094. }
  11095. /*!
  11096. Sets the pen used to draw a border around each legend icon. Legend items that draw an
  11097. icon (e.g. a visual representation of the graph) will use this pen by default.
  11098. If no border is wanted, set this to \a Qt::NoPen.
  11099. */
  11100. void QCPLegend::setIconBorderPen(const QPen &pen)
  11101. {
  11102. mIconBorderPen = pen;
  11103. }
  11104. /*!
  11105. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  11106. (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.)
  11107. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  11108. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  11109. directly.
  11110. \see SelectablePart, setSelectedParts
  11111. */
  11112. void QCPLegend::setSelectableParts(const SelectableParts &selectable)
  11113. {
  11114. if (mSelectableParts != selectable)
  11115. {
  11116. mSelectableParts = selectable;
  11117. emit selectableChanged(mSelectableParts);
  11118. }
  11119. }
  11120. /*!
  11121. Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part
  11122. is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected
  11123. doesn't contain \ref spItems, those items become deselected.
  11124. The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions
  11125. contains iSelectLegend. You only need to call this function when you wish to change the selection
  11126. state manually.
  11127. This function can change the selection state of a part even when \ref setSelectableParts was set to a
  11128. value that actually excludes the part.
  11129. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  11130. Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set
  11131. before, because there's no way to specify which exact items to newly select. Do this by calling
  11132. \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select.
  11133. \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush,
  11134. setSelectedFont
  11135. */
  11136. void QCPLegend::setSelectedParts(const SelectableParts &selected)
  11137. {
  11138. SelectableParts newSelected = selected;
  11139. mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed
  11140. if (mSelectedParts != newSelected)
  11141. {
  11142. if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that)
  11143. {
  11144. qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function";
  11145. newSelected &= ~spItems;
  11146. }
  11147. if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection
  11148. {
  11149. for (int i=0; i<itemCount(); ++i)
  11150. {
  11151. if (item(i))
  11152. item(i)->setSelected(false);
  11153. }
  11154. }
  11155. mSelectedParts = newSelected;
  11156. emit selectionChanged(mSelectedParts);
  11157. }
  11158. }
  11159. /*!
  11160. When the legend box is selected, this pen is used to draw the border instead of the normal pen
  11161. set via \ref setBorderPen.
  11162. \see setSelectedParts, setSelectableParts, setSelectedBrush
  11163. */
  11164. void QCPLegend::setSelectedBorderPen(const QPen &pen)
  11165. {
  11166. mSelectedBorderPen = pen;
  11167. }
  11168. /*!
  11169. Sets the pen legend items will use to draw their icon borders, when they are selected.
  11170. \see setSelectedParts, setSelectableParts, setSelectedFont
  11171. */
  11172. void QCPLegend::setSelectedIconBorderPen(const QPen &pen)
  11173. {
  11174. mSelectedIconBorderPen = pen;
  11175. }
  11176. /*!
  11177. When the legend box is selected, this brush is used to draw the legend background instead of the normal brush
  11178. set via \ref setBrush.
  11179. \see setSelectedParts, setSelectableParts, setSelectedBorderPen
  11180. */
  11181. void QCPLegend::setSelectedBrush(const QBrush &brush)
  11182. {
  11183. mSelectedBrush = brush;
  11184. }
  11185. /*!
  11186. Sets the default font that is used by legend items when they are selected.
  11187. This function will also set \a font on all already existing legend items.
  11188. \see setFont, QCPAbstractLegendItem::setSelectedFont
  11189. */
  11190. void QCPLegend::setSelectedFont(const QFont &font)
  11191. {
  11192. mSelectedFont = font;
  11193. for (int i=0; i<itemCount(); ++i)
  11194. {
  11195. if (item(i))
  11196. item(i)->setSelectedFont(font);
  11197. }
  11198. }
  11199. /*!
  11200. Sets the default text color that is used by legend items when they are selected.
  11201. This function will also set \a color on all already existing legend items.
  11202. \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor
  11203. */
  11204. void QCPLegend::setSelectedTextColor(const QColor &color)
  11205. {
  11206. mSelectedTextColor = color;
  11207. for (int i=0; i<itemCount(); ++i)
  11208. {
  11209. if (item(i))
  11210. item(i)->setSelectedTextColor(color);
  11211. }
  11212. }
  11213. /*!
  11214. Returns the item with index \a i.
  11215. \see itemCount
  11216. */
  11217. QCPAbstractLegendItem *QCPLegend::item(int index) const
  11218. {
  11219. return qobject_cast<QCPAbstractLegendItem*>(elementAt(index));
  11220. }
  11221. /*!
  11222. Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
  11223. If such an item isn't in the legend, returns 0.
  11224. \see hasItemWithPlottable
  11225. */
  11226. QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const
  11227. {
  11228. for (int i=0; i<itemCount(); ++i)
  11229. {
  11230. if (QCPPlottableLegendItem *pli = qobject_cast<QCPPlottableLegendItem*>(item(i)))
  11231. {
  11232. if (pli->plottable() == plottable)
  11233. return pli;
  11234. }
  11235. }
  11236. return 0;
  11237. }
  11238. /*!
  11239. Returns the number of items currently in the legend.
  11240. \see item
  11241. */
  11242. int QCPLegend::itemCount() const
  11243. {
  11244. return elementCount();
  11245. }
  11246. /*!
  11247. Returns whether the legend contains \a itm.
  11248. */
  11249. bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const
  11250. {
  11251. for (int i=0; i<itemCount(); ++i)
  11252. {
  11253. if (item == this->item(i))
  11254. return true;
  11255. }
  11256. return false;
  11257. }
  11258. /*!
  11259. Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
  11260. If such an item isn't in the legend, returns false.
  11261. \see itemWithPlottable
  11262. */
  11263. bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const
  11264. {
  11265. return itemWithPlottable(plottable);
  11266. }
  11267. /*!
  11268. Adds \a item to the legend, if it's not present already.
  11269. Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added.
  11270. The legend takes ownership of the item.
  11271. */
  11272. bool QCPLegend::addItem(QCPAbstractLegendItem *item)
  11273. {
  11274. if (!hasItem(item))
  11275. {
  11276. return addElement(rowCount(), 0, item);
  11277. } else
  11278. return false;
  11279. }
  11280. /*!
  11281. Removes the item with index \a index from the legend.
  11282. Returns true, if successful.
  11283. \see itemCount, clearItems
  11284. */
  11285. bool QCPLegend::removeItem(int index)
  11286. {
  11287. if (QCPAbstractLegendItem *ali = item(index))
  11288. {
  11289. bool success = remove(ali);
  11290. simplify();
  11291. return success;
  11292. } else
  11293. return false;
  11294. }
  11295. /*! \overload
  11296. Removes \a item from the legend.
  11297. Returns true, if successful.
  11298. \see clearItems
  11299. */
  11300. bool QCPLegend::removeItem(QCPAbstractLegendItem *item)
  11301. {
  11302. bool success = remove(item);
  11303. simplify();
  11304. return success;
  11305. }
  11306. /*!
  11307. Removes all items from the legend.
  11308. */
  11309. void QCPLegend::clearItems()
  11310. {
  11311. for (int i=itemCount()-1; i>=0; --i)
  11312. removeItem(i);
  11313. }
  11314. /*!
  11315. Returns the legend items that are currently selected. If no items are selected,
  11316. the list is empty.
  11317. \see QCPAbstractLegendItem::setSelected, setSelectable
  11318. */
  11319. QList<QCPAbstractLegendItem *> QCPLegend::selectedItems() const
  11320. {
  11321. QList<QCPAbstractLegendItem*> result;
  11322. for (int i=0; i<itemCount(); ++i)
  11323. {
  11324. if (QCPAbstractLegendItem *ali = item(i))
  11325. {
  11326. if (ali->selected())
  11327. result.append(ali);
  11328. }
  11329. }
  11330. return result;
  11331. }
  11332. /*! \internal
  11333. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  11334. before drawing main legend elements.
  11335. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  11336. This function takes into account the local setting of the antialiasing flag as well as the
  11337. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  11338. QCustomPlot::setNotAntialiasedElements.
  11339. \see setAntialiased
  11340. */
  11341. void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const
  11342. {
  11343. applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend);
  11344. }
  11345. /*! \internal
  11346. Returns the pen used to paint the border of the legend, taking into account the selection state
  11347. of the legend box.
  11348. */
  11349. QPen QCPLegend::getBorderPen() const
  11350. {
  11351. return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen;
  11352. }
  11353. /*! \internal
  11354. Returns the brush used to paint the background of the legend, taking into account the selection
  11355. state of the legend box.
  11356. */
  11357. QBrush QCPLegend::getBrush() const
  11358. {
  11359. return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush;
  11360. }
  11361. /*! \internal
  11362. Draws the legend box with the provided \a painter. The individual legend items are layerables
  11363. themselves, thus are drawn independently.
  11364. */
  11365. void QCPLegend::draw(QCPPainter *painter)
  11366. {
  11367. // draw background rect:
  11368. painter->setBrush(getBrush());
  11369. painter->setPen(getBorderPen());
  11370. painter->drawRect(mOuterRect);
  11371. }
  11372. /* inherits documentation from base class */
  11373. double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  11374. {
  11375. if (!mParentPlot) return -1;
  11376. if (onlySelectable && !mSelectableParts.testFlag(spLegendBox))
  11377. return -1;
  11378. if (mOuterRect.contains(pos.toPoint()))
  11379. {
  11380. if (details) details->setValue(spLegendBox);
  11381. return mParentPlot->selectionTolerance()*0.99;
  11382. }
  11383. return -1;
  11384. }
  11385. /* inherits documentation from base class */
  11386. void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  11387. {
  11388. Q_UNUSED(event)
  11389. mSelectedParts = selectedParts(); // in case item selection has changed
  11390. if (details.value<SelectablePart>() == spLegendBox && mSelectableParts.testFlag(spLegendBox))
  11391. {
  11392. SelectableParts selBefore = mSelectedParts;
  11393. 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)
  11394. if (selectionStateChanged)
  11395. *selectionStateChanged = mSelectedParts != selBefore;
  11396. }
  11397. }
  11398. /* inherits documentation from base class */
  11399. void QCPLegend::deselectEvent(bool *selectionStateChanged)
  11400. {
  11401. mSelectedParts = selectedParts(); // in case item selection has changed
  11402. if (mSelectableParts.testFlag(spLegendBox))
  11403. {
  11404. SelectableParts selBefore = mSelectedParts;
  11405. setSelectedParts(selectedParts() & ~spLegendBox);
  11406. if (selectionStateChanged)
  11407. *selectionStateChanged = mSelectedParts != selBefore;
  11408. }
  11409. }
  11410. /* inherits documentation from base class */
  11411. QCP::Interaction QCPLegend::selectionCategory() const
  11412. {
  11413. return QCP::iSelectLegend;
  11414. }
  11415. /* inherits documentation from base class */
  11416. QCP::Interaction QCPAbstractLegendItem::selectionCategory() const
  11417. {
  11418. return QCP::iSelectLegend;
  11419. }
  11420. /* inherits documentation from base class */
  11421. void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot)
  11422. {
  11423. Q_UNUSED(parentPlot)
  11424. }
  11425. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11426. //////////////////// QCPPlotTitle
  11427. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11428. /*! \class QCPPlotTitle
  11429. \brief A layout element displaying a plot title text
  11430. The text may be specified with \ref setText, theformatting can be controlled with \ref setFont
  11431. and \ref setTextColor.
  11432. A plot title can be added as follows:
  11433. \code
  11434. customPlot->plotLayout()->insertRow(0); // inserts an empty row above the default axis rect
  11435. customPlot->plotLayout()->addElement(0, 0, new QCPPlotTitle(customPlot, "Your Plot Title"));
  11436. \endcode
  11437. Since a plot title is a common requirement, QCustomPlot offers specialized selection signals for
  11438. easy interaction with QCPPlotTitle. If a layout element of type QCPPlotTitle is clicked, the
  11439. signal \ref QCustomPlot::titleClick is emitted. A double click emits the \ref
  11440. QCustomPlot::titleDoubleClick signal.
  11441. */
  11442. /* start documentation of signals */
  11443. /*! \fn void QCPPlotTitle::selectionChanged(bool selected)
  11444. This signal is emitted when the selection state has changed to \a selected, either by user
  11445. interaction or by a direct call to \ref setSelected.
  11446. \see setSelected, setSelectable
  11447. */
  11448. /* end documentation of signals */
  11449. /*!
  11450. Creates a new QCPPlotTitle instance and sets default values. The initial text is empty (\ref setText).
  11451. To set the title text in the constructor, rather use \ref QCPPlotTitle(QCustomPlot *parentPlot, const QString &text).
  11452. */
  11453. QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot) :
  11454. QCPLayoutElement(parentPlot),
  11455. mFont(QFont("sans serif", 13*1.5, QFont::Bold)),
  11456. mTextColor(Qt::black),
  11457. mSelectedFont(QFont("sans serif", 13*1.6, QFont::Bold)),
  11458. mSelectedTextColor(Qt::blue),
  11459. mSelectable(false),
  11460. mSelected(false)
  11461. {
  11462. if (parentPlot)
  11463. {
  11464. setLayer(parentPlot->currentLayer());
  11465. mFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold);
  11466. mSelectedFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold);
  11467. }
  11468. setMargins(QMargins(5, 5, 5, 0));
  11469. }
  11470. /*! \overload
  11471. Creates a new QCPPlotTitle instance and sets default values. The initial text is set to \a text.
  11472. */
  11473. QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot, const QString &text) :
  11474. QCPLayoutElement(parentPlot),
  11475. mText(text),
  11476. mFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold)),
  11477. mTextColor(Qt::black),
  11478. mSelectedFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold)),
  11479. mSelectedTextColor(Qt::blue),
  11480. mSelectable(false),
  11481. mSelected(false)
  11482. {
  11483. setLayer("axes");
  11484. setMargins(QMargins(5, 5, 5, 0));
  11485. }
  11486. /*!
  11487. Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n".
  11488. \see setFont, setTextColor
  11489. */
  11490. void QCPPlotTitle::setText(const QString &text)
  11491. {
  11492. mText = text;
  11493. }
  11494. /*!
  11495. Sets the \a font of the title text.
  11496. \see setTextColor, setSelectedFont
  11497. */
  11498. void QCPPlotTitle::setFont(const QFont &font)
  11499. {
  11500. mFont = font;
  11501. }
  11502. /*!
  11503. Sets the \a color of the title text.
  11504. \see setFont, setSelectedTextColor
  11505. */
  11506. void QCPPlotTitle::setTextColor(const QColor &color)
  11507. {
  11508. mTextColor = color;
  11509. }
  11510. /*!
  11511. Sets the \a font of the title text that will be used if the plot title is selected (\ref setSelected).
  11512. \see setFont
  11513. */
  11514. void QCPPlotTitle::setSelectedFont(const QFont &font)
  11515. {
  11516. mSelectedFont = font;
  11517. }
  11518. /*!
  11519. Sets the \a color of the title text that will be used if the plot title is selected (\ref setSelected).
  11520. \see setTextColor
  11521. */
  11522. void QCPPlotTitle::setSelectedTextColor(const QColor &color)
  11523. {
  11524. mSelectedTextColor = color;
  11525. }
  11526. /*!
  11527. Sets whether the user may select this plot title to \a selectable.
  11528. Note that even when \a selectable is set to <tt>false</tt>, the selection state may be changed
  11529. programmatically via \ref setSelected.
  11530. */
  11531. void QCPPlotTitle::setSelectable(bool selectable)
  11532. {
  11533. if (mSelectable != selectable)
  11534. {
  11535. mSelectable = selectable;
  11536. emit selectableChanged(mSelectable);
  11537. }
  11538. }
  11539. /*!
  11540. Sets the selection state of this plot title to \a selected. If the selection has changed, \ref
  11541. selectionChanged is emitted.
  11542. Note that this function can change the selection state independently of the current \ref
  11543. setSelectable state.
  11544. */
  11545. void QCPPlotTitle::setSelected(bool selected)
  11546. {
  11547. if (mSelected != selected)
  11548. {
  11549. mSelected = selected;
  11550. emit selectionChanged(mSelected);
  11551. }
  11552. }
  11553. /* inherits documentation from base class */
  11554. void QCPPlotTitle::applyDefaultAntialiasingHint(QCPPainter *painter) const
  11555. {
  11556. applyAntialiasingHint(painter, mAntialiased, QCP::aeNone);
  11557. }
  11558. /* inherits documentation from base class */
  11559. void QCPPlotTitle::draw(QCPPainter *painter)
  11560. {
  11561. painter->setFont(mainFont());
  11562. painter->setPen(QPen(mainTextColor()));
  11563. painter->drawText(mRect, Qt::AlignCenter, mText, &mTextBoundingRect);
  11564. }
  11565. /* inherits documentation from base class */
  11566. QSize QCPPlotTitle::minimumSizeHint() const
  11567. {
  11568. QFontMetrics metrics(mFont);
  11569. QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size();
  11570. result.rwidth() += mMargins.left() + mMargins.right();
  11571. result.rheight() += mMargins.top() + mMargins.bottom();
  11572. return result;
  11573. }
  11574. /* inherits documentation from base class */
  11575. QSize QCPPlotTitle::maximumSizeHint() const
  11576. {
  11577. QFontMetrics metrics(mFont);
  11578. QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size();
  11579. result.rheight() += mMargins.top() + mMargins.bottom();
  11580. result.setWidth(QWIDGETSIZE_MAX);
  11581. return result;
  11582. }
  11583. /* inherits documentation from base class */
  11584. void QCPPlotTitle::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  11585. {
  11586. Q_UNUSED(event)
  11587. Q_UNUSED(details)
  11588. if (mSelectable)
  11589. {
  11590. bool selBefore = mSelected;
  11591. setSelected(additive ? !mSelected : true);
  11592. if (selectionStateChanged)
  11593. *selectionStateChanged = mSelected != selBefore;
  11594. }
  11595. }
  11596. /* inherits documentation from base class */
  11597. void QCPPlotTitle::deselectEvent(bool *selectionStateChanged)
  11598. {
  11599. if (mSelectable)
  11600. {
  11601. bool selBefore = mSelected;
  11602. setSelected(false);
  11603. if (selectionStateChanged)
  11604. *selectionStateChanged = mSelected != selBefore;
  11605. }
  11606. }
  11607. /* inherits documentation from base class */
  11608. double QCPPlotTitle::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  11609. {
  11610. Q_UNUSED(details)
  11611. if (onlySelectable && !mSelectable)
  11612. return -1;
  11613. if (mTextBoundingRect.contains(pos.toPoint()))
  11614. return mParentPlot->selectionTolerance()*0.99;
  11615. else
  11616. return -1;
  11617. }
  11618. /*! \internal
  11619. Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to
  11620. <tt>true</tt>, else mFont is returned.
  11621. */
  11622. QFont QCPPlotTitle::mainFont() const
  11623. {
  11624. return mSelected ? mSelectedFont : mFont;
  11625. }
  11626. /*! \internal
  11627. Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to
  11628. <tt>true</tt>, else mTextColor is returned.
  11629. */
  11630. QColor QCPPlotTitle::mainTextColor() const
  11631. {
  11632. return mSelected ? mSelectedTextColor : mTextColor;
  11633. }
  11634. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11635. //////////////////// QCPColorScale
  11636. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11637. /*! \class QCPColorScale
  11638. \brief A color scale for use with color coding data such as QCPColorMap
  11639. This layout element can be placed on the plot to correlate a color gradient with data values. It
  11640. is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps".
  11641. \image html QCPColorScale.png
  11642. The color scale can be either horizontal or vertical, as shown in the image above. The
  11643. orientation and the side where the numbers appear is controlled with \ref setType.
  11644. Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are
  11645. connected, they share their gradient, data range and data scale type (\ref setGradient, \ref
  11646. setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color
  11647. scale, to make them all synchronize these properties.
  11648. To have finer control over the number display and axis behaviour, you can directly access the
  11649. \ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if
  11650. you want to change the number of automatically generated ticks, call
  11651. \code
  11652. colorScale->axis()->setAutoTickCount(3);
  11653. \endcode
  11654. Placing a color scale next to the main axis rect works like with any other layout element:
  11655. \code
  11656. QCPColorScale *colorScale = new QCPColorScale(customPlot);
  11657. customPlot->plotLayout()->addElement(0, 1, colorScale);
  11658. colorScale->setLabel("Some Label Text");
  11659. \endcode
  11660. In this case we have placed it to the right of the default axis rect, so it wasn't necessary to
  11661. call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color
  11662. scale can be set with \ref setLabel.
  11663. For optimum appearance (like in the image above), it may be desirable to line up the axis rect and
  11664. the borders of the color scale. Use a \ref QCPMarginGroup to achieve this:
  11665. \code
  11666. QCPMarginGroup *group = new QCPMarginGroup(customPlot);
  11667. colorScale->setMarginGroup(QCP::msTop|QCP::msBottom, group);
  11668. customPlot->axisRect()->setMarginGroup(QCP::msTop|QCP::msBottom, group);
  11669. \endcode
  11670. Color scales are initialized with a non-zero minimum top and bottom margin (\ref
  11671. setMinimumMargins), because vertical color scales are most common and the minimum top/bottom
  11672. margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a
  11673. horizontal color scale by setting \ref setType to \ref QCPAxis::atBottom or \ref QCPAxis::atTop, you
  11674. might want to also change the minimum margins accordingly, e.g. \ref
  11675. setMinimumMargins(QMargins(6, 0, 6, 0)).
  11676. */
  11677. /* start documentation of inline functions */
  11678. /*! \fn QCPAxis *QCPColorScale::axis() const
  11679. Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the
  11680. appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its
  11681. interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref
  11682. setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref
  11683. QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on
  11684. the QCPColorScale or on its QCPAxis.
  11685. If the type of the color scale is changed with \ref setType, the axis returned by this method
  11686. will change, too, to either the left, right, bottom or top axis, depending on which type was set.
  11687. */
  11688. /* end documentation of signals */
  11689. /* start documentation of signals */
  11690. /*! \fn void QCPColorScale::dataRangeChanged(QCPRange newRange);
  11691. This signal is emitted when the data range changes.
  11692. \see setDataRange
  11693. */
  11694. /*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
  11695. This signal is emitted when the data scale type changes.
  11696. \see setDataScaleType
  11697. */
  11698. /*! \fn void QCPColorScale::gradientChanged(QCPColorGradient newGradient);
  11699. This signal is emitted when the gradient changes.
  11700. \see setGradient
  11701. */
  11702. /* end documentation of signals */
  11703. /*!
  11704. Constructs a new QCPColorScale.
  11705. */
  11706. QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) :
  11707. QCPLayoutElement(parentPlot),
  11708. mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight
  11709. mDataScaleType(QCPAxis::stLinear),
  11710. mBarWidth(20),
  11711. mAxisRect(new QCPColorScaleAxisRectPrivate(this))
  11712. {
  11713. 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)
  11714. setType(QCPAxis::atRight);
  11715. setDataRange(QCPRange(0, 6));
  11716. }
  11717. QCPColorScale::~QCPColorScale()
  11718. {
  11719. delete mAxisRect;
  11720. }
  11721. /* undocumented getter */
  11722. QString QCPColorScale::label() const
  11723. {
  11724. if (!mColorAxis)
  11725. {
  11726. qDebug() << Q_FUNC_INFO << "internal color axis undefined";
  11727. return QString();
  11728. }
  11729. return mColorAxis.data()->label();
  11730. }
  11731. /* undocumented getter */
  11732. bool QCPColorScale::rangeDrag() const
  11733. {
  11734. if (!mAxisRect)
  11735. {
  11736. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  11737. return false;
  11738. }
  11739. return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) &&
  11740. mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) &&
  11741. mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
  11742. }
  11743. /* undocumented getter */
  11744. bool QCPColorScale::rangeZoom() const
  11745. {
  11746. if (!mAxisRect)
  11747. {
  11748. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  11749. return false;
  11750. }
  11751. return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) &&
  11752. mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) &&
  11753. mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
  11754. }
  11755. /*!
  11756. Sets at which side of the color scale the axis is placed, and thus also its orientation.
  11757. Note that after setting \a type to a different value, the axis returned by \ref axis() will
  11758. be a different one. The new axis will adopt the following properties from the previous axis: The
  11759. range, scale type, log base and label.
  11760. */
  11761. void QCPColorScale::setType(QCPAxis::AxisType type)
  11762. {
  11763. if (!mAxisRect)
  11764. {
  11765. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  11766. return;
  11767. }
  11768. if (mType != type)
  11769. {
  11770. mType = type;
  11771. QCPRange rangeTransfer(0, 6);
  11772. double logBaseTransfer = 10;
  11773. QString labelTransfer;
  11774. // revert some settings on old axis:
  11775. if (mColorAxis)
  11776. {
  11777. rangeTransfer = mColorAxis.data()->range();
  11778. labelTransfer = mColorAxis.data()->label();
  11779. logBaseTransfer = mColorAxis.data()->scaleLogBase();
  11780. mColorAxis.data()->setLabel("");
  11781. disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  11782. disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  11783. }
  11784. foreach (QCPAxis::AxisType atype, QList<QCPAxis::AxisType>() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop)
  11785. {
  11786. mAxisRect.data()->axis(atype)->setTicks(atype == mType);
  11787. mAxisRect.data()->axis(atype)->setTickLabels(atype== mType);
  11788. }
  11789. // set new mColorAxis pointer:
  11790. mColorAxis = mAxisRect.data()->axis(mType);
  11791. // transfer settings to new axis:
  11792. mColorAxis.data()->setRange(rangeTransfer); // transfer range of old axis to new one (necessary if axis changes from vertical to horizontal or vice versa)
  11793. mColorAxis.data()->setLabel(labelTransfer);
  11794. mColorAxis.data()->setScaleLogBase(logBaseTransfer); // scaleType is synchronized among axes in realtime via signals (connected in QCPColorScale ctor), so we only need to take care of log base here
  11795. connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  11796. connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  11797. mAxisRect.data()->setRangeDragAxes(QCPAxis::orientation(mType) == Qt::Horizontal ? mColorAxis.data() : 0,
  11798. QCPAxis::orientation(mType) == Qt::Vertical ? mColorAxis.data() : 0);
  11799. }
  11800. }
  11801. /*!
  11802. Sets the range spanned by the color gradient and that is shown by the axis in the color scale.
  11803. It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is
  11804. also equivalent to directly accessing the \ref axis and setting its range with \ref
  11805. QCPAxis::setRange.
  11806. \see setDataScaleType, setGradient, rescaleDataRange
  11807. */
  11808. void QCPColorScale::setDataRange(const QCPRange &dataRange)
  11809. {
  11810. if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
  11811. {
  11812. mDataRange = dataRange;
  11813. if (mColorAxis)
  11814. mColorAxis.data()->setRange(mDataRange);
  11815. emit dataRangeChanged(mDataRange);
  11816. }
  11817. }
  11818. /*!
  11819. Sets the scale type of the color scale, i.e. whether values are linearly associated with colors
  11820. or logarithmically.
  11821. It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is
  11822. also equivalent to directly accessing the \ref axis and setting its scale type with \ref
  11823. QCPAxis::setScaleType.
  11824. \see setDataRange, setGradient
  11825. */
  11826. void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType)
  11827. {
  11828. if (mDataScaleType != scaleType)
  11829. {
  11830. mDataScaleType = scaleType;
  11831. if (mColorAxis)
  11832. mColorAxis.data()->setScaleType(mDataScaleType);
  11833. if (mDataScaleType == QCPAxis::stLogarithmic)
  11834. setDataRange(mDataRange.sanitizedForLogScale());
  11835. emit dataScaleTypeChanged(mDataScaleType);
  11836. }
  11837. }
  11838. /*!
  11839. Sets the color gradient that will be used to represent data values.
  11840. It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps.
  11841. \see setDataRange, setDataScaleType
  11842. */
  11843. void QCPColorScale::setGradient(const QCPColorGradient &gradient)
  11844. {
  11845. if (mGradient != gradient)
  11846. {
  11847. mGradient = gradient;
  11848. if (mAxisRect)
  11849. mAxisRect.data()->mGradientImageInvalidated = true;
  11850. emit gradientChanged(mGradient);
  11851. }
  11852. }
  11853. /*!
  11854. Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on
  11855. the internal \ref axis.
  11856. */
  11857. void QCPColorScale::setLabel(const QString &str)
  11858. {
  11859. if (!mColorAxis)
  11860. {
  11861. qDebug() << Q_FUNC_INFO << "internal color axis undefined";
  11862. return;
  11863. }
  11864. mColorAxis.data()->setLabel(str);
  11865. }
  11866. /*!
  11867. Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed
  11868. will have.
  11869. */
  11870. void QCPColorScale::setBarWidth(int width)
  11871. {
  11872. mBarWidth = width;
  11873. }
  11874. /*!
  11875. Sets whether the user can drag the data range (\ref setDataRange).
  11876. Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref
  11877. QCustomPlot::setInteractions) to allow range dragging.
  11878. */
  11879. void QCPColorScale::setRangeDrag(bool enabled)
  11880. {
  11881. if (!mAxisRect)
  11882. {
  11883. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  11884. return;
  11885. }
  11886. if (enabled)
  11887. mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType));
  11888. else
  11889. mAxisRect.data()->setRangeDrag(0);
  11890. }
  11891. /*!
  11892. Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel.
  11893. Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref
  11894. QCustomPlot::setInteractions) to allow range dragging.
  11895. */
  11896. void QCPColorScale::setRangeZoom(bool enabled)
  11897. {
  11898. if (!mAxisRect)
  11899. {
  11900. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  11901. return;
  11902. }
  11903. if (enabled)
  11904. mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType));
  11905. else
  11906. mAxisRect.data()->setRangeZoom(0);
  11907. }
  11908. /*!
  11909. Returns a list of all the color maps associated with this color scale.
  11910. */
  11911. QList<QCPColorMap*> QCPColorScale::colorMaps() const
  11912. {
  11913. QList<QCPColorMap*> result;
  11914. for (int i=0; i<mParentPlot->plottableCount(); ++i)
  11915. {
  11916. if (QCPColorMap *cm = qobject_cast<QCPColorMap*>(mParentPlot->plottable(i)))
  11917. if (cm->colorScale() == this)
  11918. result.append(cm);
  11919. }
  11920. return result;
  11921. }
  11922. /*!
  11923. Changes the data range such that all color maps associated with this color scale are fully mapped
  11924. to the gradient in the data dimension.
  11925. \see setDataRange
  11926. */
  11927. void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps)
  11928. {
  11929. QList<QCPColorMap*> maps = colorMaps();
  11930. QCPRange newRange;
  11931. bool haveRange = false;
  11932. int sign = 0; // TODO: should change this to QCPAbstractPlottable::SignDomain later (currently is protected, maybe move to QCP namespace)
  11933. if (mDataScaleType == QCPAxis::stLogarithmic)
  11934. sign = (mDataRange.upper < 0 ? -1 : 1);
  11935. for (int i=0; i<maps.size(); ++i)
  11936. {
  11937. if (!maps.at(i)->realVisibility() && onlyVisibleMaps)
  11938. continue;
  11939. QCPRange mapRange;
  11940. if (maps.at(i)->colorScale() == this)
  11941. {
  11942. bool currentFoundRange = true;
  11943. mapRange = maps.at(i)->data()->dataBounds();
  11944. if (sign == 1)
  11945. {
  11946. if (mapRange.lower <= 0 && mapRange.upper > 0)
  11947. mapRange.lower = mapRange.upper*1e-3;
  11948. else if (mapRange.lower <= 0 && mapRange.upper <= 0)
  11949. currentFoundRange = false;
  11950. } else if (sign == -1)
  11951. {
  11952. if (mapRange.upper >= 0 && mapRange.lower < 0)
  11953. mapRange.upper = mapRange.lower*1e-3;
  11954. else if (mapRange.upper >= 0 && mapRange.lower >= 0)
  11955. currentFoundRange = false;
  11956. }
  11957. if (currentFoundRange)
  11958. {
  11959. if (!haveRange)
  11960. newRange = mapRange;
  11961. else
  11962. newRange.expand(mapRange);
  11963. haveRange = true;
  11964. }
  11965. }
  11966. }
  11967. if (haveRange)
  11968. {
  11969. 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
  11970. {
  11971. 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
  11972. if (mDataScaleType == QCPAxis::stLinear)
  11973. {
  11974. newRange.lower = center-mDataRange.size()/2.0;
  11975. newRange.upper = center+mDataRange.size()/2.0;
  11976. } else // mScaleType == stLogarithmic
  11977. {
  11978. newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower);
  11979. newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower);
  11980. }
  11981. }
  11982. setDataRange(newRange);
  11983. }
  11984. }
  11985. /* inherits documentation from base class */
  11986. void QCPColorScale::update(UpdatePhase phase)
  11987. {
  11988. QCPLayoutElement::update(phase);
  11989. if (!mAxisRect)
  11990. {
  11991. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  11992. return;
  11993. }
  11994. mAxisRect.data()->update(phase);
  11995. switch (phase)
  11996. {
  11997. case upMargins:
  11998. {
  11999. if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop)
  12000. {
  12001. setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom());
  12002. setMinimumSize(0, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom());
  12003. } else
  12004. {
  12005. setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), QWIDGETSIZE_MAX);
  12006. setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), 0);
  12007. }
  12008. break;
  12009. }
  12010. case upLayout:
  12011. {
  12012. mAxisRect.data()->setOuterRect(rect());
  12013. break;
  12014. }
  12015. default: break;
  12016. }
  12017. }
  12018. /* inherits documentation from base class */
  12019. void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const
  12020. {
  12021. painter->setAntialiasing(false);
  12022. }
  12023. /* inherits documentation from base class */
  12024. void QCPColorScale::mousePressEvent(QMouseEvent *event)
  12025. {
  12026. if (!mAxisRect)
  12027. {
  12028. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  12029. return;
  12030. }
  12031. mAxisRect.data()->mousePressEvent(event);
  12032. }
  12033. /* inherits documentation from base class */
  12034. void QCPColorScale::mouseMoveEvent(QMouseEvent *event)
  12035. {
  12036. if (!mAxisRect)
  12037. {
  12038. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  12039. return;
  12040. }
  12041. mAxisRect.data()->mouseMoveEvent(event);
  12042. }
  12043. /* inherits documentation from base class */
  12044. void QCPColorScale::mouseReleaseEvent(QMouseEvent *event)
  12045. {
  12046. if (!mAxisRect)
  12047. {
  12048. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  12049. return;
  12050. }
  12051. mAxisRect.data()->mouseReleaseEvent(event);
  12052. }
  12053. /* inherits documentation from base class */
  12054. void QCPColorScale::wheelEvent(QWheelEvent *event)
  12055. {
  12056. if (!mAxisRect)
  12057. {
  12058. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  12059. return;
  12060. }
  12061. mAxisRect.data()->wheelEvent(event);
  12062. }
  12063. ////////////////////////////////////////////////////////////////////////////////////////////////////
  12064. //////////////////// QCPColorScaleAxisRectPrivate
  12065. ////////////////////////////////////////////////////////////////////////////////////////////////////
  12066. /*! \class QCPColorScaleAxisRectPrivate
  12067. \internal
  12068. \brief An axis rect subclass for use in a QCPColorScale
  12069. This is a private class and not part of the public QCustomPlot interface.
  12070. It provides the axis rect functionality for the QCPColorScale class.
  12071. */
  12072. /*!
  12073. Creates a new instance, as a child of \a parentColorScale.
  12074. */
  12075. QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) :
  12076. QCPAxisRect(parentColorScale->parentPlot(), true),
  12077. mParentColorScale(parentColorScale),
  12078. mGradientImageInvalidated(true)
  12079. {
  12080. setParentLayerable(parentColorScale);
  12081. setMinimumMargins(QMargins(0, 0, 0, 0));
  12082. foreach (QCPAxis::AxisType type, QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight)
  12083. {
  12084. axis(type)->setVisible(true);
  12085. axis(type)->grid()->setVisible(false);
  12086. axis(type)->setPadding(0);
  12087. connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts)));
  12088. connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts)));
  12089. }
  12090. connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange)));
  12091. connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange)));
  12092. connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange)));
  12093. connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange)));
  12094. connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType)));
  12095. connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType)));
  12096. connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType)));
  12097. connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType)));
  12098. // make layer transfers of color scale transfer to axis rect and axes
  12099. // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect:
  12100. connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*)));
  12101. foreach (QCPAxis::AxisType type, QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight)
  12102. connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*)));
  12103. }
  12104. /*! \internal
  12105. Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws
  12106. it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation.
  12107. */
  12108. void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter)
  12109. {
  12110. if (mGradientImageInvalidated)
  12111. updateGradientImage();
  12112. bool mirrorHorz = false;
  12113. bool mirrorVert = false;
  12114. if (mParentColorScale->mColorAxis)
  12115. {
  12116. mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop);
  12117. mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight);
  12118. }
  12119. painter->drawImage(rect(), mGradientImage.mirrored(mirrorHorz, mirrorVert));
  12120. QCPAxisRect::draw(painter);
  12121. }
  12122. /*! \internal
  12123. Uses the current gradient of the parent \ref QCPColorScale (specified in the constructor) to
  12124. generate a gradient image. This gradient image will be used in the \ref draw method.
  12125. */
  12126. void QCPColorScaleAxisRectPrivate::updateGradientImage()
  12127. {
  12128. if (rect().isEmpty())
  12129. return;
  12130. int n = mParentColorScale->mGradient.levelCount();
  12131. int w, h;
  12132. QVector<double> data(n);
  12133. for (int i=0; i<n; ++i)
  12134. data[i] = i;
  12135. if (mParentColorScale->mType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop)
  12136. {
  12137. w = n;
  12138. h = rect().height();
  12139. mGradientImage = QImage(w, h, QImage::Format_RGB32);
  12140. QVector<QRgb*> pixels;
  12141. for (int y=0; y<h; ++y)
  12142. pixels.append(reinterpret_cast<QRgb*>(mGradientImage.scanLine(y)));
  12143. mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n);
  12144. for (int y=1; y<h; ++y)
  12145. memcpy(pixels.at(y), pixels.first(), n*sizeof(QRgb));
  12146. } else
  12147. {
  12148. w = rect().width();
  12149. h = n;
  12150. mGradientImage = QImage(w, h, QImage::Format_RGB32);
  12151. for (int y=0; y<h; ++y)
  12152. {
  12153. QRgb *pixels = reinterpret_cast<QRgb*>(mGradientImage.scanLine(y));
  12154. const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1));
  12155. for (int x=0; x<w; ++x)
  12156. pixels[x] = lineColor;
  12157. }
  12158. }
  12159. mGradientImageInvalidated = false;
  12160. }
  12161. /*! \internal
  12162. This slot is connected to the selectionChanged signals of the four axes in the constructor. It
  12163. synchronizes the selection state of the axes.
  12164. */
  12165. void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts selectedParts)
  12166. {
  12167. // axis bases of four axes shall always (de-)selected synchronously:
  12168. foreach (QCPAxis::AxisType type, QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight)
  12169. {
  12170. if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
  12171. if (senderAxis->axisType() == type)
  12172. continue;
  12173. if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
  12174. {
  12175. if (selectedParts.testFlag(QCPAxis::spAxis))
  12176. axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis);
  12177. else
  12178. axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis);
  12179. }
  12180. }
  12181. }
  12182. /*! \internal
  12183. This slot is connected to the selectableChanged signals of the four axes in the constructor. It
  12184. synchronizes the selectability of the axes.
  12185. */
  12186. void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts)
  12187. {
  12188. // synchronize axis base selectability:
  12189. foreach (QCPAxis::AxisType type, QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight)
  12190. {
  12191. if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
  12192. if (senderAxis->axisType() == type)
  12193. continue;
  12194. if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
  12195. {
  12196. if (selectableParts.testFlag(QCPAxis::spAxis))
  12197. axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis);
  12198. else
  12199. axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis);
  12200. }
  12201. }
  12202. }
  12203. ////////////////////////////////////////////////////////////////////////////////////////////////////
  12204. //////////////////// QCPData
  12205. ////////////////////////////////////////////////////////////////////////////////////////////////////
  12206. /*! \class QCPData
  12207. \brief Holds the data of one single data point for QCPGraph.
  12208. The container for storing multiple data points is \ref QCPDataMap.
  12209. The stored data is:
  12210. \li \a key: coordinate on the key axis of this data point
  12211. \li \a value: coordinate on the value axis of this data point
  12212. \li \a keyErrorMinus: negative error in the key dimension (for error bars)
  12213. \li \a keyErrorPlus: positive error in the key dimension (for error bars)
  12214. \li \a valueErrorMinus: negative error in the value dimension (for error bars)
  12215. \li \a valueErrorPlus: positive error in the value dimension (for error bars)
  12216. \see QCPDataMap
  12217. */
  12218. /*!
  12219. Constructs a data point with key, value and all errors set to zero.
  12220. */
  12221. QCPData::QCPData() :
  12222. key(0),
  12223. value(0),
  12224. keyErrorPlus(0),
  12225. keyErrorMinus(0),
  12226. valueErrorPlus(0),
  12227. valueErrorMinus(0)
  12228. {
  12229. }
  12230. /*!
  12231. Constructs a data point with the specified \a key and \a value. All errors are set to zero.
  12232. */
  12233. QCPData::QCPData(double key, double value) :
  12234. key(key),
  12235. value(value),
  12236. keyErrorPlus(0),
  12237. keyErrorMinus(0),
  12238. valueErrorPlus(0),
  12239. valueErrorMinus(0)
  12240. {
  12241. }
  12242. ////////////////////////////////////////////////////////////////////////////////////////////////////
  12243. //////////////////// QCPGraph
  12244. ////////////////////////////////////////////////////////////////////////////////////////////////////
  12245. /*! \class QCPGraph
  12246. \brief A plottable representing a graph in a plot.
  12247. \image html QCPGraph.png
  12248. Usually QCustomPlot creates graphs internally via QCustomPlot::addGraph and the resulting
  12249. instance is accessed via QCustomPlot::graph.
  12250. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
  12251. also access and modify the graph's data via the \ref data method, which returns a pointer to the
  12252. internal \ref QCPDataMap.
  12253. Graphs are used to display single-valued data. Single-valued means that there should only be one
  12254. data point per unique key coordinate. In other words, the graph can't have \a loops. If you do
  12255. want to plot non-single-valued curves, rather use the QCPCurve plottable.
  12256. \section appearance Changing the appearance
  12257. The appearance of the graph is mainly determined by the line style, scatter style, brush and pen
  12258. of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen).
  12259. \subsection filling Filling under or between graphs
  12260. QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to
  12261. the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill,
  12262. just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent.
  12263. By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill
  12264. between this graph and another one, call \ref setChannelFillGraph with the other graph as
  12265. parameter.
  12266. \see QCustomPlot::addGraph, QCustomPlot::graph, QCPLegend::addGraph
  12267. */
  12268. /* start of documentation of inline functions */
  12269. /*! \fn QCPDataMap *QCPGraph::data() const
  12270. Returns a pointer to the internal data storage of type \ref QCPDataMap. You may use it to
  12271. directly manipulate the data, which may be more convenient and faster than using the regular \ref
  12272. setData or \ref addData methods, in certain situations.
  12273. */
  12274. /* end of documentation of inline functions */
  12275. /*!
  12276. Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  12277. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  12278. the same orientation. If either of these restrictions is violated, a corresponding message is
  12279. printed to the debug output (qDebug), the construction is not aborted, though.
  12280. The constructed QCPGraph can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
  12281. then takes ownership of the graph.
  12282. To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function.
  12283. */
  12284. QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  12285. QCPAbstractPlottable(keyAxis, valueAxis)
  12286. {
  12287. mData = new QCPDataMap;
  12288. setPen(QPen(Qt::blue, 0));
  12289. setErrorPen(QPen(Qt::black));
  12290. setBrush(Qt::NoBrush);
  12291. setSelectedPen(QPen(QColor(80, 80, 255), 2.5));
  12292. setSelectedBrush(Qt::NoBrush);
  12293. setLineStyle(lsLine);
  12294. setErrorType(etNone);
  12295. setErrorBarSize(6);
  12296. setErrorBarSkipSymbol(true);
  12297. setChannelFillGraph(0);
  12298. setAdaptiveSampling(true);
  12299. }
  12300. QCPGraph::~QCPGraph()
  12301. {
  12302. delete mData;
  12303. }
  12304. /*!
  12305. Replaces the current data with the provided \a data.
  12306. If \a copy is set to true, data points in \a data will only be copied. if false, the graph
  12307. takes ownership of the passed data and replaces the internal data pointer with it. This is
  12308. significantly faster than copying for large datasets.
  12309. Alternatively, you can also access and modify the graph's data via the \ref data method, which
  12310. returns a pointer to the internal \ref QCPDataMap.
  12311. */
  12312. void QCPGraph::setData(QCPDataMap *data, bool copy)
  12313. {
  12314. if (copy)
  12315. {
  12316. *mData = *data;
  12317. } else
  12318. {
  12319. delete mData;
  12320. mData = data;
  12321. }
  12322. }
  12323. /*! \overload
  12324. Replaces the current data with the provided points in \a key and \a value pairs. The provided
  12325. vectors should have equal length. Else, the number of added points will be the size of the
  12326. smallest vector.
  12327. */
  12328. void QCPGraph::setData(const QVector<double> &key, const QVector<double> &value)
  12329. {
  12330. mData->clear();
  12331. int n = key.size();
  12332. n = qMin(n, value.size());
  12333. QCPData newData;
  12334. for (int i=0; i<n; ++i)
  12335. {
  12336. newData.key = key[i];
  12337. newData.value = value[i];
  12338. mData->insertMulti(newData.key, newData);
  12339. }
  12340. }
  12341. /*!
  12342. Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
  12343. symmetrical value error of the data points are set to the values in \a valueError.
  12344. For error bars to show appropriately, see \ref setErrorType.
  12345. The provided vectors should have equal length. Else, the number of added points will be the size of the
  12346. smallest vector.
  12347. For asymmetrical errors (plus different from minus), see the overloaded version of this function.
  12348. */
  12349. void QCPGraph::setDataValueError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &valueError)
  12350. {
  12351. mData->clear();
  12352. int n = key.size();
  12353. n = qMin(n, value.size());
  12354. n = qMin(n, valueError.size());
  12355. QCPData newData;
  12356. for (int i=0; i<n; ++i)
  12357. {
  12358. newData.key = key[i];
  12359. newData.value = value[i];
  12360. newData.valueErrorMinus = valueError[i];
  12361. newData.valueErrorPlus = valueError[i];
  12362. mData->insertMulti(key[i], newData);
  12363. }
  12364. }
  12365. /*!
  12366. \overload
  12367. Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
  12368. negative value error of the data points are set to the values in \a valueErrorMinus, the positive
  12369. value error to \a valueErrorPlus.
  12370. For error bars to show appropriately, see \ref setErrorType.
  12371. The provided vectors should have equal length. Else, the number of added points will be the size of the
  12372. smallest vector.
  12373. */
  12374. void QCPGraph::setDataValueError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &valueErrorMinus, const QVector<double> &valueErrorPlus)
  12375. {
  12376. mData->clear();
  12377. int n = key.size();
  12378. n = qMin(n, value.size());
  12379. n = qMin(n, valueErrorMinus.size());
  12380. n = qMin(n, valueErrorPlus.size());
  12381. QCPData newData;
  12382. for (int i=0; i<n; ++i)
  12383. {
  12384. newData.key = key[i];
  12385. newData.value = value[i];
  12386. newData.valueErrorMinus = valueErrorMinus[i];
  12387. newData.valueErrorPlus = valueErrorPlus[i];
  12388. mData->insertMulti(key[i], newData);
  12389. }
  12390. }
  12391. /*!
  12392. Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
  12393. symmetrical key error of the data points are set to the values in \a keyError.
  12394. For error bars to show appropriately, see \ref setErrorType.
  12395. The provided vectors should have equal length. Else, the number of added points will be the size of the
  12396. smallest vector.
  12397. For asymmetrical errors (plus different from minus), see the overloaded version of this function.
  12398. */
  12399. void QCPGraph::setDataKeyError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyError)
  12400. {
  12401. mData->clear();
  12402. int n = key.size();
  12403. n = qMin(n, value.size());
  12404. n = qMin(n, keyError.size());
  12405. QCPData newData;
  12406. for (int i=0; i<n; ++i)
  12407. {
  12408. newData.key = key[i];
  12409. newData.value = value[i];
  12410. newData.keyErrorMinus = keyError[i];
  12411. newData.keyErrorPlus = keyError[i];
  12412. mData->insertMulti(key[i], newData);
  12413. }
  12414. }
  12415. /*!
  12416. \overload
  12417. Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
  12418. negative key error of the data points are set to the values in \a keyErrorMinus, the positive
  12419. key error to \a keyErrorPlus.
  12420. For error bars to show appropriately, see \ref setErrorType.
  12421. The provided vectors should have equal length. Else, the number of added points will be the size of the
  12422. smallest vector.
  12423. */
  12424. void QCPGraph::setDataKeyError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyErrorMinus, const QVector<double> &keyErrorPlus)
  12425. {
  12426. mData->clear();
  12427. int n = key.size();
  12428. n = qMin(n, value.size());
  12429. n = qMin(n, keyErrorMinus.size());
  12430. n = qMin(n, keyErrorPlus.size());
  12431. QCPData newData;
  12432. for (int i=0; i<n; ++i)
  12433. {
  12434. newData.key = key[i];
  12435. newData.value = value[i];
  12436. newData.keyErrorMinus = keyErrorMinus[i];
  12437. newData.keyErrorPlus = keyErrorPlus[i];
  12438. mData->insertMulti(key[i], newData);
  12439. }
  12440. }
  12441. /*!
  12442. Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
  12443. symmetrical key and value errors of the data points are set to the values in \a keyError and \a valueError.
  12444. For error bars to show appropriately, see \ref setErrorType.
  12445. The provided vectors should have equal length. Else, the number of added points will be the size of the
  12446. smallest vector.
  12447. For asymmetrical errors (plus different from minus), see the overloaded version of this function.
  12448. */
  12449. void QCPGraph::setDataBothError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyError, const QVector<double> &valueError)
  12450. {
  12451. mData->clear();
  12452. int n = key.size();
  12453. n = qMin(n, value.size());
  12454. n = qMin(n, valueError.size());
  12455. n = qMin(n, keyError.size());
  12456. QCPData newData;
  12457. for (int i=0; i<n; ++i)
  12458. {
  12459. newData.key = key[i];
  12460. newData.value = value[i];
  12461. newData.keyErrorMinus = keyError[i];
  12462. newData.keyErrorPlus = keyError[i];
  12463. newData.valueErrorMinus = valueError[i];
  12464. newData.valueErrorPlus = valueError[i];
  12465. mData->insertMulti(key[i], newData);
  12466. }
  12467. }
  12468. /*!
  12469. \overload
  12470. Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
  12471. negative key and value errors of the data points are set to the values in \a keyErrorMinus and \a valueErrorMinus. The positive
  12472. key and value errors are set to the values in \a keyErrorPlus \a valueErrorPlus.
  12473. For error bars to show appropriately, see \ref setErrorType.
  12474. The provided vectors should have equal length. Else, the number of added points will be the size of the
  12475. smallest vector.
  12476. */
  12477. void QCPGraph::setDataBothError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyErrorMinus, const QVector<double> &keyErrorPlus, const QVector<double> &valueErrorMinus, const QVector<double> &valueErrorPlus)
  12478. {
  12479. mData->clear();
  12480. int n = key.size();
  12481. n = qMin(n, value.size());
  12482. n = qMin(n, valueErrorMinus.size());
  12483. n = qMin(n, valueErrorPlus.size());
  12484. n = qMin(n, keyErrorMinus.size());
  12485. n = qMin(n, keyErrorPlus.size());
  12486. QCPData newData;
  12487. for (int i=0; i<n; ++i)
  12488. {
  12489. newData.key = key[i];
  12490. newData.value = value[i];
  12491. newData.keyErrorMinus = keyErrorMinus[i];
  12492. newData.keyErrorPlus = keyErrorPlus[i];
  12493. newData.valueErrorMinus = valueErrorMinus[i];
  12494. newData.valueErrorPlus = valueErrorPlus[i];
  12495. mData->insertMulti(key[i], newData);
  12496. }
  12497. }
  12498. /*!
  12499. Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
  12500. \ref lsNone and \ref setScatterStyle to the desired scatter style.
  12501. \see setScatterStyle
  12502. */
  12503. void QCPGraph::setLineStyle(LineStyle ls)
  12504. {
  12505. mLineStyle = ls;
  12506. }
  12507. /*!
  12508. Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points
  12509. are drawn (e.g. for line-only-plots with appropriate line style).
  12510. \see QCPScatterStyle, setLineStyle
  12511. */
  12512. void QCPGraph::setScatterStyle(const QCPScatterStyle &style)
  12513. {
  12514. mScatterStyle = style;
  12515. }
  12516. /*!
  12517. Sets which kind of error bars (Key Error, Value Error or both) should be drawn on each data
  12518. point. If you set \a errorType to something other than \ref etNone, make sure to actually pass
  12519. error data via the specific setData functions along with the data points (e.g. \ref
  12520. setDataValueError, \ref setDataKeyError, \ref setDataBothError).
  12521. \see ErrorType
  12522. */
  12523. void QCPGraph::setErrorType(ErrorType errorType)
  12524. {
  12525. mErrorType = errorType;
  12526. }
  12527. /*!
  12528. Sets the pen with which the error bars will be drawn.
  12529. \see setErrorBarSize, setErrorType
  12530. */
  12531. void QCPGraph::setErrorPen(const QPen &pen)
  12532. {
  12533. mErrorPen = pen;
  12534. }
  12535. /*!
  12536. Sets the width of the handles at both ends of an error bar in pixels.
  12537. */
  12538. void QCPGraph::setErrorBarSize(double size)
  12539. {
  12540. mErrorBarSize = size;
  12541. }
  12542. /*!
  12543. If \a enabled is set to true, the error bar will not be drawn as a solid line under the scatter symbol but
  12544. leave some free space around the symbol.
  12545. This feature uses the current scatter size (\ref QCPScatterStyle::setSize) to determine the size
  12546. of the area to leave blank. So when drawing Pixmaps as scatter points (\ref
  12547. QCPScatterStyle::ssPixmap), the scatter size must be set manually to a value corresponding to the
  12548. size of the Pixmap, if the error bars should leave gaps to its boundaries.
  12549. \ref setErrorType, setErrorBarSize, setScatterStyle
  12550. */
  12551. void QCPGraph::setErrorBarSkipSymbol(bool enabled)
  12552. {
  12553. mErrorBarSkipSymbol = enabled;
  12554. }
  12555. /*!
  12556. Sets the target graph for filling the area between this graph and \a targetGraph with the current
  12557. brush (\ref setBrush).
  12558. When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To
  12559. disable any filling, set the brush to Qt::NoBrush.
  12560. \see setBrush
  12561. */
  12562. void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph)
  12563. {
  12564. // prevent setting channel target to this graph itself:
  12565. if (targetGraph == this)
  12566. {
  12567. qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself";
  12568. mChannelFillGraph = 0;
  12569. return;
  12570. }
  12571. // prevent setting channel target to a graph not in the plot:
  12572. if (targetGraph && targetGraph->mParentPlot != mParentPlot)
  12573. {
  12574. qDebug() << Q_FUNC_INFO << "targetGraph not in same plot";
  12575. mChannelFillGraph = 0;
  12576. return;
  12577. }
  12578. mChannelFillGraph = targetGraph;
  12579. }
  12580. /*!
  12581. Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive
  12582. sampling technique can drastically improve the replot performance for graphs with a larger number
  12583. of points (e.g. above 10,000), without notably changing the appearance of the graph.
  12584. By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive
  12585. sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no
  12586. disadvantage in almost all cases.
  12587. \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling"
  12588. As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are
  12589. reproduced reliably, as well as the overall shape of the data set. The replot time reduces
  12590. dramatically though. This allows QCustomPlot to display large amounts of data in realtime.
  12591. \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling"
  12592. Care must be taken when using high-density scatter plots in combination with adaptive sampling.
  12593. The adaptive sampling algorithm treats scatter plots more carefully than line plots which still
  12594. gives a significant reduction of replot times, but not quite as much as for line plots. This is
  12595. because scatter plots inherently need more data points to be preserved in order to still resemble
  12596. the original, non-adaptive-sampling plot. As shown above, the results still aren't quite
  12597. identical, as banding occurs for the outer data points. This is in fact intentional, such that
  12598. the boundaries of the data cloud stay visible to the viewer. How strong the banding appears,
  12599. depends on the point density, i.e. the number of points in the plot.
  12600. For some situations with scatter plots it might thus be desirable to manually turn adaptive
  12601. sampling off. For example, when saving the plot to disk. This can be achieved by setting \a
  12602. enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled
  12603. back to true afterwards.
  12604. */
  12605. void QCPGraph::setAdaptiveSampling(bool enabled)
  12606. {
  12607. mAdaptiveSampling = enabled;
  12608. }
  12609. /*!
  12610. Adds the provided data points in \a dataMap to the current data.
  12611. Alternatively, you can also access and modify the graph's data via the \ref data method, which
  12612. returns a pointer to the internal \ref QCPDataMap.
  12613. \see removeData
  12614. */
  12615. void QCPGraph::addData(const QCPDataMap &dataMap)
  12616. {
  12617. mData->unite(dataMap);
  12618. }
  12619. /*! \overload
  12620. Adds the provided single data point in \a data to the current data.
  12621. Alternatively, you can also access and modify the graph's data via the \ref data method, which
  12622. returns a pointer to the internal \ref QCPDataMap.
  12623. \see removeData
  12624. */
  12625. void QCPGraph::addData(const QCPData &data)
  12626. {
  12627. mData->insertMulti(data.key, data);
  12628. }
  12629. /*! \overload
  12630. Adds the provided single data point as \a key and \a value pair to the current data.
  12631. Alternatively, you can also access and modify the graph's data via the \ref data method, which
  12632. returns a pointer to the internal \ref QCPDataMap.
  12633. \see removeData
  12634. */
  12635. void QCPGraph::addData(double key, double value)
  12636. {
  12637. QCPData newData;
  12638. newData.key = key;
  12639. newData.value = value;
  12640. mData->insertMulti(newData.key, newData);
  12641. }
  12642. /*! \overload
  12643. Adds the provided data points as \a key and \a value pairs to the current data.
  12644. Alternatively, you can also access and modify the graph's data via the \ref data method, which
  12645. returns a pointer to the internal \ref QCPDataMap.
  12646. \see removeData
  12647. */
  12648. void QCPGraph::addData(const QVector<double> &keys, const QVector<double> &values)
  12649. {
  12650. int n = qMin(keys.size(), values.size());
  12651. QCPData newData;
  12652. for (int i=0; i<n; ++i)
  12653. {
  12654. newData.key = keys[i];
  12655. newData.value = values[i];
  12656. mData->insertMulti(newData.key, newData);
  12657. }
  12658. }
  12659. /*!
  12660. Removes all data points with keys smaller than \a key.
  12661. \see addData, clearData
  12662. */
  12663. void QCPGraph::removeDataBefore(double key)
  12664. {
  12665. QCPDataMap::iterator it = mData->begin();
  12666. while (it != mData->end() && it.key() < key)
  12667. it = mData->erase(it);
  12668. }
  12669. /*!
  12670. Removes all data points with keys greater than \a key.
  12671. \see addData, clearData
  12672. */
  12673. void QCPGraph::removeDataAfter(double key)
  12674. {
  12675. if (mData->isEmpty()) return;
  12676. QCPDataMap::iterator it = mData->upperBound(key);
  12677. while (it != mData->end())
  12678. it = mData->erase(it);
  12679. }
  12680. /*!
  12681. Removes all data points with keys between \a fromKey and \a toKey.
  12682. if \a fromKey is greater or equal to \a toKey, the function does nothing. To remove
  12683. a single data point with known key, use \ref removeData(double key).
  12684. \see addData, clearData
  12685. */
  12686. void QCPGraph::removeData(double fromKey, double toKey)
  12687. {
  12688. if (fromKey >= toKey || mData->isEmpty()) return;
  12689. QCPDataMap::iterator it = mData->upperBound(fromKey);
  12690. QCPDataMap::iterator itEnd = mData->upperBound(toKey);
  12691. while (it != itEnd)
  12692. it = mData->erase(it);
  12693. }
  12694. /*! \overload
  12695. Removes a single data point at \a key. If the position is not known with absolute precision,
  12696. consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval around
  12697. the suspected position, depeding on the precision with which the key is known.
  12698. \see addData, clearData
  12699. */
  12700. void QCPGraph::removeData(double key)
  12701. {
  12702. mData->remove(key);
  12703. }
  12704. /*!
  12705. Removes all data points.
  12706. \see removeData, removeDataAfter, removeDataBefore
  12707. */
  12708. void QCPGraph::clearData()
  12709. {
  12710. mData->clear();
  12711. }
  12712. /* inherits documentation from base class */
  12713. double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  12714. {
  12715. Q_UNUSED(details)
  12716. if ((onlySelectable && !mSelectable) || mData->isEmpty())
  12717. return -1;
  12718. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  12719. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
  12720. return pointDistance(pos);
  12721. else
  12722. return -1;
  12723. }
  12724. /*! \overload
  12725. Allows to define whether error bars are taken into consideration when determining the new axis
  12726. range.
  12727. \see rescaleKeyAxis, rescaleValueAxis, QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
  12728. */
  12729. void QCPGraph::rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const
  12730. {
  12731. rescaleKeyAxis(onlyEnlarge, includeErrorBars);
  12732. rescaleValueAxis(onlyEnlarge, includeErrorBars);
  12733. }
  12734. /*! \overload
  12735. Allows to define whether error bars (of kind \ref QCPGraph::etKey) are taken into consideration
  12736. when determining the new axis range.
  12737. \see rescaleAxes, QCPAbstractPlottable::rescaleKeyAxis
  12738. */
  12739. void QCPGraph::rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const
  12740. {
  12741. // this code is a copy of QCPAbstractPlottable::rescaleKeyAxis with the only change
  12742. // that getKeyRange is passed the includeErrorBars value.
  12743. if (mData->isEmpty()) return;
  12744. QCPAxis *keyAxis = mKeyAxis.data();
  12745. if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
  12746. SignDomain signDomain = sdBoth;
  12747. if (keyAxis->scaleType() == QCPAxis::stLogarithmic)
  12748. signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive);
  12749. bool foundRange;
  12750. QCPRange newRange = getKeyRange(foundRange, signDomain, includeErrorBars);
  12751. if (foundRange)
  12752. {
  12753. if (onlyEnlarge)
  12754. {
  12755. if (keyAxis->range().lower < newRange.lower)
  12756. newRange.lower = keyAxis->range().lower;
  12757. if (keyAxis->range().upper > newRange.upper)
  12758. newRange.upper = keyAxis->range().upper;
  12759. }
  12760. keyAxis->setRange(newRange);
  12761. }
  12762. }
  12763. /*! \overload
  12764. Allows to define whether error bars (of kind \ref QCPGraph::etValue) are taken into consideration
  12765. when determining the new axis range.
  12766. \see rescaleAxes, QCPAbstractPlottable::rescaleValueAxis
  12767. */
  12768. void QCPGraph::rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const
  12769. {
  12770. // this code is a copy of QCPAbstractPlottable::rescaleValueAxis with the only change
  12771. // is that getValueRange is passed the includeErrorBars value.
  12772. if (mData->isEmpty()) return;
  12773. QCPAxis *valueAxis = mValueAxis.data();
  12774. if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; }
  12775. SignDomain signDomain = sdBoth;
  12776. if (valueAxis->scaleType() == QCPAxis::stLogarithmic)
  12777. signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive);
  12778. bool foundRange;
  12779. QCPRange newRange = getValueRange(foundRange, signDomain, includeErrorBars);
  12780. if (foundRange)
  12781. {
  12782. if (onlyEnlarge)
  12783. {
  12784. if (valueAxis->range().lower < newRange.lower)
  12785. newRange.lower = valueAxis->range().lower;
  12786. if (valueAxis->range().upper > newRange.upper)
  12787. newRange.upper = valueAxis->range().upper;
  12788. }
  12789. valueAxis->setRange(newRange);
  12790. }
  12791. }
  12792. /* inherits documentation from base class */
  12793. void QCPGraph::draw(QCPPainter *painter)
  12794. {
  12795. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  12796. if (mKeyAxis.data()->range().size() <= 0 || mData->isEmpty()) return;
  12797. if (mLineStyle == lsNone && mScatterStyle.isNone()) return;
  12798. // allocate line and (if necessary) point vectors:
  12799. QVector<QPointF> *lineData = new QVector<QPointF>;
  12800. QVector<QCPData> *scatterData = 0;
  12801. if (!mScatterStyle.isNone())
  12802. scatterData = new QVector<QCPData>;
  12803. // fill vectors with data appropriate to plot style:
  12804. getPlotData(lineData, scatterData);
  12805. // check data validity if flag set:
  12806. #ifdef QCUSTOMPLOT_CHECK_DATA
  12807. QCPDataMap::const_iterator it;
  12808. for (it = mData->constBegin(); it != mData->constEnd(); ++it)
  12809. {
  12810. if (QCP::isInvalidData(it.value().key, it.value().value) ||
  12811. QCP::isInvalidData(it.value().keyErrorPlus, it.value().keyErrorMinus) ||
  12812. QCP::isInvalidData(it.value().valueErrorPlus, it.value().valueErrorPlus))
  12813. qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name();
  12814. }
  12815. #endif
  12816. // draw fill of graph:
  12817. drawFill(painter, lineData);
  12818. // draw line:
  12819. if (mLineStyle == lsImpulse)
  12820. drawImpulsePlot(painter, lineData);
  12821. else if (mLineStyle != lsNone)
  12822. drawLinePlot(painter, lineData); // also step plots can be drawn as a line plot
  12823. // draw scatters:
  12824. if (scatterData)
  12825. drawScatterPlot(painter, scatterData);
  12826. // free allocated line and point vectors:
  12827. delete lineData;
  12828. if (scatterData)
  12829. delete scatterData;
  12830. }
  12831. /* inherits documentation from base class */
  12832. void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  12833. {
  12834. // draw fill:
  12835. if (mBrush.style() != Qt::NoBrush)
  12836. {
  12837. applyFillAntialiasingHint(painter);
  12838. painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
  12839. }
  12840. // draw line vertically centered:
  12841. if (mLineStyle != lsNone)
  12842. {
  12843. applyDefaultAntialiasingHint(painter);
  12844. painter->setPen(mPen);
  12845. 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
  12846. }
  12847. // draw scatter symbol:
  12848. if (!mScatterStyle.isNone())
  12849. {
  12850. applyScattersAntialiasingHint(painter);
  12851. // scale scatter pixmap if it's too large to fit in legend icon rect:
  12852. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
  12853. {
  12854. QCPScatterStyle scaledStyle(mScatterStyle);
  12855. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  12856. scaledStyle.applyTo(painter, mPen);
  12857. scaledStyle.drawShape(painter, QRectF(rect).center());
  12858. } else
  12859. {
  12860. mScatterStyle.applyTo(painter, mPen);
  12861. mScatterStyle.drawShape(painter, QRectF(rect).center());
  12862. }
  12863. }
  12864. }
  12865. /*! \internal
  12866. This function branches out to the line style specific "get(...)PlotData" functions, according to
  12867. the line style of the graph.
  12868. \a lineData will be filled with raw points that will be drawn with the according draw functions,
  12869. e.g. \ref drawLinePlot and \ref drawImpulsePlot. These aren't necessarily the original data
  12870. points, since for step plots for example, additional points are needed for drawing lines that
  12871. make up steps. If the line style of the graph is \ref lsNone, the \a lineData vector will be left
  12872. untouched.
  12873. \a scatterData will be filled with the original data points so \ref drawScatterPlot can draw the
  12874. scatter symbols accordingly. If no scatters need to be drawn, i.e. the scatter style's shape is
  12875. \ref QCPScatterStyle::ssNone, pass 0 as \a scatterData, and this step will be skipped.
  12876. \see getScatterPlotData, getLinePlotData, getStepLeftPlotData, getStepRightPlotData,
  12877. getStepCenterPlotData, getImpulsePlotData
  12878. */
  12879. void QCPGraph::getPlotData(QVector<QPointF> *lineData, QVector<QCPData> *scatterData) const
  12880. {
  12881. switch(mLineStyle)
  12882. {
  12883. case lsNone: getScatterPlotData(scatterData); break;
  12884. case lsLine: getLinePlotData(lineData, scatterData); break;
  12885. case lsStepLeft: getStepLeftPlotData(lineData, scatterData); break;
  12886. case lsStepRight: getStepRightPlotData(lineData, scatterData); break;
  12887. case lsStepCenter: getStepCenterPlotData(lineData, scatterData); break;
  12888. case lsImpulse: getImpulsePlotData(lineData, scatterData); break;
  12889. }
  12890. }
  12891. /*! \internal
  12892. If line style is \ref lsNone and the scatter style's shape is not \ref QCPScatterStyle::ssNone,
  12893. this function serves at providing the visible data points in \a scatterData, so the \ref
  12894. drawScatterPlot function can draw the scatter points accordingly.
  12895. If line style is not \ref lsNone, this function is not called and the data for the scatter points
  12896. are (if needed) calculated inside the corresponding other "get(...)PlotData" functions.
  12897. \see drawScatterPlot
  12898. */
  12899. void QCPGraph::getScatterPlotData(QVector<QCPData> *scatterData) const
  12900. {
  12901. getPreparedData(0, scatterData);
  12902. }
  12903. /*! \internal
  12904. Places the raw data points needed for a normal linearly connected graph in \a linePixelData.
  12905. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
  12906. points that are visible for drawing scatter points, if necessary. If drawing scatter points is
  12907. disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
  12908. scatterData, and the function will skip filling the vector.
  12909. \see drawLinePlot
  12910. */
  12911. void QCPGraph::getLinePlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
  12912. {
  12913. QCPAxis *keyAxis = mKeyAxis.data();
  12914. QCPAxis *valueAxis = mValueAxis.data();
  12915. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  12916. if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; }
  12917. QVector<QCPData> lineData;
  12918. getPreparedData(&lineData, scatterData);
  12919. linePixelData->reserve(lineData.size()+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
  12920. linePixelData->resize(lineData.size());
  12921. // transform lineData points to pixels:
  12922. if (keyAxis->orientation() == Qt::Vertical)
  12923. {
  12924. for (int i=0; i<lineData.size(); ++i)
  12925. {
  12926. (*linePixelData)[i].setX(valueAxis->coordToPixel(lineData.at(i).value));
  12927. (*linePixelData)[i].setY(keyAxis->coordToPixel(lineData.at(i).key));
  12928. }
  12929. } else // key axis is horizontal
  12930. {
  12931. for (int i=0; i<lineData.size(); ++i)
  12932. {
  12933. (*linePixelData)[i].setX(keyAxis->coordToPixel(lineData.at(i).key));
  12934. (*linePixelData)[i].setY(valueAxis->coordToPixel(lineData.at(i).value));
  12935. }
  12936. }
  12937. }
  12938. /*!
  12939. \internal
  12940. Places the raw data points needed for a step plot with left oriented steps in \a lineData.
  12941. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
  12942. points that are visible for drawing scatter points, if necessary. If drawing scatter points is
  12943. disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
  12944. scatterData, and the function will skip filling the vector.
  12945. \see drawLinePlot
  12946. */
  12947. void QCPGraph::getStepLeftPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
  12948. {
  12949. QCPAxis *keyAxis = mKeyAxis.data();
  12950. QCPAxis *valueAxis = mValueAxis.data();
  12951. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  12952. if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; }
  12953. QVector<QCPData> lineData;
  12954. getPreparedData(&lineData, scatterData);
  12955. linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
  12956. linePixelData->resize(lineData.size()*2);
  12957. // calculate steps from lineData and transform to pixel coordinates:
  12958. if (keyAxis->orientation() == Qt::Vertical)
  12959. {
  12960. double lastValue = valueAxis->coordToPixel(lineData.first().value);
  12961. double key;
  12962. for (int i=0; i<lineData.size(); ++i)
  12963. {
  12964. key = keyAxis->coordToPixel(lineData.at(i).key);
  12965. (*linePixelData)[i*2+0].setX(lastValue);
  12966. (*linePixelData)[i*2+0].setY(key);
  12967. lastValue = valueAxis->coordToPixel(lineData.at(i).value);
  12968. (*linePixelData)[i*2+1].setX(lastValue);
  12969. (*linePixelData)[i*2+1].setY(key);
  12970. }
  12971. } else // key axis is horizontal
  12972. {
  12973. double lastValue = valueAxis->coordToPixel(lineData.first().value);
  12974. double key;
  12975. for (int i=0; i<lineData.size(); ++i)
  12976. {
  12977. key = keyAxis->coordToPixel(lineData.at(i).key);
  12978. (*linePixelData)[i*2+0].setX(key);
  12979. (*linePixelData)[i*2+0].setY(lastValue);
  12980. lastValue = valueAxis->coordToPixel(lineData.at(i).value);
  12981. (*linePixelData)[i*2+1].setX(key);
  12982. (*linePixelData)[i*2+1].setY(lastValue);
  12983. }
  12984. }
  12985. }
  12986. /*!
  12987. \internal
  12988. Places the raw data points needed for a step plot with right oriented steps in \a lineData.
  12989. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
  12990. points that are visible for drawing scatter points, if necessary. If drawing scatter points is
  12991. disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
  12992. scatterData, and the function will skip filling the vector.
  12993. \see drawLinePlot
  12994. */
  12995. void QCPGraph::getStepRightPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
  12996. {
  12997. QCPAxis *keyAxis = mKeyAxis.data();
  12998. QCPAxis *valueAxis = mValueAxis.data();
  12999. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  13000. if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; }
  13001. QVector<QCPData> lineData;
  13002. getPreparedData(&lineData, scatterData);
  13003. linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
  13004. linePixelData->resize(lineData.size()*2);
  13005. // calculate steps from lineData and transform to pixel coordinates:
  13006. if (keyAxis->orientation() == Qt::Vertical)
  13007. {
  13008. double lastKey = keyAxis->coordToPixel(lineData.first().key);
  13009. double value;
  13010. for (int i=0; i<lineData.size(); ++i)
  13011. {
  13012. value = valueAxis->coordToPixel(lineData.at(i).value);
  13013. (*linePixelData)[i*2+0].setX(value);
  13014. (*linePixelData)[i*2+0].setY(lastKey);
  13015. lastKey = keyAxis->coordToPixel(lineData.at(i).key);
  13016. (*linePixelData)[i*2+1].setX(value);
  13017. (*linePixelData)[i*2+1].setY(lastKey);
  13018. }
  13019. } else // key axis is horizontal
  13020. {
  13021. double lastKey = keyAxis->coordToPixel(lineData.first().key);
  13022. double value;
  13023. for (int i=0; i<lineData.size(); ++i)
  13024. {
  13025. value = valueAxis->coordToPixel(lineData.at(i).value);
  13026. (*linePixelData)[i*2+0].setX(lastKey);
  13027. (*linePixelData)[i*2+0].setY(value);
  13028. lastKey = keyAxis->coordToPixel(lineData.at(i).key);
  13029. (*linePixelData)[i*2+1].setX(lastKey);
  13030. (*linePixelData)[i*2+1].setY(value);
  13031. }
  13032. }
  13033. }
  13034. /*!
  13035. \internal
  13036. Places the raw data points needed for a step plot with centered steps in \a lineData.
  13037. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
  13038. points that are visible for drawing scatter points, if necessary. If drawing scatter points is
  13039. disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
  13040. scatterData, and the function will skip filling the vector.
  13041. \see drawLinePlot
  13042. */
  13043. void QCPGraph::getStepCenterPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
  13044. {
  13045. QCPAxis *keyAxis = mKeyAxis.data();
  13046. QCPAxis *valueAxis = mValueAxis.data();
  13047. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  13048. if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; }
  13049. QVector<QCPData> lineData;
  13050. getPreparedData(&lineData, scatterData);
  13051. linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
  13052. linePixelData->resize(lineData.size()*2);
  13053. // calculate steps from lineData and transform to pixel coordinates:
  13054. if (keyAxis->orientation() == Qt::Vertical)
  13055. {
  13056. double lastKey = keyAxis->coordToPixel(lineData.first().key);
  13057. double lastValue = valueAxis->coordToPixel(lineData.first().value);
  13058. double key;
  13059. (*linePixelData)[0].setX(lastValue);
  13060. (*linePixelData)[0].setY(lastKey);
  13061. for (int i=1; i<lineData.size(); ++i)
  13062. {
  13063. key = (keyAxis->coordToPixel(lineData.at(i).key)+lastKey)*0.5;
  13064. (*linePixelData)[i*2-1].setX(lastValue);
  13065. (*linePixelData)[i*2-1].setY(key);
  13066. lastValue = valueAxis->coordToPixel(lineData.at(i).value);
  13067. lastKey = keyAxis->coordToPixel(lineData.at(i).key);
  13068. (*linePixelData)[i*2+0].setX(lastValue);
  13069. (*linePixelData)[i*2+0].setY(key);
  13070. }
  13071. (*linePixelData)[lineData.size()*2-1].setX(lastValue);
  13072. (*linePixelData)[lineData.size()*2-1].setY(lastKey);
  13073. } else // key axis is horizontal
  13074. {
  13075. double lastKey = keyAxis->coordToPixel(lineData.first().key);
  13076. double lastValue = valueAxis->coordToPixel(lineData.first().value);
  13077. double key;
  13078. (*linePixelData)[0].setX(lastKey);
  13079. (*linePixelData)[0].setY(lastValue);
  13080. for (int i=1; i<lineData.size(); ++i)
  13081. {
  13082. key = (keyAxis->coordToPixel(lineData.at(i).key)+lastKey)*0.5;
  13083. (*linePixelData)[i*2-1].setX(key);
  13084. (*linePixelData)[i*2-1].setY(lastValue);
  13085. lastValue = valueAxis->coordToPixel(lineData.at(i).value);
  13086. lastKey = keyAxis->coordToPixel(lineData.at(i).key);
  13087. (*linePixelData)[i*2+0].setX(key);
  13088. (*linePixelData)[i*2+0].setY(lastValue);
  13089. }
  13090. (*linePixelData)[lineData.size()*2-1].setX(lastKey);
  13091. (*linePixelData)[lineData.size()*2-1].setY(lastValue);
  13092. }
  13093. }
  13094. /*!
  13095. \internal
  13096. Places the raw data points needed for an impulse plot in \a lineData.
  13097. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
  13098. points that are visible for drawing scatter points, if necessary. If drawing scatter points is
  13099. disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
  13100. scatterData, and the function will skip filling the vector.
  13101. \see drawImpulsePlot
  13102. */
  13103. void QCPGraph::getImpulsePlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
  13104. {
  13105. QCPAxis *keyAxis = mKeyAxis.data();
  13106. QCPAxis *valueAxis = mValueAxis.data();
  13107. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  13108. if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; }
  13109. QVector<QCPData> lineData;
  13110. getPreparedData(&lineData, scatterData);
  13111. linePixelData->resize(lineData.size()*2); // no need to reserve 2 extra points because impulse plot has no fill
  13112. // transform lineData points to pixels:
  13113. if (keyAxis->orientation() == Qt::Vertical)
  13114. {
  13115. double zeroPointX = valueAxis->coordToPixel(0);
  13116. double key;
  13117. for (int i=0; i<lineData.size(); ++i)
  13118. {
  13119. key = keyAxis->coordToPixel(lineData.at(i).key);
  13120. (*linePixelData)[i*2+0].setX(zeroPointX);
  13121. (*linePixelData)[i*2+0].setY(key);
  13122. (*linePixelData)[i*2+1].setX(valueAxis->coordToPixel(lineData.at(i).value));
  13123. (*linePixelData)[i*2+1].setY(key);
  13124. }
  13125. } else // key axis is horizontal
  13126. {
  13127. double zeroPointY = valueAxis->coordToPixel(0);
  13128. double key;
  13129. for (int i=0; i<lineData.size(); ++i)
  13130. {
  13131. key = keyAxis->coordToPixel(lineData.at(i).key);
  13132. (*linePixelData)[i*2+0].setX(key);
  13133. (*linePixelData)[i*2+0].setY(zeroPointY);
  13134. (*linePixelData)[i*2+1].setX(key);
  13135. (*linePixelData)[i*2+1].setY(valueAxis->coordToPixel(lineData.at(i).value));
  13136. }
  13137. }
  13138. }
  13139. /*! \internal
  13140. Draws the fill of the graph with the specified brush.
  13141. If the fill is a normal fill towards the zero-value-line, only the \a lineData is required (and
  13142. two extra points at the zero-value-line, which are added by \ref addFillBasePoints and removed by
  13143. \ref removeFillBasePoints after the fill drawing is done).
  13144. If the fill is a channel fill between this QCPGraph and another QCPGraph (mChannelFillGraph), the
  13145. more complex polygon is calculated with the \ref getChannelFillPolygon function.
  13146. \see drawLinePlot
  13147. */
  13148. void QCPGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lineData) const
  13149. {
  13150. if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot
  13151. if (mainBrush().style() == Qt::NoBrush || mainBrush().color().alpha() == 0) return;
  13152. applyFillAntialiasingHint(painter);
  13153. if (!mChannelFillGraph)
  13154. {
  13155. // draw base fill under graph, fill goes all the way to the zero-value-line:
  13156. addFillBasePoints(lineData);
  13157. painter->setPen(Qt::NoPen);
  13158. painter->setBrush(mainBrush());
  13159. painter->drawPolygon(QPolygonF(*lineData));
  13160. removeFillBasePoints(lineData);
  13161. } else
  13162. {
  13163. // draw channel fill between this graph and mChannelFillGraph:
  13164. painter->setPen(Qt::NoPen);
  13165. painter->setBrush(mainBrush());
  13166. painter->drawPolygon(getChannelFillPolygon(lineData));
  13167. }
  13168. }
  13169. /*! \internal
  13170. Draws scatter symbols at every data point passed in \a scatterData. scatter symbols are independent
  13171. of the line style and are always drawn if the scatter style's shape is not \ref
  13172. QCPScatterStyle::ssNone. Hence, the \a scatterData vector is outputted by all "get(...)PlotData"
  13173. functions, together with the (line style dependent) line data.
  13174. \see drawLinePlot, drawImpulsePlot
  13175. */
  13176. void QCPGraph::drawScatterPlot(QCPPainter *painter, QVector<QCPData> *scatterData) const
  13177. {
  13178. QCPAxis *keyAxis = mKeyAxis.data();
  13179. QCPAxis *valueAxis = mValueAxis.data();
  13180. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  13181. // draw error bars:
  13182. if (mErrorType != etNone)
  13183. {
  13184. applyErrorBarsAntialiasingHint(painter);
  13185. painter->setPen(mErrorPen);
  13186. if (keyAxis->orientation() == Qt::Vertical)
  13187. {
  13188. for (int i=0; i<scatterData->size(); ++i)
  13189. drawError(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key), scatterData->at(i));
  13190. } else
  13191. {
  13192. for (int i=0; i<scatterData->size(); ++i)
  13193. drawError(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value), scatterData->at(i));
  13194. }
  13195. }
  13196. // draw scatter point symbols:
  13197. applyScattersAntialiasingHint(painter);
  13198. mScatterStyle.applyTo(painter, mPen);
  13199. if (keyAxis->orientation() == Qt::Vertical)
  13200. {
  13201. for (int i=0; i<scatterData->size(); ++i)
  13202. mScatterStyle.drawShape(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key));
  13203. } else
  13204. {
  13205. for (int i=0; i<scatterData->size(); ++i)
  13206. mScatterStyle.drawShape(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value));
  13207. }
  13208. }
  13209. /*! \internal
  13210. Draws line graphs from the provided data. It connects all points in \a lineData, which was
  13211. created by one of the "get(...)PlotData" functions for line styles that require simple line
  13212. connections between the point vector they create. These are for example \ref getLinePlotData,
  13213. \ref getStepLeftPlotData, \ref getStepRightPlotData and \ref getStepCenterPlotData.
  13214. \see drawScatterPlot, drawImpulsePlot
  13215. */
  13216. void QCPGraph::drawLinePlot(QCPPainter *painter, QVector<QPointF> *lineData) const
  13217. {
  13218. // draw line of graph:
  13219. if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)
  13220. {
  13221. applyDefaultAntialiasingHint(painter);
  13222. painter->setPen(mainPen());
  13223. painter->setBrush(Qt::NoBrush);
  13224. /* Draws polyline in batches, currently not used:
  13225. int p = 0;
  13226. while (p < lineData->size())
  13227. {
  13228. int batch = qMin(25, lineData->size()-p);
  13229. if (p != 0)
  13230. {
  13231. ++batch;
  13232. --p; // to draw the connection lines between two batches
  13233. }
  13234. painter->drawPolyline(lineData->constData()+p, batch);
  13235. p += batch;
  13236. }
  13237. */
  13238. // if drawing solid line and not in PDF, use much faster line drawing instead of polyline:
  13239. if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) &&
  13240. painter->pen().style() == Qt::SolidLine &&
  13241. !painter->modes().testFlag(QCPPainter::pmVectorized)&&
  13242. !painter->modes().testFlag(QCPPainter::pmNoCaching))
  13243. {
  13244. for (int i=1; i<lineData->size(); ++i)
  13245. painter->drawLine(lineData->at(i-1), lineData->at(i));
  13246. } else
  13247. {
  13248. painter->drawPolyline(QPolygonF(*lineData));
  13249. }
  13250. }
  13251. }
  13252. /*! \internal
  13253. Draws impulses from the provided data, i.e. it connects all line pairs in \a lineData, which was
  13254. created by \ref getImpulsePlotData.
  13255. \see drawScatterPlot, drawLinePlot
  13256. */
  13257. void QCPGraph::drawImpulsePlot(QCPPainter *painter, QVector<QPointF> *lineData) const
  13258. {
  13259. // draw impulses:
  13260. if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)
  13261. {
  13262. applyDefaultAntialiasingHint(painter);
  13263. QPen pen = mainPen();
  13264. pen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line
  13265. painter->setPen(pen);
  13266. painter->setBrush(Qt::NoBrush);
  13267. painter->drawLines(*lineData);
  13268. }
  13269. }
  13270. /*! \internal
  13271. Returns the \a lineData and \a scatterData that need to be plotted for this graph taking into
  13272. consideration the current axis ranges and, if \ref setAdaptiveSampling is enabled, local point
  13273. densities.
  13274. 0 may be passed as \a lineData or \a scatterData to indicate that the respective dataset isn't
  13275. needed. For example, if the scatter style (\ref setScatterStyle) is \ref QCPScatterStyle::ssNone, \a
  13276. scatterData should be 0 to prevent unnecessary calculations.
  13277. This method is used by the various "get(...)PlotData" methods to get the basic working set of data.
  13278. */
  13279. void QCPGraph::getPreparedData(QVector<QCPData> *lineData, QVector<QCPData> *scatterData) const
  13280. {
  13281. QCPAxis *keyAxis = mKeyAxis.data();
  13282. QCPAxis *valueAxis = mValueAxis.data();
  13283. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  13284. // get visible data range:
  13285. QCPDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point
  13286. getVisibleDataBounds(lower, upper);
  13287. if (lower == mData->constEnd() || upper == mData->constEnd())
  13288. return;
  13289. // count points in visible range, taking into account that we only need to count to the limit maxCount if using adaptive sampling:
  13290. int maxCount = std::numeric_limits<int>::max();
  13291. if (mAdaptiveSampling)
  13292. {
  13293. int keyPixelSpan = qAbs(keyAxis->coordToPixel(lower.key())-keyAxis->coordToPixel(upper.key()));
  13294. maxCount = 2*keyPixelSpan+2;
  13295. }
  13296. int dataCount = countDataInBounds(lower, upper, maxCount);
  13297. if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
  13298. {
  13299. if (lineData)
  13300. {
  13301. QCPDataMap::const_iterator it = lower;
  13302. QCPDataMap::const_iterator upperEnd = upper+1;
  13303. double minValue = it.value().value;
  13304. double maxValue = it.value().value;
  13305. QCPDataMap::const_iterator currentIntervalFirstPoint = it;
  13306. int reversedFactor = keyAxis->rangeReversed() ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction
  13307. int reversedRound = keyAxis->rangeReversed() ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
  13308. double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound));
  13309. double lastIntervalEndKey = currentIntervalStartKey;
  13310. double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
  13311. bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
  13312. int intervalDataCount = 1;
  13313. ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect
  13314. while (it != upperEnd)
  13315. {
  13316. if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary
  13317. {
  13318. if (it.value().value < minValue)
  13319. minValue = it.value().value;
  13320. else if (it.value().value > maxValue)
  13321. maxValue = it.value().value;
  13322. ++intervalDataCount;
  13323. } else // new pixel interval started
  13324. {
  13325. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
  13326. {
  13327. if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point
  13328. lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value));
  13329. lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
  13330. lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
  13331. 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
  13332. lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.8, (it-1).value().value));
  13333. } else
  13334. lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value));
  13335. lastIntervalEndKey = (it-1).value().key;
  13336. minValue = it.value().value;
  13337. maxValue = it.value().value;
  13338. currentIntervalFirstPoint = it;
  13339. currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound));
  13340. if (keyEpsilonVariable)
  13341. keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
  13342. intervalDataCount = 1;
  13343. }
  13344. ++it;
  13345. }
  13346. // handle last interval:
  13347. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
  13348. {
  13349. if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point
  13350. lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value));
  13351. lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
  13352. lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
  13353. } else
  13354. lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value));
  13355. }
  13356. if (scatterData)
  13357. {
  13358. double valueMaxRange = valueAxis->range().upper;
  13359. double valueMinRange = valueAxis->range().lower;
  13360. QCPDataMap::const_iterator it = lower;
  13361. QCPDataMap::const_iterator upperEnd = upper+1;
  13362. double minValue = it.value().value;
  13363. double maxValue = it.value().value;
  13364. QCPDataMap::const_iterator minValueIt = it;
  13365. QCPDataMap::const_iterator maxValueIt = it;
  13366. QCPDataMap::const_iterator currentIntervalStart = it;
  13367. int reversedFactor = keyAxis->rangeReversed() ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction
  13368. int reversedRound = keyAxis->rangeReversed() ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
  13369. double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound));
  13370. double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
  13371. bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
  13372. int intervalDataCount = 1;
  13373. ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect
  13374. while (it != upperEnd)
  13375. {
  13376. if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary
  13377. {
  13378. if (it.value().value < minValue && it.value().value > valueMinRange && it.value().value < valueMaxRange)
  13379. {
  13380. minValue = it.value().value;
  13381. minValueIt = it;
  13382. } else if (it.value().value > maxValue && it.value().value > valueMinRange && it.value().value < valueMaxRange)
  13383. {
  13384. maxValue = it.value().value;
  13385. maxValueIt = it;
  13386. }
  13387. ++intervalDataCount;
  13388. } else // new pixel started
  13389. {
  13390. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
  13391. {
  13392. // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
  13393. double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
  13394. int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
  13395. QCPDataMap::const_iterator intervalIt = currentIntervalStart;
  13396. int c = 0;
  13397. while (intervalIt != it)
  13398. {
  13399. if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange)
  13400. scatterData->append(intervalIt.value());
  13401. ++c;
  13402. ++intervalIt;
  13403. }
  13404. } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange)
  13405. scatterData->append(currentIntervalStart.value());
  13406. minValue = it.value().value;
  13407. maxValue = it.value().value;
  13408. currentIntervalStart = it;
  13409. currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound));
  13410. if (keyEpsilonVariable)
  13411. keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
  13412. intervalDataCount = 1;
  13413. }
  13414. ++it;
  13415. }
  13416. // handle last interval:
  13417. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
  13418. {
  13419. // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
  13420. double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
  13421. int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
  13422. QCPDataMap::const_iterator intervalIt = currentIntervalStart;
  13423. int c = 0;
  13424. while (intervalIt != it)
  13425. {
  13426. if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange)
  13427. scatterData->append(intervalIt.value());
  13428. ++c;
  13429. ++intervalIt;
  13430. }
  13431. } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange)
  13432. scatterData->append(currentIntervalStart.value());
  13433. }
  13434. } else // don't use adaptive sampling algorithm, transfer points one-to-one from the map into the output parameters
  13435. {
  13436. QVector<QCPData> *dataVector = 0;
  13437. if (lineData)
  13438. dataVector = lineData;
  13439. else if (scatterData)
  13440. dataVector = scatterData;
  13441. if (dataVector)
  13442. {
  13443. QCPDataMap::const_iterator it = lower;
  13444. QCPDataMap::const_iterator upperEnd = upper+1;
  13445. dataVector->reserve(dataCount+2); // +2 for possible fill end points
  13446. while (it != upperEnd)
  13447. {
  13448. dataVector->append(it.value());
  13449. ++it;
  13450. }
  13451. }
  13452. if (lineData && scatterData)
  13453. *scatterData = *dataVector;
  13454. }
  13455. }
  13456. /*! \internal
  13457. called by the scatter drawing function (\ref drawScatterPlot) to draw the error bars on one data
  13458. point. \a x and \a y pixel positions of the data point are passed since they are already known in
  13459. pixel coordinates in the drawing function, so we save some extra coordToPixel transforms here. \a
  13460. data is therefore only used for the errors, not key and value.
  13461. */
  13462. void QCPGraph::drawError(QCPPainter *painter, double x, double y, const QCPData &data) const
  13463. {
  13464. QCPAxis *keyAxis = mKeyAxis.data();
  13465. QCPAxis *valueAxis = mValueAxis.data();
  13466. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  13467. double a, b; // positions of error bar bounds in pixels
  13468. double barWidthHalf = mErrorBarSize*0.5;
  13469. double skipSymbolMargin = mScatterStyle.size(); // pixels left blank per side, when mErrorBarSkipSymbol is true
  13470. if (keyAxis->orientation() == Qt::Vertical)
  13471. {
  13472. // draw key error vertically and value error horizontally
  13473. if (mErrorType == etKey || mErrorType == etBoth)
  13474. {
  13475. a = keyAxis->coordToPixel(data.key-data.keyErrorMinus);
  13476. b = keyAxis->coordToPixel(data.key+data.keyErrorPlus);
  13477. if (keyAxis->rangeReversed())
  13478. qSwap(a,b);
  13479. // draw spine:
  13480. if (mErrorBarSkipSymbol)
  13481. {
  13482. if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
  13483. painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin));
  13484. if (y-b > skipSymbolMargin)
  13485. painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b));
  13486. } else
  13487. painter->drawLine(QLineF(x, a, x, b));
  13488. // draw handles:
  13489. painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a));
  13490. painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b));
  13491. }
  13492. if (mErrorType == etValue || mErrorType == etBoth)
  13493. {
  13494. a = valueAxis->coordToPixel(data.value-data.valueErrorMinus);
  13495. b = valueAxis->coordToPixel(data.value+data.valueErrorPlus);
  13496. if (valueAxis->rangeReversed())
  13497. qSwap(a,b);
  13498. // draw spine:
  13499. if (mErrorBarSkipSymbol)
  13500. {
  13501. if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
  13502. painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y));
  13503. if (b-x > skipSymbolMargin)
  13504. painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y));
  13505. } else
  13506. painter->drawLine(QLineF(a, y, b, y));
  13507. // draw handles:
  13508. painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf));
  13509. painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf));
  13510. }
  13511. } else // mKeyAxis->orientation() is Qt::Horizontal
  13512. {
  13513. // draw value error vertically and key error horizontally
  13514. if (mErrorType == etKey || mErrorType == etBoth)
  13515. {
  13516. a = keyAxis->coordToPixel(data.key-data.keyErrorMinus);
  13517. b = keyAxis->coordToPixel(data.key+data.keyErrorPlus);
  13518. if (keyAxis->rangeReversed())
  13519. qSwap(a,b);
  13520. // draw spine:
  13521. if (mErrorBarSkipSymbol)
  13522. {
  13523. if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
  13524. painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y));
  13525. if (b-x > skipSymbolMargin)
  13526. painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y));
  13527. } else
  13528. painter->drawLine(QLineF(a, y, b, y));
  13529. // draw handles:
  13530. painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf));
  13531. painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf));
  13532. }
  13533. if (mErrorType == etValue || mErrorType == etBoth)
  13534. {
  13535. a = valueAxis->coordToPixel(data.value-data.valueErrorMinus);
  13536. b = valueAxis->coordToPixel(data.value+data.valueErrorPlus);
  13537. if (valueAxis->rangeReversed())
  13538. qSwap(a,b);
  13539. // draw spine:
  13540. if (mErrorBarSkipSymbol)
  13541. {
  13542. if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
  13543. painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin));
  13544. if (y-b > skipSymbolMargin)
  13545. painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b));
  13546. } else
  13547. painter->drawLine(QLineF(x, a, x, b));
  13548. // draw handles:
  13549. painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a));
  13550. painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b));
  13551. }
  13552. }
  13553. }
  13554. /*! \internal
  13555. called by \ref getPreparedData to determine which data (key) range is visible at the current key
  13556. axis range setting, so only that needs to be processed.
  13557. \a lower returns an iterator to the lowest data point that needs to be taken into account when
  13558. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  13559. lower may still be just outside the visible range.
  13560. \a upper returns an iterator to the highest data point. Same as before, \a upper may also lie
  13561. just outside of the visible range.
  13562. if the graph contains no data, both \a lower and \a upper point to constEnd.
  13563. */
  13564. void QCPGraph::getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMap::const_iterator &upper) const
  13565. {
  13566. if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
  13567. if (mData->isEmpty())
  13568. {
  13569. lower = mData->constEnd();
  13570. upper = mData->constEnd();
  13571. return;
  13572. }
  13573. // get visible data range as QMap iterators
  13574. QCPDataMap::const_iterator lbound = mData->lowerBound(mKeyAxis.data()->range().lower);
  13575. QCPDataMap::const_iterator ubound = mData->upperBound(mKeyAxis.data()->range().upper);
  13576. bool lowoutlier = lbound != mData->constBegin(); // indicates whether there exist points below axis range
  13577. bool highoutlier = ubound != mData->constEnd(); // indicates whether there exist points above axis range
  13578. lower = (lowoutlier ? lbound-1 : lbound); // data point range that will be actually drawn
  13579. upper = (highoutlier ? ubound : ubound-1); // data point range that will be actually drawn
  13580. }
  13581. /*! \internal
  13582. Counts the number of data points between \a lower and \a upper (including them), up to a maximum
  13583. of \a maxCount.
  13584. This function is used by \ref getPreparedData to determine whether adaptive sampling shall be
  13585. used (if enabled via \ref setAdaptiveSampling) or not. This is also why counting of data points
  13586. only needs to be done until \a maxCount is reached, which should be set to the number of data
  13587. points at which adaptive sampling sets in.
  13588. */
  13589. int QCPGraph::countDataInBounds(const QCPDataMap::const_iterator &lower, const QCPDataMap::const_iterator &upper, int maxCount) const
  13590. {
  13591. if (upper == mData->constEnd() && lower == mData->constEnd())
  13592. return 0;
  13593. QCPDataMap::const_iterator it = lower;
  13594. int count = 1;
  13595. while (it != upper && count < maxCount)
  13596. {
  13597. ++it;
  13598. ++count;
  13599. }
  13600. return count;
  13601. }
  13602. /*! \internal
  13603. The line data vector generated by e.g. getLinePlotData contains only the line that connects the
  13604. data points. If the graph needs to be filled, two additional points need to be added at the
  13605. value-zero-line in the lower and upper key positions of the graph. This function calculates these
  13606. points and adds them to the end of \a lineData. Since the fill is typically drawn before the line
  13607. stroke, these added points need to be removed again after the fill is done, with the
  13608. removeFillBasePoints function.
  13609. The expanding of \a lineData by two points will not cause unnecessary memory reallocations,
  13610. because the data vector generation functions (getLinePlotData etc.) reserve two extra points when
  13611. they allocate memory for \a lineData.
  13612. \see removeFillBasePoints, lowerFillBasePoint, upperFillBasePoint
  13613. */
  13614. void QCPGraph::addFillBasePoints(QVector<QPointF> *lineData) const
  13615. {
  13616. if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
  13617. // append points that close the polygon fill at the key axis:
  13618. if (mKeyAxis.data()->orientation() == Qt::Vertical)
  13619. {
  13620. *lineData << upperFillBasePoint(lineData->last().y());
  13621. *lineData << lowerFillBasePoint(lineData->first().y());
  13622. } else
  13623. {
  13624. *lineData << upperFillBasePoint(lineData->last().x());
  13625. *lineData << lowerFillBasePoint(lineData->first().x());
  13626. }
  13627. }
  13628. /*! \internal
  13629. removes the two points from \a lineData that were added by \ref addFillBasePoints.
  13630. \see addFillBasePoints, lowerFillBasePoint, upperFillBasePoint
  13631. */
  13632. void QCPGraph::removeFillBasePoints(QVector<QPointF> *lineData) const
  13633. {
  13634. lineData->remove(lineData->size()-2, 2);
  13635. }
  13636. /*! \internal
  13637. called by \ref addFillBasePoints to conveniently assign the point which closes the fill polygon
  13638. on the lower side of the zero-value-line parallel to the key axis. The logarithmic axis scale
  13639. case is a bit special, since the zero-value-line in pixel coordinates is in positive or negative
  13640. infinity. So this case is handled separately by just closing the fill polygon on the axis which
  13641. lies in the direction towards the zero value.
  13642. \a lowerKey will be the the key (in pixels) of the returned point. Depending on whether the key
  13643. axis is horizontal or vertical, \a lowerKey will end up as the x or y value of the returned
  13644. point, respectively.
  13645. \see upperFillBasePoint, addFillBasePoints
  13646. */
  13647. QPointF QCPGraph::lowerFillBasePoint(double lowerKey) const
  13648. {
  13649. QCPAxis *keyAxis = mKeyAxis.data();
  13650. QCPAxis *valueAxis = mValueAxis.data();
  13651. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
  13652. QPointF point;
  13653. if (valueAxis->scaleType() == QCPAxis::stLinear)
  13654. {
  13655. if (keyAxis->axisType() == QCPAxis::atLeft)
  13656. {
  13657. point.setX(valueAxis->coordToPixel(0));
  13658. point.setY(lowerKey);
  13659. } else if (keyAxis->axisType() == QCPAxis::atRight)
  13660. {
  13661. point.setX(valueAxis->coordToPixel(0));
  13662. point.setY(lowerKey);
  13663. } else if (keyAxis->axisType() == QCPAxis::atTop)
  13664. {
  13665. point.setX(lowerKey);
  13666. point.setY(valueAxis->coordToPixel(0));
  13667. } else if (keyAxis->axisType() == QCPAxis::atBottom)
  13668. {
  13669. point.setX(lowerKey);
  13670. point.setY(valueAxis->coordToPixel(0));
  13671. }
  13672. } else // valueAxis->mScaleType == QCPAxis::stLogarithmic
  13673. {
  13674. // In logarithmic scaling we can't just draw to value zero so we just fill all the way
  13675. // to the axis which is in the direction towards zero
  13676. if (keyAxis->orientation() == Qt::Vertical)
  13677. {
  13678. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
  13679. (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
  13680. point.setX(keyAxis->axisRect()->right());
  13681. else
  13682. point.setX(keyAxis->axisRect()->left());
  13683. point.setY(lowerKey);
  13684. } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom)
  13685. {
  13686. point.setX(lowerKey);
  13687. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
  13688. (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
  13689. point.setY(keyAxis->axisRect()->top());
  13690. else
  13691. point.setY(keyAxis->axisRect()->bottom());
  13692. }
  13693. }
  13694. return point;
  13695. }
  13696. /*! \internal
  13697. called by \ref addFillBasePoints to conveniently assign the point which closes the fill
  13698. polygon on the upper side of the zero-value-line parallel to the key axis. The logarithmic axis
  13699. scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or
  13700. negative infinity. So this case is handled separately by just closing the fill polygon on the
  13701. axis which lies in the direction towards the zero value.
  13702. \a upperKey will be the the key (in pixels) of the returned point. Depending on whether the key
  13703. axis is horizontal or vertical, \a upperKey will end up as the x or y value of the returned
  13704. point, respectively.
  13705. \see lowerFillBasePoint, addFillBasePoints
  13706. */
  13707. QPointF QCPGraph::upperFillBasePoint(double upperKey) const
  13708. {
  13709. QCPAxis *keyAxis = mKeyAxis.data();
  13710. QCPAxis *valueAxis = mValueAxis.data();
  13711. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
  13712. QPointF point;
  13713. if (valueAxis->scaleType() == QCPAxis::stLinear)
  13714. {
  13715. if (keyAxis->axisType() == QCPAxis::atLeft)
  13716. {
  13717. point.setX(valueAxis->coordToPixel(0));
  13718. point.setY(upperKey);
  13719. } else if (keyAxis->axisType() == QCPAxis::atRight)
  13720. {
  13721. point.setX(valueAxis->coordToPixel(0));
  13722. point.setY(upperKey);
  13723. } else if (keyAxis->axisType() == QCPAxis::atTop)
  13724. {
  13725. point.setX(upperKey);
  13726. point.setY(valueAxis->coordToPixel(0));
  13727. } else if (keyAxis->axisType() == QCPAxis::atBottom)
  13728. {
  13729. point.setX(upperKey);
  13730. point.setY(valueAxis->coordToPixel(0));
  13731. }
  13732. } else // valueAxis->mScaleType == QCPAxis::stLogarithmic
  13733. {
  13734. // In logarithmic scaling we can't just draw to value 0 so we just fill all the way
  13735. // to the axis which is in the direction towards 0
  13736. if (keyAxis->orientation() == Qt::Vertical)
  13737. {
  13738. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
  13739. (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
  13740. point.setX(keyAxis->axisRect()->right());
  13741. else
  13742. point.setX(keyAxis->axisRect()->left());
  13743. point.setY(upperKey);
  13744. } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom)
  13745. {
  13746. point.setX(upperKey);
  13747. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
  13748. (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
  13749. point.setY(keyAxis->axisRect()->top());
  13750. else
  13751. point.setY(keyAxis->axisRect()->bottom());
  13752. }
  13753. }
  13754. return point;
  13755. }
  13756. /*! \internal
  13757. Generates the polygon needed for drawing channel fills between this graph (data passed via \a
  13758. lineData) and the graph specified by mChannelFillGraph (data generated by calling its \ref
  13759. getPlotData function). May return an empty polygon if the key ranges have no overlap or fill
  13760. target graph and this graph don't have same orientation (i.e. both key axes horizontal or both
  13761. key axes vertical). For increased performance (due to implicit sharing), keep the returned
  13762. QPolygonF const.
  13763. */
  13764. const QPolygonF QCPGraph::getChannelFillPolygon(const QVector<QPointF> *lineData) const
  13765. {
  13766. if (!mChannelFillGraph)
  13767. return QPolygonF();
  13768. QCPAxis *keyAxis = mKeyAxis.data();
  13769. QCPAxis *valueAxis = mValueAxis.data();
  13770. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); }
  13771. if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); }
  13772. if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation())
  13773. 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)
  13774. if (lineData->isEmpty()) return QPolygonF();
  13775. QVector<QPointF> otherData;
  13776. mChannelFillGraph.data()->getPlotData(&otherData, 0);
  13777. if (otherData.isEmpty()) return QPolygonF();
  13778. QVector<QPointF> thisData;
  13779. thisData.reserve(lineData->size()+otherData.size()); // because we will join both vectors at end of this function
  13780. for (int i=0; i<lineData->size(); ++i) // don't use the vector<<(vector), it squeezes internally, which ruins the performance tuning with reserve()
  13781. thisData << lineData->at(i);
  13782. // pointers to be able to swap them, depending which data range needs cropping:
  13783. QVector<QPointF> *staticData = &thisData;
  13784. QVector<QPointF> *croppedData = &otherData;
  13785. // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType):
  13786. if (keyAxis->orientation() == Qt::Horizontal)
  13787. {
  13788. // x is key
  13789. // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys:
  13790. if (staticData->first().x() > staticData->last().x())
  13791. {
  13792. int size = staticData->size();
  13793. for (int i=0; i<size/2; ++i)
  13794. qSwap((*staticData)[i], (*staticData)[size-1-i]);
  13795. }
  13796. if (croppedData->first().x() > croppedData->last().x())
  13797. {
  13798. int size = croppedData->size();
  13799. for (int i=0; i<size/2; ++i)
  13800. qSwap((*croppedData)[i], (*croppedData)[size-1-i]);
  13801. }
  13802. // crop lower bound:
  13803. if (staticData->first().x() < croppedData->first().x()) // other one must be cropped
  13804. qSwap(staticData, croppedData);
  13805. int lowBound = findIndexBelowX(croppedData, staticData->first().x());
  13806. if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
  13807. croppedData->remove(0, lowBound);
  13808. // set lowest point of cropped data to fit exactly key position of first static data
  13809. // point via linear interpolation:
  13810. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  13811. double slope;
  13812. if (croppedData->at(1).x()-croppedData->at(0).x() != 0)
  13813. slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x());
  13814. else
  13815. slope = 0;
  13816. (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x()));
  13817. (*croppedData)[0].setX(staticData->first().x());
  13818. // crop upper bound:
  13819. if (staticData->last().x() > croppedData->last().x()) // other one must be cropped
  13820. qSwap(staticData, croppedData);
  13821. int highBound = findIndexAboveX(croppedData, staticData->last().x());
  13822. if (highBound == -1) return QPolygonF(); // key ranges have no overlap
  13823. croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
  13824. // set highest point of cropped data to fit exactly key position of last static data
  13825. // point via linear interpolation:
  13826. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  13827. int li = croppedData->size()-1; // last index
  13828. if (croppedData->at(li).x()-croppedData->at(li-1).x() != 0)
  13829. slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x());
  13830. else
  13831. slope = 0;
  13832. (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x()));
  13833. (*croppedData)[li].setX(staticData->last().x());
  13834. } else // mKeyAxis->orientation() == Qt::Vertical
  13835. {
  13836. // y is key
  13837. // similar to "x is key" but switched x,y. Further, lower/upper meaning is inverted compared to x,
  13838. // because in pixel coordinates, y increases from top to bottom, not bottom to top like data coordinate.
  13839. // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys:
  13840. if (staticData->first().y() < staticData->last().y())
  13841. {
  13842. int size = staticData->size();
  13843. for (int i=0; i<size/2; ++i)
  13844. qSwap((*staticData)[i], (*staticData)[size-1-i]);
  13845. }
  13846. if (croppedData->first().y() < croppedData->last().y())
  13847. {
  13848. int size = croppedData->size();
  13849. for (int i=0; i<size/2; ++i)
  13850. qSwap((*croppedData)[i], (*croppedData)[size-1-i]);
  13851. }
  13852. // crop lower bound:
  13853. if (staticData->first().y() > croppedData->first().y()) // other one must be cropped
  13854. qSwap(staticData, croppedData);
  13855. int lowBound = findIndexAboveY(croppedData, staticData->first().y());
  13856. if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
  13857. croppedData->remove(0, lowBound);
  13858. // set lowest point of cropped data to fit exactly key position of first static data
  13859. // point via linear interpolation:
  13860. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  13861. double slope;
  13862. if (croppedData->at(1).y()-croppedData->at(0).y() != 0) // avoid division by zero in step plots
  13863. slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y());
  13864. else
  13865. slope = 0;
  13866. (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y()));
  13867. (*croppedData)[0].setY(staticData->first().y());
  13868. // crop upper bound:
  13869. if (staticData->last().y() < croppedData->last().y()) // other one must be cropped
  13870. qSwap(staticData, croppedData);
  13871. int highBound = findIndexBelowY(croppedData, staticData->last().y());
  13872. if (highBound == -1) return QPolygonF(); // key ranges have no overlap
  13873. croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
  13874. // set highest point of cropped data to fit exactly key position of last static data
  13875. // point via linear interpolation:
  13876. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  13877. int li = croppedData->size()-1; // last index
  13878. if (croppedData->at(li).y()-croppedData->at(li-1).y() != 0) // avoid division by zero in step plots
  13879. slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y());
  13880. else
  13881. slope = 0;
  13882. (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y()));
  13883. (*croppedData)[li].setY(staticData->last().y());
  13884. }
  13885. // return joined:
  13886. for (int i=otherData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted
  13887. thisData << otherData.at(i);
  13888. return QPolygonF(thisData);
  13889. }
  13890. /*! \internal
  13891. Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in
  13892. \a data points are ordered ascending, as is the case when plotting with horizontal key axis.
  13893. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  13894. */
  13895. int QCPGraph::findIndexAboveX(const QVector<QPointF> *data, double x) const
  13896. {
  13897. for (int i=data->size()-1; i>=0; --i)
  13898. {
  13899. if (data->at(i).x() < x)
  13900. {
  13901. if (i<data->size()-1)
  13902. return i+1;
  13903. else
  13904. return data->size()-1;
  13905. }
  13906. }
  13907. return -1;
  13908. }
  13909. /*! \internal
  13910. Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in
  13911. \a data points are ordered ascending, as is the case when plotting with horizontal key axis.
  13912. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  13913. */
  13914. int QCPGraph::findIndexBelowX(const QVector<QPointF> *data, double x) const
  13915. {
  13916. for (int i=0; i<data->size(); ++i)
  13917. {
  13918. if (data->at(i).x() > x)
  13919. {
  13920. if (i>0)
  13921. return i-1;
  13922. else
  13923. return 0;
  13924. }
  13925. }
  13926. return -1;
  13927. }
  13928. /*! \internal
  13929. Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in
  13930. \a data points are ordered descending, as is the case when plotting with vertical key axis.
  13931. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  13932. */
  13933. int QCPGraph::findIndexAboveY(const QVector<QPointF> *data, double y) const
  13934. {
  13935. for (int i=0; i<data->size(); ++i)
  13936. {
  13937. if (data->at(i).y() < y)
  13938. {
  13939. if (i>0)
  13940. return i-1;
  13941. else
  13942. return 0;
  13943. }
  13944. }
  13945. return -1;
  13946. }
  13947. /*! \internal
  13948. Calculates the (minimum) distance (in pixels) the graph's representation has from the given \a
  13949. pixelPoint in pixels. This is used to determine whether the graph was clicked or not, e.g. in
  13950. \ref selectTest.
  13951. If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape
  13952. is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns
  13953. 500.
  13954. */
  13955. double QCPGraph::pointDistance(const QPointF &pixelPoint) const
  13956. {
  13957. if (mData->isEmpty())
  13958. {
  13959. qDebug() << Q_FUNC_INFO << "requested point distance on graph" << mName << "without data";
  13960. return 500;
  13961. }
  13962. if (mData->size() == 1)
  13963. {
  13964. QPointF dataPoint = coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value);
  13965. return QVector2D(dataPoint-pixelPoint).length();
  13966. }
  13967. if (mLineStyle == lsNone && mScatterStyle.isNone())
  13968. return 500;
  13969. // calculate minimum distances to graph representation:
  13970. if (mLineStyle == lsNone)
  13971. {
  13972. // no line displayed, only calculate distance to scatter points:
  13973. QVector<QCPData> *scatterData = new QVector<QCPData>;
  13974. getScatterPlotData(scatterData);
  13975. double minDistSqr = std::numeric_limits<double>::max();
  13976. QPointF ptA;
  13977. QPointF ptB = coordsToPixels(scatterData->at(0).key, scatterData->at(0).value); // getScatterPlotData returns in plot coordinates, so transform to pixels
  13978. for (int i=1; i<scatterData->size(); ++i)
  13979. {
  13980. ptA = ptB;
  13981. ptB = coordsToPixels(scatterData->at(i).key, scatterData->at(i).value);
  13982. double currentDistSqr = distSqrToLine(ptA, ptB, pixelPoint);
  13983. if (currentDistSqr < minDistSqr)
  13984. minDistSqr = currentDistSqr;
  13985. }
  13986. delete scatterData;
  13987. return sqrt(minDistSqr);
  13988. } else
  13989. {
  13990. // line displayed calculate distance to line segments:
  13991. QVector<QPointF> *lineData = new QVector<QPointF>;
  13992. getPlotData(lineData, 0); // unlike with getScatterPlotData we get pixel coordinates here
  13993. double minDistSqr = std::numeric_limits<double>::max();
  13994. if (mLineStyle == lsImpulse)
  13995. {
  13996. // impulse plot differs from other line styles in that the lineData points are only pairwise connected:
  13997. for (int i=0; i<lineData->size()-1; i+=2) // iterate pairs
  13998. {
  13999. double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint);
  14000. if (currentDistSqr < minDistSqr)
  14001. minDistSqr = currentDistSqr;
  14002. }
  14003. } else
  14004. {
  14005. // all other line plots (line and step) connect points directly:
  14006. for (int i=0; i<lineData->size()-1; ++i)
  14007. {
  14008. double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint);
  14009. if (currentDistSqr < minDistSqr)
  14010. minDistSqr = currentDistSqr;
  14011. }
  14012. }
  14013. delete lineData;
  14014. return sqrt(minDistSqr);
  14015. }
  14016. }
  14017. /*! \internal
  14018. Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in
  14019. \a data points are ordered descending, as is the case when plotting with vertical key axis (since
  14020. keys are ordered ascending).
  14021. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  14022. */
  14023. int QCPGraph::findIndexBelowY(const QVector<QPointF> *data, double y) const
  14024. {
  14025. for (int i=data->size()-1; i>=0; --i)
  14026. {
  14027. if (data->at(i).y() > y)
  14028. {
  14029. if (i<data->size()-1)
  14030. return i+1;
  14031. else
  14032. return data->size()-1;
  14033. }
  14034. }
  14035. return -1;
  14036. }
  14037. /* inherits documentation from base class */
  14038. QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain) const
  14039. {
  14040. // just call the specialized version which takes an additional argument whether error bars
  14041. // should also be taken into consideration for range calculation. We set this to true here.
  14042. return getKeyRange(foundRange, inSignDomain, true);
  14043. }
  14044. /* inherits documentation from base class */
  14045. QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain) const
  14046. {
  14047. // just call the specialized version which takes an additional argument whether error bars
  14048. // should also be taken into consideration for range calculation. We set this to true here.
  14049. return getValueRange(foundRange, inSignDomain, true);
  14050. }
  14051. /*! \overload
  14052. Allows to specify whether the error bars should be included in the range calculation.
  14053. \see getKeyRange(bool &foundRange, SignDomain inSignDomain)
  14054. */
  14055. QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const
  14056. {
  14057. QCPRange range;
  14058. bool haveLower = false;
  14059. bool haveUpper = false;
  14060. double current, currentErrorMinus, currentErrorPlus;
  14061. if (inSignDomain == sdBoth) // range may be anywhere
  14062. {
  14063. QCPDataMap::const_iterator it = mData->constBegin();
  14064. while (it != mData->constEnd())
  14065. {
  14066. current = it.value().key;
  14067. currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0);
  14068. currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0);
  14069. if (current-currentErrorMinus < range.lower || !haveLower)
  14070. {
  14071. range.lower = current-currentErrorMinus;
  14072. haveLower = true;
  14073. }
  14074. if (current+currentErrorPlus > range.upper || !haveUpper)
  14075. {
  14076. range.upper = current+currentErrorPlus;
  14077. haveUpper = true;
  14078. }
  14079. ++it;
  14080. }
  14081. } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain
  14082. {
  14083. QCPDataMap::const_iterator it = mData->constBegin();
  14084. while (it != mData->constEnd())
  14085. {
  14086. current = it.value().key;
  14087. currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0);
  14088. currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0);
  14089. if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0)
  14090. {
  14091. range.lower = current-currentErrorMinus;
  14092. haveLower = true;
  14093. }
  14094. if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0)
  14095. {
  14096. range.upper = current+currentErrorPlus;
  14097. haveUpper = true;
  14098. }
  14099. if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point.
  14100. {
  14101. if ((current < range.lower || !haveLower) && current < 0)
  14102. {
  14103. range.lower = current;
  14104. haveLower = true;
  14105. }
  14106. if ((current > range.upper || !haveUpper) && current < 0)
  14107. {
  14108. range.upper = current;
  14109. haveUpper = true;
  14110. }
  14111. }
  14112. ++it;
  14113. }
  14114. } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain
  14115. {
  14116. QCPDataMap::const_iterator it = mData->constBegin();
  14117. while (it != mData->constEnd())
  14118. {
  14119. current = it.value().key;
  14120. currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0);
  14121. currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0);
  14122. if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0)
  14123. {
  14124. range.lower = current-currentErrorMinus;
  14125. haveLower = true;
  14126. }
  14127. if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0)
  14128. {
  14129. range.upper = current+currentErrorPlus;
  14130. haveUpper = true;
  14131. }
  14132. if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point.
  14133. {
  14134. if ((current < range.lower || !haveLower) && current > 0)
  14135. {
  14136. range.lower = current;
  14137. haveLower = true;
  14138. }
  14139. if ((current > range.upper || !haveUpper) && current > 0)
  14140. {
  14141. range.upper = current;
  14142. haveUpper = true;
  14143. }
  14144. }
  14145. ++it;
  14146. }
  14147. }
  14148. foundRange = haveLower && haveUpper;
  14149. return range;
  14150. }
  14151. /*! \overload
  14152. Allows to specify whether the error bars should be included in the range calculation.
  14153. \see getValueRange(bool &foundRange, SignDomain inSignDomain)
  14154. */
  14155. QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const
  14156. {
  14157. QCPRange range;
  14158. bool haveLower = false;
  14159. bool haveUpper = false;
  14160. double current, currentErrorMinus, currentErrorPlus;
  14161. if (inSignDomain == sdBoth) // range may be anywhere
  14162. {
  14163. QCPDataMap::const_iterator it = mData->constBegin();
  14164. while (it != mData->constEnd())
  14165. {
  14166. current = it.value().value;
  14167. currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0);
  14168. currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0);
  14169. if (current-currentErrorMinus < range.lower || !haveLower)
  14170. {
  14171. range.lower = current-currentErrorMinus;
  14172. haveLower = true;
  14173. }
  14174. if (current+currentErrorPlus > range.upper || !haveUpper)
  14175. {
  14176. range.upper = current+currentErrorPlus;
  14177. haveUpper = true;
  14178. }
  14179. ++it;
  14180. }
  14181. } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain
  14182. {
  14183. QCPDataMap::const_iterator it = mData->constBegin();
  14184. while (it != mData->constEnd())
  14185. {
  14186. current = it.value().value;
  14187. currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0);
  14188. currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0);
  14189. if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0)
  14190. {
  14191. range.lower = current-currentErrorMinus;
  14192. haveLower = true;
  14193. }
  14194. if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0)
  14195. {
  14196. range.upper = current+currentErrorPlus;
  14197. haveUpper = true;
  14198. }
  14199. if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point.
  14200. {
  14201. if ((current < range.lower || !haveLower) && current < 0)
  14202. {
  14203. range.lower = current;
  14204. haveLower = true;
  14205. }
  14206. if ((current > range.upper || !haveUpper) && current < 0)
  14207. {
  14208. range.upper = current;
  14209. haveUpper = true;
  14210. }
  14211. }
  14212. ++it;
  14213. }
  14214. } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain
  14215. {
  14216. QCPDataMap::const_iterator it = mData->constBegin();
  14217. while (it != mData->constEnd())
  14218. {
  14219. current = it.value().value;
  14220. currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0);
  14221. currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0);
  14222. if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0)
  14223. {
  14224. range.lower = current-currentErrorMinus;
  14225. haveLower = true;
  14226. }
  14227. if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0)
  14228. {
  14229. range.upper = current+currentErrorPlus;
  14230. haveUpper = true;
  14231. }
  14232. if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point.
  14233. {
  14234. if ((current < range.lower || !haveLower) && current > 0)
  14235. {
  14236. range.lower = current;
  14237. haveLower = true;
  14238. }
  14239. if ((current > range.upper || !haveUpper) && current > 0)
  14240. {
  14241. range.upper = current;
  14242. haveUpper = true;
  14243. }
  14244. }
  14245. ++it;
  14246. }
  14247. }
  14248. foundRange = haveLower && haveUpper;
  14249. return range;
  14250. }
  14251. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14252. //////////////////// QCPCurveData
  14253. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14254. /*! \class QCPCurveData
  14255. \brief Holds the data of one single data point for QCPCurve.
  14256. The container for storing multiple data points is \ref QCPCurveDataMap.
  14257. The stored data is:
  14258. \li \a t: the free parameter of the curve at this curve point (cp. the mathematical vector <em>(x(t), y(t))</em>)
  14259. \li \a key: coordinate on the key axis of this curve point
  14260. \li \a value: coordinate on the value axis of this curve point
  14261. \see QCPCurveDataMap
  14262. */
  14263. /*!
  14264. Constructs a curve data point with t, key and value set to zero.
  14265. */
  14266. QCPCurveData::QCPCurveData() :
  14267. t(0),
  14268. key(0),
  14269. value(0)
  14270. {
  14271. }
  14272. /*!
  14273. Constructs a curve data point with the specified \a t, \a key and \a value.
  14274. */
  14275. QCPCurveData::QCPCurveData(double t, double key, double value) :
  14276. t(t),
  14277. key(key),
  14278. value(value)
  14279. {
  14280. }
  14281. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14282. //////////////////// QCPCurve
  14283. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14284. /*! \class QCPCurve
  14285. \brief A plottable representing a parametric curve in a plot.
  14286. \image html QCPCurve.png
  14287. Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate,
  14288. so their visual representation can have \a loops. This is realized by introducing a third
  14289. coordinate \a t, which defines the order of the points described by the other two coordinates \a
  14290. x and \a y.
  14291. To plot data, assign it with the \ref setData or \ref addData functions.
  14292. \section appearance Changing the appearance
  14293. The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush).
  14294. \section usage Usage
  14295. Like all data representing objects in QCustomPlot, the QCPCurve is a plottable (QCPAbstractPlottable). So
  14296. the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.)
  14297. Usually, you first create an instance:
  14298. \code
  14299. QCPCurve *newCurve = new QCPCurve(customPlot->xAxis, customPlot->yAxis);\endcode
  14300. add it to the customPlot with QCustomPlot::addPlottable:
  14301. \code
  14302. customPlot->addPlottable(newCurve);\endcode
  14303. and then modify the properties of the newly created plottable, e.g.:
  14304. \code
  14305. newCurve->setName("Fermat's Spiral");
  14306. newCurve->setData(tData, xData, yData);\endcode
  14307. */
  14308. /*!
  14309. Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  14310. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  14311. the same orientation. If either of these restrictions is violated, a corresponding message is
  14312. printed to the debug output (qDebug), the construction is not aborted, though.
  14313. The constructed QCPCurve can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
  14314. then takes ownership of the graph.
  14315. */
  14316. QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  14317. QCPAbstractPlottable(keyAxis, valueAxis)
  14318. {
  14319. mData = new QCPCurveDataMap;
  14320. mPen.setColor(Qt::blue);
  14321. mPen.setStyle(Qt::SolidLine);
  14322. mBrush.setColor(Qt::blue);
  14323. mBrush.setStyle(Qt::NoBrush);
  14324. mSelectedPen = mPen;
  14325. mSelectedPen.setWidthF(2.5);
  14326. mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen
  14327. mSelectedBrush = mBrush;
  14328. setScatterStyle(QCPScatterStyle());
  14329. setLineStyle(lsLine);
  14330. }
  14331. QCPCurve::~QCPCurve()
  14332. {
  14333. delete mData;
  14334. }
  14335. /*!
  14336. Replaces the current data with the provided \a data.
  14337. If \a copy is set to true, data points in \a data will only be copied. if false, the plottable
  14338. takes ownership of the passed data and replaces the internal data pointer with it. This is
  14339. significantly faster than copying for large datasets.
  14340. */
  14341. void QCPCurve::setData(QCPCurveDataMap *data, bool copy)
  14342. {
  14343. if (copy)
  14344. {
  14345. *mData = *data;
  14346. } else
  14347. {
  14348. delete mData;
  14349. mData = data;
  14350. }
  14351. }
  14352. /*! \overload
  14353. Replaces the current data with the provided points in \a t, \a key and \a value tuples. The
  14354. provided vectors should have equal length. Else, the number of added points will be the size of
  14355. the smallest vector.
  14356. */
  14357. void QCPCurve::setData(const QVector<double> &t, const QVector<double> &key, const QVector<double> &value)
  14358. {
  14359. mData->clear();
  14360. int n = t.size();
  14361. n = qMin(n, key.size());
  14362. n = qMin(n, value.size());
  14363. QCPCurveData newData;
  14364. for (int i=0; i<n; ++i)
  14365. {
  14366. newData.t = t[i];
  14367. newData.key = key[i];
  14368. newData.value = value[i];
  14369. mData->insertMulti(newData.t, newData);
  14370. }
  14371. }
  14372. /*! \overload
  14373. Replaces the current data with the provided \a key and \a value pairs. The t parameter
  14374. of each data point will be set to the integer index of the respective key/value pair.
  14375. */
  14376. void QCPCurve::setData(const QVector<double> &key, const QVector<double> &value)
  14377. {
  14378. mData->clear();
  14379. int n = key.size();
  14380. n = qMin(n, value.size());
  14381. QCPCurveData newData;
  14382. for (int i=0; i<n; ++i)
  14383. {
  14384. newData.t = i; // no t vector given, so we assign t the index of the key/value pair
  14385. newData.key = key[i];
  14386. newData.value = value[i];
  14387. mData->insertMulti(newData.t, newData);
  14388. }
  14389. }
  14390. /*!
  14391. Sets the visual appearance of single data points in the plot. If set to \ref
  14392. QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate
  14393. line style).
  14394. \see QCPScatterStyle, setLineStyle
  14395. */
  14396. void QCPCurve::setScatterStyle(const QCPScatterStyle &style)
  14397. {
  14398. mScatterStyle = style;
  14399. }
  14400. /*!
  14401. Sets how the single data points are connected in the plot or how they are represented visually
  14402. apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref
  14403. setScatterStyle to the desired scatter style.
  14404. \see setScatterStyle
  14405. */
  14406. void QCPCurve::setLineStyle(QCPCurve::LineStyle style)
  14407. {
  14408. mLineStyle = style;
  14409. }
  14410. /*!
  14411. Adds the provided data points in \a dataMap to the current data.
  14412. \see removeData
  14413. */
  14414. void QCPCurve::addData(const QCPCurveDataMap &dataMap)
  14415. {
  14416. mData->unite(dataMap);
  14417. }
  14418. /*! \overload
  14419. Adds the provided single data point in \a data to the current data.
  14420. \see removeData
  14421. */
  14422. void QCPCurve::addData(const QCPCurveData &data)
  14423. {
  14424. mData->insertMulti(data.t, data);
  14425. }
  14426. /*! \overload
  14427. Adds the provided single data point as \a t, \a key and \a value tuple to the current data
  14428. \see removeData
  14429. */
  14430. void QCPCurve::addData(double t, double key, double value)
  14431. {
  14432. QCPCurveData newData;
  14433. newData.t = t;
  14434. newData.key = key;
  14435. newData.value = value;
  14436. mData->insertMulti(newData.t, newData);
  14437. }
  14438. /*! \overload
  14439. Adds the provided single data point as \a key and \a value pair to the current data The t
  14440. parameter of the data point is set to the t of the last data point plus 1. If there is no last
  14441. data point, t will be set to 0.
  14442. \see removeData
  14443. */
  14444. void QCPCurve::addData(double key, double value)
  14445. {
  14446. QCPCurveData newData;
  14447. if (!mData->isEmpty())
  14448. newData.t = (mData->constEnd()-1).key()+1;
  14449. else
  14450. newData.t = 0;
  14451. newData.key = key;
  14452. newData.value = value;
  14453. mData->insertMulti(newData.t, newData);
  14454. }
  14455. /*! \overload
  14456. Adds the provided data points as \a t, \a key and \a value tuples to the current data.
  14457. \see removeData
  14458. */
  14459. void QCPCurve::addData(const QVector<double> &ts, const QVector<double> &keys, const QVector<double> &values)
  14460. {
  14461. int n = ts.size();
  14462. n = qMin(n, keys.size());
  14463. n = qMin(n, values.size());
  14464. QCPCurveData newData;
  14465. for (int i=0; i<n; ++i)
  14466. {
  14467. newData.t = ts[i];
  14468. newData.key = keys[i];
  14469. newData.value = values[i];
  14470. mData->insertMulti(newData.t, newData);
  14471. }
  14472. }
  14473. /*!
  14474. Removes all data points with curve parameter t smaller than \a t.
  14475. \see addData, clearData
  14476. */
  14477. void QCPCurve::removeDataBefore(double t)
  14478. {
  14479. QCPCurveDataMap::iterator it = mData->begin();
  14480. while (it != mData->end() && it.key() < t)
  14481. it = mData->erase(it);
  14482. }
  14483. /*!
  14484. Removes all data points with curve parameter t greater than \a t.
  14485. \see addData, clearData
  14486. */
  14487. void QCPCurve::removeDataAfter(double t)
  14488. {
  14489. if (mData->isEmpty()) return;
  14490. QCPCurveDataMap::iterator it = mData->upperBound(t);
  14491. while (it != mData->end())
  14492. it = mData->erase(it);
  14493. }
  14494. /*!
  14495. Removes all data points with curve parameter t between \a fromt and \a tot. if \a fromt is
  14496. greater or equal to \a tot, the function does nothing. To remove a single data point with known
  14497. t, use \ref removeData(double t).
  14498. \see addData, clearData
  14499. */
  14500. void QCPCurve::removeData(double fromt, double tot)
  14501. {
  14502. if (fromt >= tot || mData->isEmpty()) return;
  14503. QCPCurveDataMap::iterator it = mData->upperBound(fromt);
  14504. QCPCurveDataMap::iterator itEnd = mData->upperBound(tot);
  14505. while (it != itEnd)
  14506. it = mData->erase(it);
  14507. }
  14508. /*! \overload
  14509. Removes a single data point at curve parameter \a t. If the position is not known with absolute
  14510. precision, consider using \ref removeData(double fromt, double tot) with a small fuzziness
  14511. interval around the suspected position, depeding on the precision with which the curve parameter
  14512. is known.
  14513. \see addData, clearData
  14514. */
  14515. void QCPCurve::removeData(double t)
  14516. {
  14517. mData->remove(t);
  14518. }
  14519. /*!
  14520. Removes all data points.
  14521. \see removeData, removeDataAfter, removeDataBefore
  14522. */
  14523. void QCPCurve::clearData()
  14524. {
  14525. mData->clear();
  14526. }
  14527. /* inherits documentation from base class */
  14528. double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  14529. {
  14530. Q_UNUSED(details)
  14531. if ((onlySelectable && !mSelectable) || mData->isEmpty())
  14532. return -1;
  14533. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  14534. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
  14535. return pointDistance(pos);
  14536. else
  14537. return -1;
  14538. }
  14539. /* inherits documentation from base class */
  14540. void QCPCurve::draw(QCPPainter *painter)
  14541. {
  14542. if (mData->isEmpty()) return;
  14543. // allocate line vector:
  14544. QVector<QPointF> *lineData = new QVector<QPointF>;
  14545. // fill with curve data:
  14546. getCurveData(lineData);
  14547. // check data validity if flag set:
  14548. #ifdef QCUSTOMPLOT_CHECK_DATA
  14549. QCPCurveDataMap::const_iterator it;
  14550. for (it = mData->constBegin(); it != mData->constEnd(); ++it)
  14551. {
  14552. if (QCP::isInvalidData(it.value().t) ||
  14553. QCP::isInvalidData(it.value().key, it.value().value))
  14554. qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name();
  14555. }
  14556. #endif
  14557. // draw curve fill:
  14558. if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0)
  14559. {
  14560. applyFillAntialiasingHint(painter);
  14561. painter->setPen(Qt::NoPen);
  14562. painter->setBrush(mainBrush());
  14563. painter->drawPolygon(QPolygonF(*lineData));
  14564. }
  14565. // draw curve line:
  14566. if (mLineStyle != lsNone && mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)
  14567. {
  14568. applyDefaultAntialiasingHint(painter);
  14569. painter->setPen(mainPen());
  14570. painter->setBrush(Qt::NoBrush);
  14571. // if drawing solid line and not in PDF, use much faster line drawing instead of polyline:
  14572. if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) &&
  14573. painter->pen().style() == Qt::SolidLine &&
  14574. !painter->modes().testFlag(QCPPainter::pmVectorized) &&
  14575. !painter->modes().testFlag(QCPPainter::pmNoCaching))
  14576. {
  14577. for (int i=1; i<lineData->size(); ++i)
  14578. painter->drawLine(lineData->at(i-1), lineData->at(i));
  14579. } else
  14580. {
  14581. painter->drawPolyline(QPolygonF(*lineData));
  14582. }
  14583. }
  14584. // draw scatters:
  14585. if (!mScatterStyle.isNone())
  14586. drawScatterPlot(painter, lineData);
  14587. // free allocated line data:
  14588. delete lineData;
  14589. }
  14590. /* inherits documentation from base class */
  14591. void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  14592. {
  14593. // draw fill:
  14594. if (mBrush.style() != Qt::NoBrush)
  14595. {
  14596. applyFillAntialiasingHint(painter);
  14597. painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
  14598. }
  14599. // draw line vertically centered:
  14600. if (mLineStyle != lsNone)
  14601. {
  14602. applyDefaultAntialiasingHint(painter);
  14603. painter->setPen(mPen);
  14604. 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
  14605. }
  14606. // draw scatter symbol:
  14607. if (!mScatterStyle.isNone())
  14608. {
  14609. applyScattersAntialiasingHint(painter);
  14610. // scale scatter pixmap if it's too large to fit in legend icon rect:
  14611. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
  14612. {
  14613. QCPScatterStyle scaledStyle(mScatterStyle);
  14614. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  14615. scaledStyle.applyTo(painter, mPen);
  14616. scaledStyle.drawShape(painter, QRectF(rect).center());
  14617. } else
  14618. {
  14619. mScatterStyle.applyTo(painter, mPen);
  14620. mScatterStyle.drawShape(painter, QRectF(rect).center());
  14621. }
  14622. }
  14623. }
  14624. /*! \internal
  14625. Draws scatter symbols at every data point passed in \a pointData. scatter symbols are independent of
  14626. the line style and are always drawn if scatter shape is not \ref QCPScatterStyle::ssNone.
  14627. */
  14628. void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> *pointData) const
  14629. {
  14630. // draw scatter point symbols:
  14631. applyScattersAntialiasingHint(painter);
  14632. mScatterStyle.applyTo(painter, mPen);
  14633. for (int i=0; i<pointData->size(); ++i)
  14634. mScatterStyle.drawShape(painter, pointData->at(i));
  14635. }
  14636. /*! \internal
  14637. called by QCPCurve::draw to generate a point vector (pixels) which represents the line of the
  14638. curve. Line segments that aren't visible in the current axis rect are handled in an optimized
  14639. way.
  14640. */
  14641. void QCPCurve::getCurveData(QVector<QPointF> *lineData) const
  14642. {
  14643. /* Extended sides of axis rect R divide space into 9 regions:
  14644. 1__|_4_|__7
  14645. 2__|_R_|__8
  14646. 3 | 6 | 9
  14647. General idea: If the two points of a line segment are in the same region (that is not R), the line segment corner is removed.
  14648. Curves outside R become straight lines closely outside of R which greatly reduces drawing time, yet keeps the look of lines and
  14649. fills inside R consistent.
  14650. The region R has index 5.
  14651. */
  14652. QCPAxis *keyAxis = mKeyAxis.data();
  14653. QCPAxis *valueAxis = mValueAxis.data();
  14654. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  14655. QRect axisRect = mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect();
  14656. lineData->reserve(mData->size());
  14657. QCPCurveDataMap::const_iterator it;
  14658. int lastRegion = 5;
  14659. int currentRegion = 5;
  14660. double RLeft = keyAxis->range().lower;
  14661. double RRight = keyAxis->range().upper;
  14662. double RBottom = valueAxis->range().lower;
  14663. double RTop = valueAxis->range().upper;
  14664. double x, y; // current key/value
  14665. bool addedLastAlready = true;
  14666. bool firstPoint = true; // first point must always be drawn, to make sure fill works correctly
  14667. for (it = mData->constBegin(); it != mData->constEnd(); ++it)
  14668. {
  14669. x = it.value().key;
  14670. y = it.value().value;
  14671. // determine current region:
  14672. if (x < RLeft) // region 123
  14673. {
  14674. if (y > RTop)
  14675. currentRegion = 1;
  14676. else if (y < RBottom)
  14677. currentRegion = 3;
  14678. else
  14679. currentRegion = 2;
  14680. } else if (x > RRight) // region 789
  14681. {
  14682. if (y > RTop)
  14683. currentRegion = 7;
  14684. else if (y < RBottom)
  14685. currentRegion = 9;
  14686. else
  14687. currentRegion = 8;
  14688. } else // region 456
  14689. {
  14690. if (y > RTop)
  14691. currentRegion = 4;
  14692. else if (y < RBottom)
  14693. currentRegion = 6;
  14694. else
  14695. currentRegion = 5;
  14696. }
  14697. /*
  14698. Watch out, the next part is very tricky. It modifies the curve such that it seems like the
  14699. whole thing is still drawn, but actually the points outside the axisRect are simplified
  14700. ("optimized") greatly. There are some subtle special cases when line segments are large and
  14701. thereby each subsequent point may be in a different region or even skip some.
  14702. */
  14703. // determine whether to keep current point:
  14704. if (currentRegion == 5 || (firstPoint && mBrush.style() != Qt::NoBrush)) // current is in R, add current and last if it wasn't added already
  14705. {
  14706. if (!addedLastAlready) // in case curve just entered R, make sure the last point outside R is also drawn correctly
  14707. lineData->append(coordsToPixels((it-1).value().key, (it-1).value().value)); // add last point to vector
  14708. else if (lastRegion != 5) // added last already. If that's the case, we probably added it at optimized position. So go back and make sure it's at original position (else the angle changes under which this segment enters R)
  14709. {
  14710. if (!firstPoint) // because on firstPoint, currentRegion is 5 and addedLastAlready is true, although there is no last point
  14711. lineData->replace(lineData->size()-1, coordsToPixels((it-1).value().key, (it-1).value().value));
  14712. }
  14713. lineData->append(coordsToPixels(it.value().key, it.value().value)); // add current point to vector
  14714. addedLastAlready = true; // so in next iteration, we don't add this point twice
  14715. } else if (currentRegion != lastRegion) // changed region, add current and last if not added already
  14716. {
  14717. // using outsideCoordsToPixels instead of coorsToPixels for optimized point placement (places points just outside axisRect instead of potentially far away)
  14718. // if we're coming from R or we skip diagonally over the corner regions (so line might still be visible in R), we can't place points optimized
  14719. if (lastRegion == 5 || // coming from R
  14720. ((lastRegion==2 && currentRegion==4) || (lastRegion==4 && currentRegion==2)) || // skip top left diagonal
  14721. ((lastRegion==4 && currentRegion==8) || (lastRegion==8 && currentRegion==4)) || // skip top right diagonal
  14722. ((lastRegion==8 && currentRegion==6) || (lastRegion==6 && currentRegion==8)) || // skip bottom right diagonal
  14723. ((lastRegion==6 && currentRegion==2) || (lastRegion==2 && currentRegion==6)) // skip bottom left diagonal
  14724. )
  14725. {
  14726. // always add last point if not added already, original:
  14727. if (!addedLastAlready)
  14728. lineData->append(coordsToPixels((it-1).value().key, (it-1).value().value));
  14729. // add current point, original:
  14730. lineData->append(coordsToPixels(it.value().key, it.value().value));
  14731. } else // no special case that forbids optimized point placement, so do it:
  14732. {
  14733. // always add last point if not added already, optimized:
  14734. if (!addedLastAlready)
  14735. lineData->append(outsideCoordsToPixels((it-1).value().key, (it-1).value().value, currentRegion, axisRect));
  14736. // add current point, optimized:
  14737. lineData->append(outsideCoordsToPixels(it.value().key, it.value().value, currentRegion, axisRect));
  14738. }
  14739. addedLastAlready = true; // so that if next point enters 5, or crosses another region boundary, we don't add this point twice
  14740. } else // neither in R, nor crossed a region boundary, skip current point
  14741. {
  14742. addedLastAlready = false;
  14743. }
  14744. lastRegion = currentRegion;
  14745. firstPoint = false;
  14746. }
  14747. // If curve ends outside R, we want to add very last point so the fill looks like it should when the curve started inside R:
  14748. if (lastRegion != 5 && mBrush.style() != Qt::NoBrush && !mData->isEmpty())
  14749. lineData->append(coordsToPixels((mData->constEnd()-1).value().key, (mData->constEnd()-1).value().value));
  14750. }
  14751. /*! \internal
  14752. Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a
  14753. pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in
  14754. \ref selectTest.
  14755. */
  14756. double QCPCurve::pointDistance(const QPointF &pixelPoint) const
  14757. {
  14758. if (mData->isEmpty())
  14759. {
  14760. qDebug() << Q_FUNC_INFO << "requested point distance on curve" << mName << "without data";
  14761. return 500;
  14762. }
  14763. if (mData->size() == 1)
  14764. {
  14765. QPointF dataPoint = coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value);
  14766. return QVector2D(dataPoint-pixelPoint).length();
  14767. }
  14768. // calculate minimum distance to line segments:
  14769. QVector<QPointF> *lineData = new QVector<QPointF>;
  14770. getCurveData(lineData);
  14771. double minDistSqr = std::numeric_limits<double>::max();
  14772. for (int i=0; i<lineData->size()-1; ++i)
  14773. {
  14774. double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint);
  14775. if (currentDistSqr < minDistSqr)
  14776. minDistSqr = currentDistSqr;
  14777. }
  14778. delete lineData;
  14779. return sqrt(minDistSqr);
  14780. }
  14781. /*! \internal
  14782. This is a specialized \ref coordsToPixels function for points that are outside the visible
  14783. axisRect and just crossing a boundary (since \ref getCurveData reduces non-visible curve segments
  14784. to those line segments that cross region boundaries, see documentation there). It only uses the
  14785. coordinate parallel to the region boundary of the axisRect. The other coordinate is picked just
  14786. outside the axisRect (how far is determined by the scatter size and the line width). Together
  14787. with the optimization in \ref getCurveData this improves performance for large curves (or zoomed
  14788. in ones) significantly while keeping the illusion the whole curve and its filling is still being
  14789. drawn for the viewer.
  14790. */
  14791. QPointF QCPCurve::outsideCoordsToPixels(double key, double value, int region, QRect axisRect) const
  14792. {
  14793. int margin = qCeil(qMax(mScatterStyle.size(), (double)mPen.widthF())) + 2;
  14794. QPointF result = coordsToPixels(key, value);
  14795. switch (region)
  14796. {
  14797. case 2: result.setX(axisRect.left()-margin); break; // left
  14798. case 8: result.setX(axisRect.right()+margin); break; // right
  14799. case 4: result.setY(axisRect.top()-margin); break; // top
  14800. case 6: result.setY(axisRect.bottom()+margin); break; // bottom
  14801. case 1: result.setX(axisRect.left()-margin);
  14802. result.setY(axisRect.top()-margin); break; // top left
  14803. case 7: result.setX(axisRect.right()+margin);
  14804. result.setY(axisRect.top()-margin); break; // top right
  14805. case 9: result.setX(axisRect.right()+margin);
  14806. result.setY(axisRect.bottom()+margin); break; // bottom right
  14807. case 3: result.setX(axisRect.left()-margin);
  14808. result.setY(axisRect.bottom()+margin); break; // bottom left
  14809. }
  14810. return result;
  14811. }
  14812. /* inherits documentation from base class */
  14813. QCPRange QCPCurve::getKeyRange(bool &foundRange, SignDomain inSignDomain) const
  14814. {
  14815. QCPRange range;
  14816. bool haveLower = false;
  14817. bool haveUpper = false;
  14818. double current;
  14819. QCPCurveDataMap::const_iterator it = mData->constBegin();
  14820. while (it != mData->constEnd())
  14821. {
  14822. current = it.value().key;
  14823. if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0))
  14824. {
  14825. if (current < range.lower || !haveLower)
  14826. {
  14827. range.lower = current;
  14828. haveLower = true;
  14829. }
  14830. if (current > range.upper || !haveUpper)
  14831. {
  14832. range.upper = current;
  14833. haveUpper = true;
  14834. }
  14835. }
  14836. ++it;
  14837. }
  14838. foundRange = haveLower && haveUpper;
  14839. return range;
  14840. }
  14841. /* inherits documentation from base class */
  14842. QCPRange QCPCurve::getValueRange(bool &foundRange, SignDomain inSignDomain) const
  14843. {
  14844. QCPRange range;
  14845. bool haveLower = false;
  14846. bool haveUpper = false;
  14847. double current;
  14848. QCPCurveDataMap::const_iterator it = mData->constBegin();
  14849. while (it != mData->constEnd())
  14850. {
  14851. current = it.value().value;
  14852. if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0))
  14853. {
  14854. if (current < range.lower || !haveLower)
  14855. {
  14856. range.lower = current;
  14857. haveLower = true;
  14858. }
  14859. if (current > range.upper || !haveUpper)
  14860. {
  14861. range.upper = current;
  14862. haveUpper = true;
  14863. }
  14864. }
  14865. ++it;
  14866. }
  14867. foundRange = haveLower && haveUpper;
  14868. return range;
  14869. }
  14870. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14871. //////////////////// QCPBarData
  14872. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14873. /*! \class QCPBarData
  14874. \brief Holds the data of one single data point (one bar) for QCPBars.
  14875. The container for storing multiple data points is \ref QCPBarDataMap.
  14876. The stored data is:
  14877. \li \a key: coordinate on the key axis of this bar
  14878. \li \a value: height coordinate on the value axis of this bar
  14879. \see QCPBarDataaMap
  14880. */
  14881. /*!
  14882. Constructs a bar data point with key and value set to zero.
  14883. */
  14884. QCPBarData::QCPBarData() :
  14885. key(0),
  14886. value(0)
  14887. {
  14888. }
  14889. /*!
  14890. Constructs a bar data point with the specified \a key and \a value.
  14891. */
  14892. QCPBarData::QCPBarData(double key, double value) :
  14893. key(key),
  14894. value(value)
  14895. {
  14896. }
  14897. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14898. //////////////////// QCPBars
  14899. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14900. /*! \class QCPBars
  14901. \brief A plottable representing a bar chart in a plot.
  14902. \image html QCPBars.png
  14903. To plot data, assign it with the \ref setData or \ref addData functions.
  14904. \section appearance Changing the appearance
  14905. The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush).
  14906. Bar charts are stackable. This means, Two QCPBars plottables can be placed on top of each other
  14907. (see \ref QCPBars::moveAbove). Then, when two bars are at the same key position, they will appear
  14908. stacked.
  14909. \section usage Usage
  14910. Like all data representing objects in QCustomPlot, the QCPBars is a plottable
  14911. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  14912. (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.)
  14913. Usually, you first create an instance:
  14914. \code
  14915. QCPBars *newBars = new QCPBars(customPlot->xAxis, customPlot->yAxis);\endcode
  14916. add it to the customPlot with QCustomPlot::addPlottable:
  14917. \code
  14918. customPlot->addPlottable(newBars);\endcode
  14919. and then modify the properties of the newly created plottable, e.g.:
  14920. \code
  14921. newBars->setName("Country population");
  14922. newBars->setData(xData, yData);\endcode
  14923. */
  14924. /*! \fn QCPBars *QCPBars::barBelow() const
  14925. Returns the bars plottable that is directly below this bars plottable.
  14926. If there is no such plottable, returns 0.
  14927. \see barAbove, moveBelow, moveAbove
  14928. */
  14929. /*! \fn QCPBars *QCPBars::barAbove() const
  14930. Returns the bars plottable that is directly above this bars plottable.
  14931. If there is no such plottable, returns 0.
  14932. \see barBelow, moveBelow, moveAbove
  14933. */
  14934. /*!
  14935. Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  14936. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  14937. the same orientation. If either of these restrictions is violated, a corresponding message is
  14938. printed to the debug output (qDebug), the construction is not aborted, though.
  14939. The constructed QCPBars can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
  14940. then takes ownership of the bar chart.
  14941. */
  14942. QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  14943. QCPAbstractPlottable(keyAxis, valueAxis)
  14944. {
  14945. mData = new QCPBarDataMap;
  14946. mPen.setColor(Qt::blue);
  14947. mPen.setStyle(Qt::SolidLine);
  14948. mBrush.setColor(QColor(40, 50, 255, 30));
  14949. mBrush.setStyle(Qt::SolidPattern);
  14950. mSelectedPen = mPen;
  14951. mSelectedPen.setWidthF(2.5);
  14952. mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen
  14953. mSelectedBrush = mBrush;
  14954. mWidth = 0.75;
  14955. }
  14956. QCPBars::~QCPBars()
  14957. {
  14958. if (mBarBelow || mBarAbove)
  14959. connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking
  14960. delete mData;
  14961. }
  14962. /*!
  14963. Sets the width of the bars in plot (key) coordinates.
  14964. */
  14965. void QCPBars::setWidth(double width)
  14966. {
  14967. mWidth = width;
  14968. }
  14969. /*!
  14970. Replaces the current data with the provided \a data.
  14971. If \a copy is set to true, data points in \a data will only be copied. if false, the plottable
  14972. takes ownership of the passed data and replaces the internal data pointer with it. This is
  14973. significantly faster than copying for large datasets.
  14974. */
  14975. void QCPBars::setData(QCPBarDataMap *data, bool copy)
  14976. {
  14977. if (copy)
  14978. {
  14979. *mData = *data;
  14980. } else
  14981. {
  14982. delete mData;
  14983. mData = data;
  14984. }
  14985. }
  14986. /*! \overload
  14987. Replaces the current data with the provided points in \a key and \a value tuples. The
  14988. provided vectors should have equal length. Else, the number of added points will be the size of
  14989. the smallest vector.
  14990. */
  14991. void QCPBars::setData(const QVector<double> &key, const QVector<double> &value)
  14992. {
  14993. mData->clear();
  14994. int n = key.size();
  14995. n = qMin(n, value.size());
  14996. QCPBarData newData;
  14997. for (int i=0; i<n; ++i)
  14998. {
  14999. newData.key = key[i];
  15000. newData.value = value[i];
  15001. mData->insertMulti(newData.key, newData);
  15002. }
  15003. }
  15004. /*!
  15005. Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear
  15006. below the bars of \a bars. The move target \a bars must use the same key and value axis as this
  15007. plottable.
  15008. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
  15009. has a bars object below itself, this bars object is inserted between the two. If this bars object
  15010. is already between two other bars, the two other bars will be stacked on top of each other after
  15011. the operation.
  15012. To remove this bars plottable from any stacking, set \a bars to 0.
  15013. \see moveBelow, barAbove, barBelow
  15014. */
  15015. void QCPBars::moveBelow(QCPBars *bars)
  15016. {
  15017. if (bars == this) return;
  15018. if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
  15019. {
  15020. qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
  15021. return;
  15022. }
  15023. // remove from stacking:
  15024. connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
  15025. // if new bar given, insert this bar below it:
  15026. if (bars)
  15027. {
  15028. if (bars->mBarBelow)
  15029. connectBars(bars->mBarBelow.data(), this);
  15030. connectBars(this, bars);
  15031. }
  15032. }
  15033. /*!
  15034. Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear
  15035. above the bars of \a bars. The move target \a bars must use the same key and value axis as this
  15036. plottable.
  15037. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
  15038. has a bars object below itself, this bars object is inserted between the two. If this bars object
  15039. is already between two other bars, the two other bars will be stacked on top of each other after
  15040. the operation.
  15041. To remove this bars plottable from any stacking, set \a bars to 0.
  15042. \see moveBelow, barBelow, barAbove
  15043. */
  15044. void QCPBars::moveAbove(QCPBars *bars)
  15045. {
  15046. if (bars == this) return;
  15047. if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
  15048. {
  15049. qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
  15050. return;
  15051. }
  15052. // remove from stacking:
  15053. connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
  15054. // if new bar given, insert this bar above it:
  15055. if (bars)
  15056. {
  15057. if (bars->mBarAbove)
  15058. connectBars(this, bars->mBarAbove.data());
  15059. connectBars(bars, this);
  15060. }
  15061. }
  15062. /*!
  15063. Adds the provided data points in \a dataMap to the current data.
  15064. \see removeData
  15065. */
  15066. void QCPBars::addData(const QCPBarDataMap &dataMap)
  15067. {
  15068. mData->unite(dataMap);
  15069. }
  15070. /*! \overload
  15071. Adds the provided single data point in \a data to the current data.
  15072. \see removeData
  15073. */
  15074. void QCPBars::addData(const QCPBarData &data)
  15075. {
  15076. mData->insertMulti(data.key, data);
  15077. }
  15078. /*! \overload
  15079. Adds the provided single data point as \a key and \a value tuple to the current data
  15080. \see removeData
  15081. */
  15082. void QCPBars::addData(double key, double value)
  15083. {
  15084. QCPBarData newData;
  15085. newData.key = key;
  15086. newData.value = value;
  15087. mData->insertMulti(newData.key, newData);
  15088. }
  15089. /*! \overload
  15090. Adds the provided data points as \a key and \a value tuples to the current data.
  15091. \see removeData
  15092. */
  15093. void QCPBars::addData(const QVector<double> &keys, const QVector<double> &values)
  15094. {
  15095. int n = keys.size();
  15096. n = qMin(n, values.size());
  15097. QCPBarData newData;
  15098. for (int i=0; i<n; ++i)
  15099. {
  15100. newData.key = keys[i];
  15101. newData.value = values[i];
  15102. mData->insertMulti(newData.key, newData);
  15103. }
  15104. }
  15105. /*!
  15106. Removes all data points with key smaller than \a key.
  15107. \see addData, clearData
  15108. */
  15109. void QCPBars::removeDataBefore(double key)
  15110. {
  15111. QCPBarDataMap::iterator it = mData->begin();
  15112. while (it != mData->end() && it.key() < key)
  15113. it = mData->erase(it);
  15114. }
  15115. /*!
  15116. Removes all data points with key greater than \a key.
  15117. \see addData, clearData
  15118. */
  15119. void QCPBars::removeDataAfter(double key)
  15120. {
  15121. if (mData->isEmpty()) return;
  15122. QCPBarDataMap::iterator it = mData->upperBound(key);
  15123. while (it != mData->end())
  15124. it = mData->erase(it);
  15125. }
  15126. /*!
  15127. Removes all data points with key between \a fromKey and \a toKey. if \a fromKey is
  15128. greater or equal to \a toKey, the function does nothing. To remove a single data point with known
  15129. key, use \ref removeData(double key).
  15130. \see addData, clearData
  15131. */
  15132. void QCPBars::removeData(double fromKey, double toKey)
  15133. {
  15134. if (fromKey >= toKey || mData->isEmpty()) return;
  15135. QCPBarDataMap::iterator it = mData->upperBound(fromKey);
  15136. QCPBarDataMap::iterator itEnd = mData->upperBound(toKey);
  15137. while (it != itEnd)
  15138. it = mData->erase(it);
  15139. }
  15140. /*! \overload
  15141. Removes a single data point at \a key. If the position is not known with absolute precision,
  15142. consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval
  15143. around the suspected position, depeding on the precision with which the key is known.
  15144. \see addData, clearData
  15145. */
  15146. void QCPBars::removeData(double key)
  15147. {
  15148. mData->remove(key);
  15149. }
  15150. /*!
  15151. Removes all data points.
  15152. \see removeData, removeDataAfter, removeDataBefore
  15153. */
  15154. void QCPBars::clearData()
  15155. {
  15156. mData->clear();
  15157. }
  15158. /* inherits documentation from base class */
  15159. double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  15160. {
  15161. Q_UNUSED(details)
  15162. if (onlySelectable && !mSelectable)
  15163. return -1;
  15164. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  15165. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
  15166. {
  15167. QCPBarDataMap::ConstIterator it;
  15168. double posKey, posValue;
  15169. pixelsToCoords(pos, posKey, posValue);
  15170. for (it = mData->constBegin(); it != mData->constEnd(); ++it)
  15171. {
  15172. double baseValue = getBaseValue(it.key(), it.value().value >=0);
  15173. QCPRange keyRange(it.key()-mWidth*0.5, it.key()+mWidth*0.5);
  15174. QCPRange valueRange(baseValue, baseValue+it.value().value);
  15175. if (keyRange.contains(posKey) && valueRange.contains(posValue))
  15176. return mParentPlot->selectionTolerance()*0.99;
  15177. }
  15178. }
  15179. return -1;
  15180. }
  15181. /* inherits documentation from base class */
  15182. void QCPBars::draw(QCPPainter *painter)
  15183. {
  15184. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  15185. if (mData->isEmpty()) return;
  15186. QCPBarDataMap::const_iterator it;
  15187. for (it = mData->constBegin(); it != mData->constEnd(); ++it)
  15188. {
  15189. // skip bar if not visible in key axis range:
  15190. if (it.key()+mWidth*0.5 < mKeyAxis.data()->range().lower || it.key()-mWidth*0.5 > mKeyAxis.data()->range().upper)
  15191. continue;
  15192. // check data validity if flag set:
  15193. #ifdef QCUSTOMPLOT_CHECK_DATA
  15194. if (QCP::isInvalidData(it.value().key, it.value().value))
  15195. qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "of drawn range invalid." << "Plottable name:" << name();
  15196. #endif
  15197. QPolygonF barPolygon = getBarPolygon(it.key(), it.value().value);
  15198. // draw bar fill:
  15199. if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0)
  15200. {
  15201. applyFillAntialiasingHint(painter);
  15202. painter->setPen(Qt::NoPen);
  15203. painter->setBrush(mainBrush());
  15204. painter->drawPolygon(barPolygon);
  15205. }
  15206. // draw bar line:
  15207. if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)
  15208. {
  15209. applyDefaultAntialiasingHint(painter);
  15210. painter->setPen(mainPen());
  15211. painter->setBrush(Qt::NoBrush);
  15212. painter->drawPolyline(barPolygon);
  15213. }
  15214. }
  15215. }
  15216. /* inherits documentation from base class */
  15217. void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  15218. {
  15219. // draw filled rect:
  15220. applyDefaultAntialiasingHint(painter);
  15221. painter->setBrush(mBrush);
  15222. painter->setPen(mPen);
  15223. QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
  15224. r.moveCenter(rect.center());
  15225. painter->drawRect(r);
  15226. }
  15227. /*! \internal
  15228. Returns the polygon of a single bar with \a key and \a value. The Polygon is open at the bottom
  15229. and shifted according to the bar stacking (see \ref moveAbove).
  15230. */
  15231. QPolygonF QCPBars::getBarPolygon(double key, double value) const
  15232. {
  15233. QPolygonF result;
  15234. double baseValue = getBaseValue(key, value >= 0);
  15235. result << coordsToPixels(key-mWidth*0.5, baseValue);
  15236. result << coordsToPixels(key-mWidth*0.5, baseValue+value);
  15237. result << coordsToPixels(key+mWidth*0.5, baseValue+value);
  15238. result << coordsToPixels(key+mWidth*0.5, baseValue);
  15239. return result;
  15240. }
  15241. /*! \internal
  15242. This function is called to find at which value to start drawing the base of a bar at \a key, when
  15243. it is stacked on top of another QCPBars (e.g. with \ref moveAbove).
  15244. positive and negative bars are separated per stack (positive are stacked above 0-value upwards,
  15245. negative are stacked below 0-value downwards). This can be indicated with \a positive. So if the
  15246. bar for which we need the base value is negative, set \a positive to false.
  15247. */
  15248. double QCPBars::getBaseValue(double key, bool positive) const
  15249. {
  15250. if (mBarBelow)
  15251. {
  15252. double max = 0;
  15253. // find bars of mBarBelow that are approximately at key and find largest one:
  15254. QCPBarDataMap::const_iterator it = mBarBelow.data()->mData->lowerBound(key-mWidth*0.1);
  15255. QCPBarDataMap::const_iterator itEnd = mBarBelow.data()->mData->upperBound(key+mWidth*0.1);
  15256. while (it != itEnd)
  15257. {
  15258. if ((positive && it.value().value > max) ||
  15259. (!positive && it.value().value < max))
  15260. max = it.value().value;
  15261. ++it;
  15262. }
  15263. // recurse down the bar-stack to find the total height:
  15264. return max + mBarBelow.data()->getBaseValue(key, positive);
  15265. } else
  15266. return 0;
  15267. }
  15268. /*! \internal
  15269. Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties.
  15270. The bar(s) currently below lower and upper will become disconnected to lower/upper.
  15271. If lower is zero, upper will be disconnected at the bottom.
  15272. If upper is zero, lower will be disconnected at the top.
  15273. */
  15274. void QCPBars::connectBars(QCPBars *lower, QCPBars *upper)
  15275. {
  15276. if (!lower && !upper) return;
  15277. if (!lower) // disconnect upper at bottom
  15278. {
  15279. // disconnect old bar below upper:
  15280. if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
  15281. upper->mBarBelow.data()->mBarAbove = 0;
  15282. upper->mBarBelow = 0;
  15283. } else if (!upper) // disconnect lower at top
  15284. {
  15285. // disconnect old bar above lower:
  15286. if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
  15287. lower->mBarAbove.data()->mBarBelow = 0;
  15288. lower->mBarAbove = 0;
  15289. } else // connect lower and upper
  15290. {
  15291. // disconnect old bar above lower:
  15292. if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
  15293. lower->mBarAbove.data()->mBarBelow = 0;
  15294. // disconnect old bar below upper:
  15295. if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
  15296. upper->mBarBelow.data()->mBarAbove = 0;
  15297. lower->mBarAbove = upper;
  15298. upper->mBarBelow = lower;
  15299. }
  15300. }
  15301. /* inherits documentation from base class */
  15302. QCPRange QCPBars::getKeyRange(bool &foundRange, SignDomain inSignDomain) const
  15303. {
  15304. QCPRange range;
  15305. bool haveLower = false;
  15306. bool haveUpper = false;
  15307. double current;
  15308. double barWidthHalf = mWidth*0.5;
  15309. QCPBarDataMap::const_iterator it = mData->constBegin();
  15310. while (it != mData->constEnd())
  15311. {
  15312. current = it.value().key;
  15313. if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current+barWidthHalf < 0) || (inSignDomain == sdPositive && current-barWidthHalf > 0))
  15314. {
  15315. if (current-barWidthHalf < range.lower || !haveLower)
  15316. {
  15317. range.lower = current-barWidthHalf;
  15318. haveLower = true;
  15319. }
  15320. if (current+barWidthHalf > range.upper || !haveUpper)
  15321. {
  15322. range.upper = current+barWidthHalf;
  15323. haveUpper = true;
  15324. }
  15325. }
  15326. ++it;
  15327. }
  15328. foundRange = haveLower && haveUpper;
  15329. return range;
  15330. }
  15331. /* inherits documentation from base class */
  15332. QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const
  15333. {
  15334. QCPRange range;
  15335. bool haveLower = true; // set to true, because 0 should always be visible in bar charts
  15336. bool haveUpper = true; // set to true, because 0 should always be visible in bar charts
  15337. double current;
  15338. QCPBarDataMap::const_iterator it = mData->constBegin();
  15339. while (it != mData->constEnd())
  15340. {
  15341. current = it.value().value + getBaseValue(it.value().key, it.value().value >= 0);
  15342. if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0))
  15343. {
  15344. if (current < range.lower || !haveLower)
  15345. {
  15346. range.lower = current;
  15347. haveLower = true;
  15348. }
  15349. if (current > range.upper || !haveUpper)
  15350. {
  15351. range.upper = current;
  15352. haveUpper = true;
  15353. }
  15354. }
  15355. ++it;
  15356. }
  15357. foundRange = true; // return true because bar charts always have the 0-line visible
  15358. return range;
  15359. }
  15360. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15361. //////////////////// QCPStatisticalBox
  15362. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15363. /*! \class QCPStatisticalBox
  15364. \brief A plottable representing a single statistical box in a plot.
  15365. \image html QCPStatisticalBox.png
  15366. To plot data, assign it with the individual parameter functions or use \ref setData to set all
  15367. parameters at once. The individual functions are:
  15368. \li \ref setMinimum
  15369. \li \ref setLowerQuartile
  15370. \li \ref setMedian
  15371. \li \ref setUpperQuartile
  15372. \li \ref setMaximum
  15373. Additionally you can define a list of outliers, drawn as scatter datapoints:
  15374. \li \ref setOutliers
  15375. \section appearance Changing the appearance
  15376. The appearance of the box itself is controlled via \ref setPen and \ref setBrush. You may change
  15377. the width of the box with \ref setWidth in plot coordinates (not pixels).
  15378. Analog functions exist for the minimum/maximum-whiskers: \ref setWhiskerPen, \ref
  15379. setWhiskerBarPen, \ref setWhiskerWidth. The whisker width is the width of the bar at the top
  15380. (maximum) and bottom (minimum).
  15381. The median indicator line has its own pen, \ref setMedianPen.
  15382. If the whisker backbone pen is changed, make sure to set the capStyle to Qt::FlatCap. Else, the
  15383. backbone line might exceed the whisker bars by a few pixels due to the pen cap being not
  15384. perfectly flat.
  15385. The Outlier data points are drawn as normal scatter points. Their look can be controlled with
  15386. \ref setOutlierStyle
  15387. \section usage Usage
  15388. Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable
  15389. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  15390. (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.)
  15391. Usually, you first create an instance:
  15392. \code
  15393. QCPStatisticalBox *newBox = new QCPStatisticalBox(customPlot->xAxis, customPlot->yAxis);\endcode
  15394. add it to the customPlot with QCustomPlot::addPlottable:
  15395. \code
  15396. customPlot->addPlottable(newBox);\endcode
  15397. and then modify the properties of the newly created plottable, e.g.:
  15398. \code
  15399. newBox->setName("Measurement Series 1");
  15400. newBox->setData(1, 3, 4, 5, 7);
  15401. newBox->setOutliers(QVector<double>() << 0.5 << 0.64 << 7.2 << 7.42);\endcode
  15402. */
  15403. /*!
  15404. Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its
  15405. value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and
  15406. not have the same orientation. If either of these restrictions is violated, a corresponding
  15407. message is printed to the debug output (qDebug), the construction is not aborted, though.
  15408. The constructed statistical box can be added to the plot with QCustomPlot::addPlottable,
  15409. QCustomPlot then takes ownership of the statistical box.
  15410. */
  15411. QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  15412. QCPAbstractPlottable(keyAxis, valueAxis),
  15413. mKey(0),
  15414. mMinimum(0),
  15415. mLowerQuartile(0),
  15416. mMedian(0),
  15417. mUpperQuartile(0),
  15418. mMaximum(0)
  15419. {
  15420. setOutlierStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, 6));
  15421. setWhiskerWidth(0.2);
  15422. setWidth(0.5);
  15423. setPen(QPen(Qt::black));
  15424. setSelectedPen(QPen(Qt::blue, 2.5));
  15425. setMedianPen(QPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap));
  15426. setWhiskerPen(QPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap));
  15427. setWhiskerBarPen(QPen(Qt::black));
  15428. setBrush(Qt::NoBrush);
  15429. setSelectedBrush(Qt::NoBrush);
  15430. }
  15431. /*!
  15432. Sets the key coordinate of the statistical box.
  15433. */
  15434. void QCPStatisticalBox::setKey(double key)
  15435. {
  15436. mKey = key;
  15437. }
  15438. /*!
  15439. Sets the parameter "minimum" of the statistical box plot. This is the position of the lower
  15440. whisker, typically the minimum measurement of the sample that's not considered an outlier.
  15441. \see setMaximum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth
  15442. */
  15443. void QCPStatisticalBox::setMinimum(double value)
  15444. {
  15445. mMinimum = value;
  15446. }
  15447. /*!
  15448. Sets the parameter "lower Quartile" of the statistical box plot. This is the lower end of the
  15449. box. The lower and the upper quartiles are the two statistical quartiles around the median of the
  15450. sample, they contain 50% of the sample data.
  15451. \see setUpperQuartile, setPen, setBrush, setWidth
  15452. */
  15453. void QCPStatisticalBox::setLowerQuartile(double value)
  15454. {
  15455. mLowerQuartile = value;
  15456. }
  15457. /*!
  15458. Sets the parameter "median" of the statistical box plot. This is the value of the median mark
  15459. inside the quartile box. The median separates the sample data in half (50% of the sample data is
  15460. below/above the median).
  15461. \see setMedianPen
  15462. */
  15463. void QCPStatisticalBox::setMedian(double value)
  15464. {
  15465. mMedian = value;
  15466. }
  15467. /*!
  15468. Sets the parameter "upper Quartile" of the statistical box plot. This is the upper end of the
  15469. box. The lower and the upper quartiles are the two statistical quartiles around the median of the
  15470. sample, they contain 50% of the sample data.
  15471. \see setLowerQuartile, setPen, setBrush, setWidth
  15472. */
  15473. void QCPStatisticalBox::setUpperQuartile(double value)
  15474. {
  15475. mUpperQuartile = value;
  15476. }
  15477. /*!
  15478. Sets the parameter "maximum" of the statistical box plot. This is the position of the upper
  15479. whisker, typically the maximum measurement of the sample that's not considered an outlier.
  15480. \see setMinimum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth
  15481. */
  15482. void QCPStatisticalBox::setMaximum(double value)
  15483. {
  15484. mMaximum = value;
  15485. }
  15486. /*!
  15487. Sets a vector of outlier values that will be drawn as scatters. Any data points in the sample
  15488. that are not within the whiskers (\ref setMinimum, \ref setMaximum) should be considered outliers
  15489. and displayed as such.
  15490. \see setOutlierStyle
  15491. */
  15492. void QCPStatisticalBox::setOutliers(const QVector<double> &values)
  15493. {
  15494. mOutliers = values;
  15495. }
  15496. /*!
  15497. Sets all parameters of the statistical box plot at once.
  15498. \see setKey, setMinimum, setLowerQuartile, setMedian, setUpperQuartile, setMaximum
  15499. */
  15500. void QCPStatisticalBox::setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum)
  15501. {
  15502. setKey(key);
  15503. setMinimum(minimum);
  15504. setLowerQuartile(lowerQuartile);
  15505. setMedian(median);
  15506. setUpperQuartile(upperQuartile);
  15507. setMaximum(maximum);
  15508. }
  15509. /*!
  15510. Sets the width of the box in key coordinates.
  15511. \see setWhiskerWidth
  15512. */
  15513. void QCPStatisticalBox::setWidth(double width)
  15514. {
  15515. mWidth = width;
  15516. }
  15517. /*!
  15518. Sets the width of the whiskers (\ref setMinimum, \ref setMaximum) in key coordinates.
  15519. \see setWidth
  15520. */
  15521. void QCPStatisticalBox::setWhiskerWidth(double width)
  15522. {
  15523. mWhiskerWidth = width;
  15524. }
  15525. /*!
  15526. Sets the pen used for drawing the whisker backbone (That's the line parallel to the value axis).
  15527. Make sure to set the \a pen capStyle to Qt::FlatCap to prevent the whisker backbone from reaching
  15528. a few pixels past the whisker bars, when using a non-zero pen width.
  15529. \see setWhiskerBarPen
  15530. */
  15531. void QCPStatisticalBox::setWhiskerPen(const QPen &pen)
  15532. {
  15533. mWhiskerPen = pen;
  15534. }
  15535. /*!
  15536. Sets the pen used for drawing the whisker bars (Those are the lines parallel to the key axis at
  15537. each end of the whisker backbone).
  15538. \see setWhiskerPen
  15539. */
  15540. void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen)
  15541. {
  15542. mWhiskerBarPen = pen;
  15543. }
  15544. /*!
  15545. Sets the pen used for drawing the median indicator line inside the statistical box.
  15546. */
  15547. void QCPStatisticalBox::setMedianPen(const QPen &pen)
  15548. {
  15549. mMedianPen = pen;
  15550. }
  15551. /*!
  15552. Sets the appearance of the outlier data points.
  15553. \see setOutliers
  15554. */
  15555. void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style)
  15556. {
  15557. mOutlierStyle = style;
  15558. }
  15559. /* inherits documentation from base class */
  15560. void QCPStatisticalBox::clearData()
  15561. {
  15562. setOutliers(QVector<double>());
  15563. setKey(0);
  15564. setMinimum(0);
  15565. setLowerQuartile(0);
  15566. setMedian(0);
  15567. setUpperQuartile(0);
  15568. setMaximum(0);
  15569. }
  15570. /* inherits documentation from base class */
  15571. double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  15572. {
  15573. Q_UNUSED(details)
  15574. if (onlySelectable && !mSelectable)
  15575. return -1;
  15576. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  15577. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
  15578. {
  15579. double posKey, posValue;
  15580. pixelsToCoords(pos, posKey, posValue);
  15581. // quartile box:
  15582. QCPRange keyRange(mKey-mWidth*0.5, mKey+mWidth*0.5);
  15583. QCPRange valueRange(mLowerQuartile, mUpperQuartile);
  15584. if (keyRange.contains(posKey) && valueRange.contains(posValue))
  15585. return mParentPlot->selectionTolerance()*0.99;
  15586. // min/max whiskers:
  15587. if (QCPRange(mMinimum, mMaximum).contains(posValue))
  15588. return qAbs(mKeyAxis.data()->coordToPixel(mKey)-mKeyAxis.data()->coordToPixel(posKey));
  15589. }
  15590. return -1;
  15591. }
  15592. /* inherits documentation from base class */
  15593. void QCPStatisticalBox::draw(QCPPainter *painter)
  15594. {
  15595. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  15596. // check data validity if flag set:
  15597. #ifdef QCUSTOMPLOT_CHECK_DATA
  15598. if (QCP::isInvalidData(mKey, mMedian) ||
  15599. QCP::isInvalidData(mLowerQuartile, mUpperQuartile) ||
  15600. QCP::isInvalidData(mMinimum, mMaximum))
  15601. qDebug() << Q_FUNC_INFO << "Data point at" << mKey << "of drawn range has invalid data." << "Plottable name:" << name();
  15602. for (int i=0; i<mOutliers.size(); ++i)
  15603. if (QCP::isInvalidData(mOutliers.at(i)))
  15604. qDebug() << Q_FUNC_INFO << "Data point outlier at" << mKey << "of drawn range invalid." << "Plottable name:" << name();
  15605. #endif
  15606. QRectF quartileBox;
  15607. drawQuartileBox(painter, &quartileBox);
  15608. painter->save();
  15609. painter->setClipRect(quartileBox, Qt::IntersectClip);
  15610. drawMedian(painter);
  15611. painter->restore();
  15612. drawWhiskers(painter);
  15613. drawOutliers(painter);
  15614. }
  15615. /* inherits documentation from base class */
  15616. void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  15617. {
  15618. // draw filled rect:
  15619. applyDefaultAntialiasingHint(painter);
  15620. painter->setPen(mPen);
  15621. painter->setBrush(mBrush);
  15622. QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
  15623. r.moveCenter(rect.center());
  15624. painter->drawRect(r);
  15625. }
  15626. /*! \internal
  15627. Draws the quartile box. \a box is an output parameter that returns the quartile box (in pixel
  15628. coordinates) which is used to set the clip rect of the painter before calling \ref drawMedian (so
  15629. the median doesn't draw outside the quartile box).
  15630. */
  15631. void QCPStatisticalBox::drawQuartileBox(QCPPainter *painter, QRectF *quartileBox) const
  15632. {
  15633. QRectF box;
  15634. box.setTopLeft(coordsToPixels(mKey-mWidth*0.5, mUpperQuartile));
  15635. box.setBottomRight(coordsToPixels(mKey+mWidth*0.5, mLowerQuartile));
  15636. applyDefaultAntialiasingHint(painter);
  15637. painter->setPen(mainPen());
  15638. painter->setBrush(mainBrush());
  15639. painter->drawRect(box);
  15640. if (quartileBox)
  15641. *quartileBox = box;
  15642. }
  15643. /*! \internal
  15644. Draws the median line inside the quartile box.
  15645. */
  15646. void QCPStatisticalBox::drawMedian(QCPPainter *painter) const
  15647. {
  15648. QLineF medianLine;
  15649. medianLine.setP1(coordsToPixels(mKey-mWidth*0.5, mMedian));
  15650. medianLine.setP2(coordsToPixels(mKey+mWidth*0.5, mMedian));
  15651. applyDefaultAntialiasingHint(painter);
  15652. painter->setPen(mMedianPen);
  15653. painter->drawLine(medianLine);
  15654. }
  15655. /*! \internal
  15656. Draws both whisker backbones and bars.
  15657. */
  15658. void QCPStatisticalBox::drawWhiskers(QCPPainter *painter) const
  15659. {
  15660. QLineF backboneMin, backboneMax, barMin, barMax;
  15661. backboneMax.setPoints(coordsToPixels(mKey, mUpperQuartile), coordsToPixels(mKey, mMaximum));
  15662. backboneMin.setPoints(coordsToPixels(mKey, mLowerQuartile), coordsToPixels(mKey, mMinimum));
  15663. barMax.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMaximum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMaximum));
  15664. barMin.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMinimum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMinimum));
  15665. applyErrorBarsAntialiasingHint(painter);
  15666. painter->setPen(mWhiskerPen);
  15667. painter->drawLine(backboneMin);
  15668. painter->drawLine(backboneMax);
  15669. painter->setPen(mWhiskerBarPen);
  15670. painter->drawLine(barMin);
  15671. painter->drawLine(barMax);
  15672. }
  15673. /*! \internal
  15674. Draws the outlier scatter points.
  15675. */
  15676. void QCPStatisticalBox::drawOutliers(QCPPainter *painter) const
  15677. {
  15678. applyScattersAntialiasingHint(painter);
  15679. mOutlierStyle.applyTo(painter, mPen);
  15680. for (int i=0; i<mOutliers.size(); ++i)
  15681. mOutlierStyle.drawShape(painter, coordsToPixels(mKey, mOutliers.at(i)));
  15682. }
  15683. /* inherits documentation from base class */
  15684. QCPRange QCPStatisticalBox::getKeyRange(bool &foundRange, SignDomain inSignDomain) const
  15685. {
  15686. foundRange = true;
  15687. if (inSignDomain == sdBoth)
  15688. {
  15689. return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5);
  15690. } else if (inSignDomain == sdNegative)
  15691. {
  15692. if (mKey+mWidth*0.5 < 0)
  15693. return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5);
  15694. else if (mKey < 0)
  15695. return QCPRange(mKey-mWidth*0.5, mKey);
  15696. else
  15697. {
  15698. foundRange = false;
  15699. return QCPRange();
  15700. }
  15701. } else if (inSignDomain == sdPositive)
  15702. {
  15703. if (mKey-mWidth*0.5 > 0)
  15704. return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5);
  15705. else if (mKey > 0)
  15706. return QCPRange(mKey, mKey+mWidth*0.5);
  15707. else
  15708. {
  15709. foundRange = false;
  15710. return QCPRange();
  15711. }
  15712. }
  15713. foundRange = false;
  15714. return QCPRange();
  15715. }
  15716. /* inherits documentation from base class */
  15717. QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, SignDomain inSignDomain) const
  15718. {
  15719. QVector<double> values; // values that must be considered (i.e. all outliers and the five box-parameters)
  15720. values.reserve(mOutliers.size() + 5);
  15721. values << mMaximum << mUpperQuartile << mMedian << mLowerQuartile << mMinimum;
  15722. values << mOutliers;
  15723. // go through values and find the ones in legal range:
  15724. bool haveUpper = false;
  15725. bool haveLower = false;
  15726. double upper = 0;
  15727. double lower = 0;
  15728. for (int i=0; i<values.size(); ++i)
  15729. {
  15730. if ((inSignDomain == sdNegative && values.at(i) < 0) ||
  15731. (inSignDomain == sdPositive && values.at(i) > 0) ||
  15732. (inSignDomain == sdBoth))
  15733. {
  15734. if (values.at(i) > upper || !haveUpper)
  15735. {
  15736. upper = values.at(i);
  15737. haveUpper = true;
  15738. }
  15739. if (values.at(i) < lower || !haveLower)
  15740. {
  15741. lower = values.at(i);
  15742. haveLower = true;
  15743. }
  15744. }
  15745. }
  15746. // return the bounds if we found some sensible values:
  15747. if (haveLower && haveUpper)
  15748. {
  15749. foundRange = true;
  15750. return QCPRange(lower, upper);
  15751. } else // might happen if all values are in other sign domain
  15752. {
  15753. foundRange = false;
  15754. return QCPRange();
  15755. }
  15756. }
  15757. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15758. //////////////////// QCPColorMapData
  15759. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15760. /*! \class QCPColorMapData
  15761. \brief Holds the two-dimensional data of a QCPColorMap plottable.
  15762. This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref
  15763. QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a
  15764. color, depending on the value.
  15765. The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize).
  15766. Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref
  15767. setKeyRange, \ref setValueRange).
  15768. The data cells can be accessed in two ways: They can be directly addressed by an integer index
  15769. with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot
  15770. coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are
  15771. provided by the functions \ref coordToCell and \ref cellToCoord.
  15772. This class also buffers the minimum and maximum values that are in the data set, to provide
  15773. QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value
  15774. that is greater than the current maximum increases this maximum to the new value. However,
  15775. setting the cell that currently holds the maximum value to a smaller value doesn't decrease the
  15776. maximum again, because finding the true new maximum would require going through the entire data
  15777. array, which might be time consuming. The same holds for the data minimum. This functionality is
  15778. given by \ref recalculateDataBounds, such that you can decide when it is sensible to find the
  15779. true current minimum and maximum. The method QCPColorMap::rescaleDataRange offers a convenience
  15780. parameter \a recalculateDataBounds which may be set to true to automatically call \ref
  15781. recalculateDataBounds internally.
  15782. */
  15783. /* start of documentation of inline functions */
  15784. /*! \fn bool QCPColorMapData::isEmpty() const
  15785. Returns whether this instance carries no data. This is equivalent to having a size where at least
  15786. one of the dimensions is 0 (see \ref setSize).
  15787. */
  15788. /* end of documentation of inline functions */
  15789. /*!
  15790. Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction
  15791. and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap
  15792. at the coordinates \a keyRange and \a valueRange.
  15793. \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange
  15794. */
  15795. QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) :
  15796. mKeySize(0),
  15797. mValueSize(0),
  15798. mKeyRange(keyRange),
  15799. mValueRange(valueRange),
  15800. mIsEmpty(true),
  15801. mData(0),
  15802. mDataModified(true)
  15803. {
  15804. setSize(keySize, valueSize);
  15805. fill(0);
  15806. }
  15807. QCPColorMapData::~QCPColorMapData()
  15808. {
  15809. if (mData)
  15810. delete[] mData;
  15811. }
  15812. /*!
  15813. Constructs a new QCPColorMapData instance copying the data and range of \a other.
  15814. */
  15815. QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) :
  15816. mKeySize(0),
  15817. mValueSize(0),
  15818. mIsEmpty(true),
  15819. mData(0),
  15820. mDataModified(true)
  15821. {
  15822. *this = other;
  15823. }
  15824. /*!
  15825. Overwrites this color map data instance with the data stored in \a other.
  15826. */
  15827. QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other)
  15828. {
  15829. if (&other != this)
  15830. {
  15831. const int keySize = other.keySize();
  15832. const int valueSize = other.valueSize();
  15833. setSize(keySize, valueSize);
  15834. setRange(other.keyRange(), other.valueRange());
  15835. if (!mIsEmpty)
  15836. memcpy(mData, other.mData, sizeof(mData[0])*keySize*valueSize);
  15837. mDataBounds = other.mDataBounds;
  15838. mDataModified = true;
  15839. }
  15840. return *this;
  15841. }
  15842. /* undocumented getter */
  15843. double QCPColorMapData::data(double key, double value)
  15844. {
  15845. int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5;
  15846. int valueCell = (1.0-(value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower))*(mValueSize-1)+0.5;
  15847. if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
  15848. return mData[valueCell*mKeySize + keyCell];
  15849. else
  15850. return 0;
  15851. }
  15852. /* undocumented getter */
  15853. double QCPColorMapData::cell(int keyIndex, int valueIndex)
  15854. {
  15855. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  15856. return mData[valueIndex*mKeySize + keyIndex];
  15857. else
  15858. return 0;
  15859. }
  15860. /*!
  15861. Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in
  15862. the value dimension.
  15863. The current data is discarded and the map cells are set to 0, unless the map had already the
  15864. requested size.
  15865. Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref
  15866. isEmpty returns true.
  15867. \see setRange, setKeySize, setValueSize
  15868. */
  15869. void QCPColorMapData::setSize(int keySize, int valueSize)
  15870. {
  15871. if (keySize != mKeySize || valueSize != mValueSize)
  15872. {
  15873. mKeySize = keySize;
  15874. mValueSize = valueSize;
  15875. if (mData)
  15876. delete[] mData;
  15877. mIsEmpty = mKeySize == 0 || mValueSize == 0;
  15878. if (!mIsEmpty)
  15879. {
  15880. #ifdef __EXCEPTIONS
  15881. try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message
  15882. #endif
  15883. mData = new double[mKeySize*mValueSize];
  15884. #ifdef __EXCEPTIONS
  15885. } catch (...) { mData = 0; }
  15886. #endif
  15887. if (mData)
  15888. fill(0);
  15889. else
  15890. qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize;
  15891. } else
  15892. mData = 0;
  15893. mDataModified = true;
  15894. }
  15895. }
  15896. /*!
  15897. Resizes the data array to have \a keySize cells in the key dimension.
  15898. The current data is discarded and the map cells are set to 0, unless the map had already the
  15899. requested size.
  15900. Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true.
  15901. \see setKeyRange, setSize, setValueSize
  15902. */
  15903. void QCPColorMapData::setKeySize(int keySize)
  15904. {
  15905. setSize(keySize, mValueSize);
  15906. }
  15907. /*!
  15908. Resizes the data array to have \a valueSize cells in the value dimension.
  15909. The current data is discarded and the map cells are set to 0, unless the map had already the
  15910. requested size.
  15911. Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true.
  15912. \see setValueRange, setSize, setKeySize
  15913. */
  15914. void QCPColorMapData::setValueSize(int valueSize)
  15915. {
  15916. setSize(mKeySize, valueSize);
  15917. }
  15918. /*!
  15919. Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area
  15920. covered by the color map in plot coordinates.
  15921. The outer cells will be centered on the range boundaries given to this function. For example, if
  15922. the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
  15923. be cells centered on the key coordinates 2, 2.5 and 3.
  15924. \see setSize
  15925. */
  15926. void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange)
  15927. {
  15928. setKeyRange(keyRange);
  15929. setValueRange(valueRange);
  15930. }
  15931. /*!
  15932. Sets the coordinate range the data shall be distributed over in the key dimension. Together with
  15933. the value range, This defines the rectangular area covered by the color map in plot coordinates.
  15934. The outer cells will be centered on the range boundaries given to this function. For example, if
  15935. the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
  15936. be cells centered on the key coordinates 2, 2.5 and 3.
  15937. \see setRange, setValueRange, setSize
  15938. */
  15939. void QCPColorMapData::setKeyRange(const QCPRange &keyRange)
  15940. {
  15941. mKeyRange = keyRange;
  15942. }
  15943. /*!
  15944. Sets the coordinate range the data shall be distributed over in the value dimension. Together with
  15945. the key range, This defines the rectangular area covered by the color map in plot coordinates.
  15946. The outer cells will be centered on the range boundaries given to this function. For example, if
  15947. the value size (\ref setValueSize) is 3 and \a valueRange is set to <tt>QCPRange(2, 3)</tt> there
  15948. will be cells centered on the value coordinates 2, 2.5 and 3.
  15949. \see setRange, setKeyRange, setSize
  15950. */
  15951. void QCPColorMapData::setValueRange(const QCPRange &valueRange)
  15952. {
  15953. mValueRange = valueRange;
  15954. }
  15955. /*!
  15956. Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a
  15957. z.
  15958. \see setCell, setRange
  15959. */
  15960. void QCPColorMapData::setData(double key, double value, double z)
  15961. {
  15962. int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5;
  15963. int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5;
  15964. if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
  15965. {
  15966. mData[valueCell*mKeySize + keyCell] = z;
  15967. if (z < mDataBounds.lower)
  15968. mDataBounds.lower = z;
  15969. if (z > mDataBounds.upper)
  15970. mDataBounds.upper = z;
  15971. mDataModified = true;
  15972. }
  15973. }
  15974. /*!
  15975. Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices
  15976. enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see
  15977. \ref setSize).
  15978. In the standard plot configuration (horizontal key axis and vertical value axis, both not
  15979. range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with
  15980. indices (keySize-1, valueSize-1) is in the top right corner of the color map.
  15981. \see setData, setSize
  15982. */
  15983. void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z)
  15984. {
  15985. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  15986. {
  15987. mData[valueIndex*mKeySize + keyIndex] = z;
  15988. if (z < mDataBounds.lower)
  15989. mDataBounds.lower = z;
  15990. if (z > mDataBounds.upper)
  15991. mDataBounds.upper = z;
  15992. mDataModified = true;
  15993. }
  15994. }
  15995. /*!
  15996. Goes through the data and updates the buffered minimum and maximum data values.
  15997. Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange
  15998. and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten
  15999. with a smaller or larger value respectively, since the buffered maximum/minimum values have been
  16000. updated the last time. Why this is the case is explained in the class description (\ref
  16001. QCPColorMapData).
  16002. Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a
  16003. recalculateDataBounds for convenience. Setting this to true will call this method for you, before
  16004. doing the rescale.
  16005. */
  16006. void QCPColorMapData::recalculateDataBounds()
  16007. {
  16008. if (mKeySize > 0 && mValueSize > 0)
  16009. {
  16010. double minHeight = mData[0];
  16011. double maxHeight = mData[0];
  16012. const int dataCount = mValueSize*mKeySize;
  16013. for (int i=0; i<dataCount; ++i)
  16014. {
  16015. if (mData[i] > maxHeight)
  16016. maxHeight = mData[i];
  16017. if (mData[i] < minHeight)
  16018. minHeight = mData[i];
  16019. }
  16020. mDataBounds.lower = minHeight;
  16021. mDataBounds.upper = maxHeight;
  16022. }
  16023. }
  16024. /*!
  16025. Frees the internal data memory.
  16026. This is equivalent to calling \ref setSize "setSize(0, 0)".
  16027. */
  16028. void QCPColorMapData::clear()
  16029. {
  16030. setSize(0, 0);
  16031. }
  16032. /*!
  16033. Sets all cells to the value \a z.
  16034. */
  16035. void QCPColorMapData::fill(double z)
  16036. {
  16037. const int dataCount = mValueSize*mKeySize;
  16038. for (int i=0; i<dataCount; ++i)
  16039. mData[i] = z;
  16040. mDataBounds = QCPRange(z, z);
  16041. }
  16042. /*!
  16043. Transforms plot coordinates given by \a key and \a value to cell indices of this QCPColorMapData
  16044. instance. The resulting cell indices are returned via the output parameters \a keyIndex and \a
  16045. valueIndex.
  16046. The retrieved key/value cell indices can then be used for example with \ref setCell.
  16047. If you are only interested in a key or value index, you may pass 0 as \a valueIndex or \a
  16048. keyIndex.
  16049. \see cellToCoord, QCPAxis::coordToPixel
  16050. */
  16051. void QCPColorMapData::coordToCell(double key, double value, int *keyIndex, int *valueIndex) const
  16052. {
  16053. if (keyIndex)
  16054. *keyIndex = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5;
  16055. if (valueIndex)
  16056. *valueIndex = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5;
  16057. }
  16058. /*!
  16059. Transforms cell indices given by \a keyIndex and \a valueIndex to cell indices of this QCPColorMapData
  16060. instance. The resulting coordinates are returned via the output parameters \a key and \a
  16061. value.
  16062. If you are only interested in a key or value coordinate, you may pass 0 as \a key or \a
  16063. value.
  16064. \see coordToCell, QCPAxis::pixelToCoord
  16065. */
  16066. void QCPColorMapData::cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const
  16067. {
  16068. if (key)
  16069. *key = keyIndex/(double)(mKeySize-1)*(mKeyRange.upper-mKeyRange.lower)+mKeyRange.lower;
  16070. if (value)
  16071. *value = valueIndex/(double)(mValueSize-1)*(mValueRange.upper-mValueRange.lower)+mValueRange.lower;
  16072. }
  16073. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16074. //////////////////// QCPColorMap
  16075. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16076. /*! \class QCPColorMap
  16077. \brief A plottable representing a two-dimensional color map in a plot.
  16078. \image html QCPColorMap.png
  16079. The data is stored in the class \ref QCPColorMapData, which can be accessed via the data()
  16080. method.
  16081. A color map has three dimensions to represent a data point: The \a key dimension, the \a value
  16082. dimension and the \a data dimension. As with other plottables such as graphs, \a key and \a value
  16083. correspond to two orthogonal axes on the QCustomPlot surface that you specify in the QColorMap
  16084. constructor. The \a data dimension however is encoded as the color of the point at (\a key, \a
  16085. value).
  16086. Set the number of points (or \a cells) in the key/value dimension via \ref
  16087. QCPColorMapData::setSize. The plot coordinate range over which these points will be displayed is
  16088. specified via \ref QCPColorMapData::setRange. The first cell will be centered on the lower range
  16089. boundary and the last cell will be centered on the upper range boundary. The data can be set by
  16090. either accessing the cells directly with QCPColorMapData::setCell or by addressing the cells via
  16091. their plot coordinates with \ref QCPColorMapData::setData. If possible, you should prefer
  16092. setCell, since it doesn't need to do any coordinate transformation and thus performs a bit
  16093. better.
  16094. The cell with index (0, 0) is at the bottom left, if the color map uses normal (i.e. not reversed)
  16095. key and value axes.
  16096. To show the user which colors correspond to which \a data values, a \ref QCPColorScale is
  16097. typically placed to the right of the axis rect. See the documentation there for details on how to
  16098. add and use a color scale.
  16099. \section appearance Changing the appearance
  16100. The central part of the appearance is the color gradient, which can be specified via \ref
  16101. setGradient. See the documentation of \ref QCPColorGradient for details on configuring a color
  16102. gradient.
  16103. The \a data range that is mapped to the colors of the gradient can be specified with \ref
  16104. setDataRange. To make the data range encompass the whole data set minimum to maximum, call \ref
  16105. rescaleDataRange.
  16106. \section usage Usage
  16107. Like all data representing objects in QCustomPlot, the QCPColorMap is a plottable
  16108. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  16109. (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.)
  16110. Usually, you first create an instance:
  16111. \code
  16112. QCPColorMap *colorMap = new QCPColorMap(customPlot->xAxis, customPlot->yAxis);\endcode
  16113. add it to the customPlot with QCustomPlot::addPlottable:
  16114. \code
  16115. customPlot->addPlottable(colorMap);\endcode
  16116. and then modify the properties of the newly created color map, e.g.:
  16117. \code
  16118. colorMap->data()->setSize(50, 50);
  16119. colorMap->data()->setRange(QCPRange(0, 2), QCPRange(0, 2));
  16120. for (int x=0; x<50; ++x)
  16121. for (int y=0; y<50; ++y)
  16122. colorMap->data()->setCell(x, y, qCos(x/10.0)+qSin(y/10.0));
  16123. colorMap->setGradient(QCPColorGradient::gpPolar);
  16124. colorMap->rescaleDataRange(true);
  16125. customPlot->rescaleAxes();
  16126. customPlot->replot();
  16127. \endcode
  16128. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  16129. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  16130. you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
  16131. determine the cell index. Rather directly access the cell index with \ref
  16132. QCPColorMapData::setCell.
  16133. */
  16134. /* start documentation of inline functions */
  16135. /*! \fn QCPColorMapData *QCPColorMap::data() const
  16136. Returns a pointer to the internal data storage of type \ref QCPColorMapData. Access this to
  16137. modify data points (cells) and the color map key/value range.
  16138. \see setData
  16139. */
  16140. /* end documentation of inline functions */
  16141. /* start documentation of signals */
  16142. /*! \fn void QCPColorMap::dataRangeChanged(QCPRange newRange);
  16143. This signal is emitted when the data range changes.
  16144. \see setDataRange
  16145. */
  16146. /*! \fn void QCPColorMap::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
  16147. This signal is emitted when the data scale type changes.
  16148. \see setDataScaleType
  16149. */
  16150. /*! \fn void QCPColorMap::gradientChanged(QCPColorGradient newGradient);
  16151. This signal is emitted when the gradient changes.
  16152. \see setGradient
  16153. */
  16154. /* end documentation of signals */
  16155. /*!
  16156. Constructs a color map with the specified \a keyAxis and \a valueAxis.
  16157. The constructed QCPColorMap can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
  16158. then takes ownership of the color map.
  16159. */
  16160. QCPColorMap::QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  16161. QCPAbstractPlottable(keyAxis, valueAxis),
  16162. mDataScaleType(QCPAxis::stLinear),
  16163. mMapData(new QCPColorMapData(10, 10, QCPRange(0, 5), QCPRange(0, 5))),
  16164. mInterpolate(true),
  16165. mTightBoundary(false),
  16166. mMapImageInvalidated(true)
  16167. {
  16168. }
  16169. QCPColorMap::~QCPColorMap()
  16170. {
  16171. delete mMapData;
  16172. }
  16173. /*!
  16174. Replaces the current \ref data with the provided \a data.
  16175. If \a copy is set to true, the \a data object will only be copied. if false, the color map
  16176. takes ownership of the passed data and replaces the internal data pointer with it. This is
  16177. significantly faster than copying for large datasets.
  16178. */
  16179. void QCPColorMap::setData(QCPColorMapData *data, bool copy)
  16180. {
  16181. if (copy)
  16182. {
  16183. *mMapData = *data;
  16184. } else
  16185. {
  16186. delete mMapData;
  16187. mMapData = data;
  16188. }
  16189. mMapImageInvalidated = true;
  16190. }
  16191. /*!
  16192. Sets the data range of this color map to \a dataRange. The data range defines which data values
  16193. are mapped to the color gradient.
  16194. To make the data range span the full range of the data set, use \ref rescaleDataRange.
  16195. \see QCPColorScale::setDataRange
  16196. */
  16197. void QCPColorMap::setDataRange(const QCPRange &dataRange)
  16198. {
  16199. if (!QCPRange::validRange(dataRange)) return;
  16200. if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
  16201. {
  16202. if (mDataScaleType == QCPAxis::stLogarithmic)
  16203. mDataRange = dataRange.sanitizedForLogScale();
  16204. else
  16205. mDataRange = dataRange.sanitizedForLinScale();
  16206. mMapImageInvalidated = true;
  16207. emit dataRangeChanged(mDataRange);
  16208. }
  16209. }
  16210. /*!
  16211. Sets whether the data is correlated with the color gradient linearly or logarithmically.
  16212. \see QCPColorScale::setDataScaleType
  16213. */
  16214. void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType)
  16215. {
  16216. if (mDataScaleType != scaleType)
  16217. {
  16218. mDataScaleType = scaleType;
  16219. mMapImageInvalidated = true;
  16220. emit dataScaleTypeChanged(mDataScaleType);
  16221. if (mDataScaleType == QCPAxis::stLogarithmic)
  16222. setDataRange(mDataRange.sanitizedForLogScale());
  16223. }
  16224. }
  16225. /*!
  16226. Sets the color gradient that is used to represent the data. For more details on how to create an
  16227. own gradient or use one of the preset gradients, see \ref QCPColorGradient.
  16228. The colors defined by the gradient will be used to represent data values in the currently set
  16229. data range, see \ref setDataRange. Data points that are outside this data range will either be
  16230. colored uniformly with the respective gradient boundary color, or the gradient will repeat,
  16231. depending on \ref QCPColorGradient::setPeriodic.
  16232. \see QCPColorScale::setGradient
  16233. */
  16234. void QCPColorMap::setGradient(const QCPColorGradient &gradient)
  16235. {
  16236. if (mGradient != gradient)
  16237. {
  16238. mGradient = gradient;
  16239. mMapImageInvalidated = true;
  16240. emit gradientChanged(mGradient);
  16241. }
  16242. }
  16243. /*!
  16244. Sets whether the color map image shall use bicubic interpolation when displaying the color map
  16245. shrinked or expanded, and not at a 1:1 pixel-to-data scale.
  16246. \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled"
  16247. */
  16248. void QCPColorMap::setInterpolate(bool enabled)
  16249. {
  16250. mInterpolate = enabled;
  16251. }
  16252. /*!
  16253. Sets whether the outer most data rows and columns are clipped to the specified key and value
  16254. range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange).
  16255. if \a enabled is set to false, the data points at the border of the color map are drawn with the
  16256. same width and height as all other data points. Since the data points are represented by
  16257. rectangles of one color centered on the data coordinate, this means that the shown color map
  16258. extends by half a data point over the specified key/value range in each direction.
  16259. \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled"
  16260. */
  16261. void QCPColorMap::setTightBoundary(bool enabled)
  16262. {
  16263. mTightBoundary = enabled;
  16264. }
  16265. /*!
  16266. Associates the color scale \a colorScale with this color map.
  16267. This means that both the color scale and the color map synchronize their gradient, data range and
  16268. data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps
  16269. can be associated with one single color scale. This causes the color maps to also synchronize
  16270. those properties, via the mutual color scale.
  16271. This function causes the color map to adopt the current color gradient, data range and data scale
  16272. type of \a colorScale. After this call, you may change these properties at either the color map
  16273. or the color scale, and the setting will be applied to both.
  16274. Pass 0 as \a colorScale to disconnect the color scale from this color map again.
  16275. */
  16276. void QCPColorMap::setColorScale(QCPColorScale *colorScale)
  16277. {
  16278. if (mColorScale) // unconnect signals from old color scale
  16279. {
  16280. disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
  16281. disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
  16282. disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
  16283. disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  16284. disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
  16285. disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  16286. }
  16287. mColorScale = colorScale;
  16288. if (mColorScale) // connect signals to new color scale
  16289. {
  16290. setGradient(mColorScale.data()->gradient());
  16291. setDataRange(mColorScale.data()->dataRange());
  16292. setDataScaleType(mColorScale.data()->dataScaleType());
  16293. connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
  16294. connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
  16295. connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
  16296. connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  16297. connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
  16298. connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  16299. }
  16300. }
  16301. /*!
  16302. Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the
  16303. current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods,
  16304. only for the third data dimension of the color map.
  16305. The minimum and maximum values of the data set are buffered in the internal QCPColorMapData
  16306. instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref
  16307. QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For
  16308. performance reasons, however, they are only updated in an expanding fashion. So the buffered
  16309. maximum can only increase and the buffered minimum can only decrease. In consequence, changes to
  16310. the data that actually lower the maximum of the data set (by overwriting the cell holding the
  16311. current maximum with a smaller value), aren't recognized and the buffered maximum overestimates
  16312. the true maximum of the data set. The same happens for the buffered minimum. To recalculate the
  16313. true minimum and maximum by explicitly looking at each cell, the method
  16314. QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a
  16315. recalculateDataBounds calls this method before setting the data range to the buffered minimum and
  16316. maximum.
  16317. \see setDataRange
  16318. */
  16319. void QCPColorMap::rescaleDataRange(bool recalculateDataBounds)
  16320. {
  16321. if (recalculateDataBounds)
  16322. mMapData->recalculateDataBounds();
  16323. setDataRange(mMapData->dataBounds());
  16324. }
  16325. /*!
  16326. Takes the current appearance of the color map and updates the legend icon, which is used to
  16327. represent this color map in the legend (see \ref QCPLegend).
  16328. The \a transformMode specifies whether the rescaling is done by a faster, low quality image
  16329. scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm
  16330. (Qt::SmoothTransformation).
  16331. The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to
  16332. the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured
  16333. legend icon size, the thumb will be rescaled during drawing of the legend item.
  16334. \see setDataRange
  16335. */
  16336. void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize)
  16337. {
  16338. if (mMapImage.isNull() && !data()->isEmpty())
  16339. updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet)
  16340. if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again
  16341. {
  16342. bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
  16343. bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
  16344. mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode);
  16345. }
  16346. }
  16347. /*!
  16348. Clears the colormap data by calling \ref QCPColorMapData::clear() on the internal data. This also
  16349. resizes the map to 0x0 cells.
  16350. */
  16351. void QCPColorMap::clearData()
  16352. {
  16353. mMapData->clear();
  16354. }
  16355. /* inherits documentation from base class */
  16356. double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  16357. {
  16358. Q_UNUSED(details)
  16359. if (onlySelectable && !mSelectable)
  16360. return -1;
  16361. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  16362. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
  16363. {
  16364. double posKey, posValue;
  16365. pixelsToCoords(pos, posKey, posValue);
  16366. if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue))
  16367. return mParentPlot->selectionTolerance()*0.99;
  16368. }
  16369. return -1;
  16370. }
  16371. /*! \internal
  16372. Updates the internal map image buffer by going through the internal \ref QCPColorMapData and
  16373. turning the data values into color pixels with \ref QCPColorGradient::colorize.
  16374. This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image
  16375. has been invalidated for a different reason (e.g. a change of the data range with \ref
  16376. setDataRange).
  16377. */
  16378. void QCPColorMap::updateMapImage()
  16379. {
  16380. QCPAxis *keyAxis = mKeyAxis.data();
  16381. if (!keyAxis) return;
  16382. // resize mMapImage to correct dimensions, according to key/value axes orientation:
  16383. if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.size().width() != mMapData->keySize() || mMapImage.size().height() != mMapData->valueSize()))
  16384. mMapImage = QImage(QSize(mMapData->keySize(), mMapData->valueSize()), QImage::Format_RGB32);
  16385. else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.size().width() != mMapData->valueSize() || mMapImage.size().height() != mMapData->keySize()))
  16386. mMapImage = QImage(QSize(mMapData->valueSize(), mMapData->keySize()), QImage::Format_RGB32);
  16387. const int keySize = mMapData->keySize();
  16388. const int valueSize = mMapData->valueSize();
  16389. const double *rawData = mMapData->mData;
  16390. if (keyAxis->orientation() == Qt::Horizontal)
  16391. {
  16392. const int lineCount = valueSize;
  16393. const int rowCount = keySize;
  16394. for (int line=0; line<lineCount; ++line)
  16395. {
  16396. QRgb* pixels = reinterpret_cast<QRgb*>(mMapImage.scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system)
  16397. mGradient.colorize(rawData+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic);
  16398. }
  16399. } else // keyAxis->orientation() == Qt::Vertical
  16400. {
  16401. const int lineCount = keySize;
  16402. const int rowCount = valueSize;
  16403. for (int line=0; line<lineCount; ++line)
  16404. {
  16405. QRgb* pixels = reinterpret_cast<QRgb*>(mMapImage.scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system)
  16406. mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic);
  16407. }
  16408. }
  16409. mMapData->mDataModified = false;
  16410. mMapImageInvalidated = false;
  16411. }
  16412. /* inherits documentation from base class */
  16413. void QCPColorMap::draw(QCPPainter *painter)
  16414. {
  16415. if (mMapData->isEmpty()) return;
  16416. if (!mKeyAxis || !mValueAxis) return;
  16417. applyDefaultAntialiasingHint(painter);
  16418. if (mMapData->mDataModified || mMapImageInvalidated)
  16419. updateMapImage();
  16420. double halfSampleKey = 0;
  16421. double halfSampleValue = 0;
  16422. if (mMapData->keySize() > 1)
  16423. halfSampleKey = 0.5*mMapData->keyRange().size()/(double)(mMapData->keySize()-1);
  16424. if (mMapData->valueSize() > 1)
  16425. halfSampleValue = 0.5*mMapData->valueRange().size()/(double)(mMapData->valueSize()-1);
  16426. QRectF imageRect(coordsToPixels(mMapData->keyRange().lower-halfSampleKey, mMapData->valueRange().lower-halfSampleValue),
  16427. coordsToPixels(mMapData->keyRange().upper+halfSampleKey, mMapData->valueRange().upper+halfSampleValue));
  16428. imageRect = imageRect.normalized();
  16429. bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
  16430. bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
  16431. bool smoothBackup = painter->renderHints().testFlag(QPainter::SmoothPixmapTransform);
  16432. painter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate);
  16433. QRegion clipBackup;
  16434. if (mTightBoundary)
  16435. {
  16436. clipBackup = painter->clipRegion();
  16437. painter->setClipRect(QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
  16438. coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(), Qt::IntersectClip);
  16439. }
  16440. painter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY));
  16441. if (mTightBoundary)
  16442. painter->setClipRegion(clipBackup);
  16443. painter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup);
  16444. }
  16445. /* inherits documentation from base class */
  16446. void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  16447. {
  16448. applyDefaultAntialiasingHint(painter);
  16449. // draw map thumbnail:
  16450. if (!mLegendIcon.isNull())
  16451. {
  16452. QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation);
  16453. QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height());
  16454. iconRect.moveCenter(rect.center());
  16455. painter->drawPixmap(iconRect.topLeft(), scaledIcon);
  16456. }
  16457. /*
  16458. // draw frame:
  16459. painter->setBrush(Qt::NoBrush);
  16460. painter->setPen(Qt::black);
  16461. painter->drawRect(rect.adjusted(1, 1, 0, 0));
  16462. */
  16463. }
  16464. /* inherits documentation from base class */
  16465. QCPRange QCPColorMap::getKeyRange(bool &foundRange, SignDomain inSignDomain) const
  16466. {
  16467. foundRange = true;
  16468. QCPRange result = mMapData->keyRange();
  16469. result.normalize();
  16470. if (inSignDomain == QCPAbstractPlottable::sdPositive)
  16471. {
  16472. if (result.lower <= 0 && result.upper > 0)
  16473. result.lower = result.upper*1e-3;
  16474. else if (result.lower <= 0 && result.upper <= 0)
  16475. foundRange = false;
  16476. } else if (inSignDomain == QCPAbstractPlottable::sdNegative)
  16477. {
  16478. if (result.upper >= 0 && result.lower < 0)
  16479. result.upper = result.lower*1e-3;
  16480. else if (result.upper >= 0 && result.lower >= 0)
  16481. foundRange = false;
  16482. }
  16483. return result;
  16484. }
  16485. /* inherits documentation from base class */
  16486. QCPRange QCPColorMap::getValueRange(bool &foundRange, SignDomain inSignDomain) const
  16487. {
  16488. foundRange = true;
  16489. QCPRange result = mMapData->valueRange();
  16490. result.normalize();
  16491. if (inSignDomain == QCPAbstractPlottable::sdPositive)
  16492. {
  16493. if (result.lower <= 0 && result.upper > 0)
  16494. result.lower = result.upper*1e-3;
  16495. else if (result.lower <= 0 && result.upper <= 0)
  16496. foundRange = false;
  16497. } else if (inSignDomain == QCPAbstractPlottable::sdNegative)
  16498. {
  16499. if (result.upper >= 0 && result.lower < 0)
  16500. result.upper = result.lower*1e-3;
  16501. else if (result.upper >= 0 && result.lower >= 0)
  16502. foundRange = false;
  16503. }
  16504. return result;
  16505. }
  16506. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16507. //////////////////// QCPItemStraightLine
  16508. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16509. /*! \class QCPItemStraightLine
  16510. \brief A straight line that spans infinitely in both directions
  16511. \image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid blue discs are positions."
  16512. It has two positions, \a point1 and \a point2, which define the straight line.
  16513. */
  16514. /*!
  16515. Creates a straight line item and sets default values.
  16516. The constructed item can be added to the plot with QCustomPlot::addItem.
  16517. */
  16518. QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) :
  16519. QCPAbstractItem(parentPlot),
  16520. point1(createPosition("point1")),
  16521. point2(createPosition("point2"))
  16522. {
  16523. point1->setCoords(0, 0);
  16524. point2->setCoords(1, 1);
  16525. setPen(QPen(Qt::black));
  16526. setSelectedPen(QPen(Qt::blue,2));
  16527. }
  16528. QCPItemStraightLine::~QCPItemStraightLine()
  16529. {
  16530. }
  16531. /*!
  16532. Sets the pen that will be used to draw the line
  16533. \see setSelectedPen
  16534. */
  16535. void QCPItemStraightLine::setPen(const QPen &pen)
  16536. {
  16537. mPen = pen;
  16538. }
  16539. /*!
  16540. Sets the pen that will be used to draw the line when selected
  16541. \see setPen, setSelected
  16542. */
  16543. void QCPItemStraightLine::setSelectedPen(const QPen &pen)
  16544. {
  16545. mSelectedPen = pen;
  16546. }
  16547. /* inherits documentation from base class */
  16548. double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  16549. {
  16550. Q_UNUSED(details)
  16551. if (onlySelectable && !mSelectable)
  16552. return -1;
  16553. return distToStraightLine(QVector2D(point1->pixelPoint()), QVector2D(point2->pixelPoint()-point1->pixelPoint()), QVector2D(pos));
  16554. }
  16555. /* inherits documentation from base class */
  16556. void QCPItemStraightLine::draw(QCPPainter *painter)
  16557. {
  16558. QVector2D start(point1->pixelPoint());
  16559. QVector2D end(point2->pixelPoint());
  16560. // get visible segment of straight line inside clipRect:
  16561. double clipPad = mainPen().widthF();
  16562. QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
  16563. // paint visible segment, if existent:
  16564. if (!line.isNull())
  16565. {
  16566. painter->setPen(mainPen());
  16567. painter->drawLine(line);
  16568. }
  16569. }
  16570. /*! \internal
  16571. finds the shortest distance of \a point to the straight line defined by the base point \a
  16572. base and the direction vector \a vec.
  16573. This is a helper function for \ref selectTest.
  16574. */
  16575. double QCPItemStraightLine::distToStraightLine(const QVector2D &base, const QVector2D &vec, const QVector2D &point) const
  16576. {
  16577. return qAbs((base.y()-point.y())*vec.x()-(base.x()-point.x())*vec.y())/vec.length();
  16578. }
  16579. /*! \internal
  16580. Returns the section of the straight line defined by \a base and direction vector \a
  16581. vec, that is visible in the specified \a rect.
  16582. This is a helper function for \ref draw.
  16583. */
  16584. QLineF QCPItemStraightLine::getRectClippedStraightLine(const QVector2D &base, const QVector2D &vec, const QRect &rect) const
  16585. {
  16586. double bx, by;
  16587. double gamma;
  16588. QLineF result;
  16589. if (vec.x() == 0 && vec.y() == 0)
  16590. return result;
  16591. if (qFuzzyIsNull(vec.x())) // line is vertical
  16592. {
  16593. // check top of rect:
  16594. bx = rect.left();
  16595. by = rect.top();
  16596. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  16597. if (gamma >= 0 && gamma <= rect.width())
  16598. result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical
  16599. } else if (qFuzzyIsNull(vec.y())) // line is horizontal
  16600. {
  16601. // check left of rect:
  16602. bx = rect.left();
  16603. by = rect.top();
  16604. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  16605. if (gamma >= 0 && gamma <= rect.height())
  16606. result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal
  16607. } else // line is skewed
  16608. {
  16609. QList<QVector2D> pointVectors;
  16610. // check top of rect:
  16611. bx = rect.left();
  16612. by = rect.top();
  16613. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  16614. if (gamma >= 0 && gamma <= rect.width())
  16615. pointVectors.append(QVector2D(bx+gamma, by));
  16616. // check bottom of rect:
  16617. bx = rect.left();
  16618. by = rect.bottom();
  16619. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  16620. if (gamma >= 0 && gamma <= rect.width())
  16621. pointVectors.append(QVector2D(bx+gamma, by));
  16622. // check left of rect:
  16623. bx = rect.left();
  16624. by = rect.top();
  16625. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  16626. if (gamma >= 0 && gamma <= rect.height())
  16627. pointVectors.append(QVector2D(bx, by+gamma));
  16628. // check right of rect:
  16629. bx = rect.right();
  16630. by = rect.top();
  16631. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  16632. if (gamma >= 0 && gamma <= rect.height())
  16633. pointVectors.append(QVector2D(bx, by+gamma));
  16634. // evaluate points:
  16635. if (pointVectors.size() == 2)
  16636. {
  16637. result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
  16638. } else if (pointVectors.size() > 2)
  16639. {
  16640. // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
  16641. double distSqrMax = 0;
  16642. QVector2D pv1, pv2;
  16643. for (int i=0; i<pointVectors.size()-1; ++i)
  16644. {
  16645. for (int k=i+1; k<pointVectors.size(); ++k)
  16646. {
  16647. double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
  16648. if (distSqr > distSqrMax)
  16649. {
  16650. pv1 = pointVectors.at(i);
  16651. pv2 = pointVectors.at(k);
  16652. distSqrMax = distSqr;
  16653. }
  16654. }
  16655. }
  16656. result.setPoints(pv1.toPointF(), pv2.toPointF());
  16657. }
  16658. }
  16659. return result;
  16660. }
  16661. /*! \internal
  16662. Returns the pen that should be used for drawing lines. Returns mPen when the
  16663. item is not selected and mSelectedPen when it is.
  16664. */
  16665. QPen QCPItemStraightLine::mainPen() const
  16666. {
  16667. return mSelected ? mSelectedPen : mPen;
  16668. }
  16669. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16670. //////////////////// QCPItemLine
  16671. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16672. /*! \class QCPItemLine
  16673. \brief A line from one point to another
  16674. \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions."
  16675. It has two positions, \a start and \a end, which define the end points of the line.
  16676. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow.
  16677. */
  16678. /*!
  16679. Creates a line item and sets default values.
  16680. The constructed item can be added to the plot with QCustomPlot::addItem.
  16681. */
  16682. QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) :
  16683. QCPAbstractItem(parentPlot),
  16684. start(createPosition("start")),
  16685. end(createPosition("end"))
  16686. {
  16687. start->setCoords(0, 0);
  16688. end->setCoords(1, 1);
  16689. setPen(QPen(Qt::black));
  16690. setSelectedPen(QPen(Qt::blue,2));
  16691. }
  16692. QCPItemLine::~QCPItemLine()
  16693. {
  16694. }
  16695. /*!
  16696. Sets the pen that will be used to draw the line
  16697. \see setSelectedPen
  16698. */
  16699. void QCPItemLine::setPen(const QPen &pen)
  16700. {
  16701. mPen = pen;
  16702. }
  16703. /*!
  16704. Sets the pen that will be used to draw the line when selected
  16705. \see setPen, setSelected
  16706. */
  16707. void QCPItemLine::setSelectedPen(const QPen &pen)
  16708. {
  16709. mSelectedPen = pen;
  16710. }
  16711. /*!
  16712. Sets the line ending style of the head. The head corresponds to the \a end position.
  16713. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  16714. a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
  16715. \see setTail
  16716. */
  16717. void QCPItemLine::setHead(const QCPLineEnding &head)
  16718. {
  16719. mHead = head;
  16720. }
  16721. /*!
  16722. Sets the line ending style of the tail. The tail corresponds to the \a start position.
  16723. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  16724. a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
  16725. \see setHead
  16726. */
  16727. void QCPItemLine::setTail(const QCPLineEnding &tail)
  16728. {
  16729. mTail = tail;
  16730. }
  16731. /* inherits documentation from base class */
  16732. double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  16733. {
  16734. Q_UNUSED(details)
  16735. if (onlySelectable && !mSelectable)
  16736. return -1;
  16737. return qSqrt(distSqrToLine(start->pixelPoint(), end->pixelPoint(), pos));
  16738. }
  16739. /* inherits documentation from base class */
  16740. void QCPItemLine::draw(QCPPainter *painter)
  16741. {
  16742. QVector2D startVec(start->pixelPoint());
  16743. QVector2D endVec(end->pixelPoint());
  16744. if (startVec.toPoint() == endVec.toPoint())
  16745. return;
  16746. // get visible segment of straight line inside clipRect:
  16747. double clipPad = qMax(mHead.boundingDistance(), mTail.boundingDistance());
  16748. clipPad = qMax(clipPad, (double)mainPen().widthF());
  16749. QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
  16750. // paint visible segment, if existent:
  16751. if (!line.isNull())
  16752. {
  16753. painter->setPen(mainPen());
  16754. painter->drawLine(line);
  16755. painter->setBrush(Qt::SolidPattern);
  16756. if (mTail.style() != QCPLineEnding::esNone)
  16757. mTail.draw(painter, startVec, startVec-endVec);
  16758. if (mHead.style() != QCPLineEnding::esNone)
  16759. mHead.draw(painter, endVec, endVec-startVec);
  16760. }
  16761. }
  16762. /*! \internal
  16763. Returns the section of the line defined by \a start and \a end, that is visible in the specified
  16764. \a rect.
  16765. This is a helper function for \ref draw.
  16766. */
  16767. QLineF QCPItemLine::getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const
  16768. {
  16769. bool containsStart = rect.contains(start.x(), start.y());
  16770. bool containsEnd = rect.contains(end.x(), end.y());
  16771. if (containsStart && containsEnd)
  16772. return QLineF(start.toPointF(), end.toPointF());
  16773. QVector2D base = start;
  16774. QVector2D vec = end-start;
  16775. double bx, by;
  16776. double gamma, mu;
  16777. QLineF result;
  16778. QList<QVector2D> pointVectors;
  16779. if (!qFuzzyIsNull(vec.y())) // line is not horizontal
  16780. {
  16781. // check top of rect:
  16782. bx = rect.left();
  16783. by = rect.top();
  16784. mu = (by-base.y())/vec.y();
  16785. if (mu >= 0 && mu <= 1)
  16786. {
  16787. gamma = base.x()-bx + mu*vec.x();
  16788. if (gamma >= 0 && gamma <= rect.width())
  16789. pointVectors.append(QVector2D(bx+gamma, by));
  16790. }
  16791. // check bottom of rect:
  16792. bx = rect.left();
  16793. by = rect.bottom();
  16794. mu = (by-base.y())/vec.y();
  16795. if (mu >= 0 && mu <= 1)
  16796. {
  16797. gamma = base.x()-bx + mu*vec.x();
  16798. if (gamma >= 0 && gamma <= rect.width())
  16799. pointVectors.append(QVector2D(bx+gamma, by));
  16800. }
  16801. }
  16802. if (!qFuzzyIsNull(vec.x())) // line is not vertical
  16803. {
  16804. // check left of rect:
  16805. bx = rect.left();
  16806. by = rect.top();
  16807. mu = (bx-base.x())/vec.x();
  16808. if (mu >= 0 && mu <= 1)
  16809. {
  16810. gamma = base.y()-by + mu*vec.y();
  16811. if (gamma >= 0 && gamma <= rect.height())
  16812. pointVectors.append(QVector2D(bx, by+gamma));
  16813. }
  16814. // check right of rect:
  16815. bx = rect.right();
  16816. by = rect.top();
  16817. mu = (bx-base.x())/vec.x();
  16818. if (mu >= 0 && mu <= 1)
  16819. {
  16820. gamma = base.y()-by + mu*vec.y();
  16821. if (gamma >= 0 && gamma <= rect.height())
  16822. pointVectors.append(QVector2D(bx, by+gamma));
  16823. }
  16824. }
  16825. if (containsStart)
  16826. pointVectors.append(start);
  16827. if (containsEnd)
  16828. pointVectors.append(end);
  16829. // evaluate points:
  16830. if (pointVectors.size() == 2)
  16831. {
  16832. result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
  16833. } else if (pointVectors.size() > 2)
  16834. {
  16835. // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
  16836. double distSqrMax = 0;
  16837. QVector2D pv1, pv2;
  16838. for (int i=0; i<pointVectors.size()-1; ++i)
  16839. {
  16840. for (int k=i+1; k<pointVectors.size(); ++k)
  16841. {
  16842. double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
  16843. if (distSqr > distSqrMax)
  16844. {
  16845. pv1 = pointVectors.at(i);
  16846. pv2 = pointVectors.at(k);
  16847. distSqrMax = distSqr;
  16848. }
  16849. }
  16850. }
  16851. result.setPoints(pv1.toPointF(), pv2.toPointF());
  16852. }
  16853. return result;
  16854. }
  16855. /*! \internal
  16856. Returns the pen that should be used for drawing lines. Returns mPen when the
  16857. item is not selected and mSelectedPen when it is.
  16858. */
  16859. QPen QCPItemLine::mainPen() const
  16860. {
  16861. return mSelected ? mSelectedPen : mPen;
  16862. }
  16863. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16864. //////////////////// QCPItemCurve
  16865. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16866. /*! \class QCPItemCurve
  16867. \brief A curved line from one point to another
  16868. \image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are positions."
  16869. It has four positions, \a start and \a end, which define the end points of the line, and two
  16870. control points which define the direction the line exits from the start and the direction from
  16871. which it approaches the end: \a startDir and \a endDir.
  16872. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an
  16873. arrow.
  16874. Often it is desirable for the control points to stay at fixed relative positions to the start/end
  16875. point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start,
  16876. and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir.
  16877. */
  16878. /*!
  16879. Creates a curve item and sets default values.
  16880. The constructed item can be added to the plot with QCustomPlot::addItem.
  16881. */
  16882. QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) :
  16883. QCPAbstractItem(parentPlot),
  16884. start(createPosition("start")),
  16885. startDir(createPosition("startDir")),
  16886. endDir(createPosition("endDir")),
  16887. end(createPosition("end"))
  16888. {
  16889. start->setCoords(0, 0);
  16890. startDir->setCoords(0.5, 0);
  16891. endDir->setCoords(0, 0.5);
  16892. end->setCoords(1, 1);
  16893. setPen(QPen(Qt::black));
  16894. setSelectedPen(QPen(Qt::blue,2));
  16895. }
  16896. QCPItemCurve::~QCPItemCurve()
  16897. {
  16898. }
  16899. /*!
  16900. Sets the pen that will be used to draw the line
  16901. \see setSelectedPen
  16902. */
  16903. void QCPItemCurve::setPen(const QPen &pen)
  16904. {
  16905. mPen = pen;
  16906. }
  16907. /*!
  16908. Sets the pen that will be used to draw the line when selected
  16909. \see setPen, setSelected
  16910. */
  16911. void QCPItemCurve::setSelectedPen(const QPen &pen)
  16912. {
  16913. mSelectedPen = pen;
  16914. }
  16915. /*!
  16916. Sets the line ending style of the head. The head corresponds to the \a end position.
  16917. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  16918. a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
  16919. \see setTail
  16920. */
  16921. void QCPItemCurve::setHead(const QCPLineEnding &head)
  16922. {
  16923. mHead = head;
  16924. }
  16925. /*!
  16926. Sets the line ending style of the tail. The tail corresponds to the \a start position.
  16927. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  16928. a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
  16929. \see setHead
  16930. */
  16931. void QCPItemCurve::setTail(const QCPLineEnding &tail)
  16932. {
  16933. mTail = tail;
  16934. }
  16935. /* inherits documentation from base class */
  16936. double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  16937. {
  16938. Q_UNUSED(details)
  16939. if (onlySelectable && !mSelectable)
  16940. return -1;
  16941. QPointF startVec(start->pixelPoint());
  16942. QPointF startDirVec(startDir->pixelPoint());
  16943. QPointF endDirVec(endDir->pixelPoint());
  16944. QPointF endVec(end->pixelPoint());
  16945. QPainterPath cubicPath(startVec);
  16946. cubicPath.cubicTo(startDirVec, endDirVec, endVec);
  16947. QPolygonF polygon = cubicPath.toSubpathPolygons().first();
  16948. double minDistSqr = std::numeric_limits<double>::max();
  16949. for (int i=1; i<polygon.size(); ++i)
  16950. {
  16951. double distSqr = distSqrToLine(polygon.at(i-1), polygon.at(i), pos);
  16952. if (distSqr < minDistSqr)
  16953. minDistSqr = distSqr;
  16954. }
  16955. return qSqrt(minDistSqr);
  16956. }
  16957. /* inherits documentation from base class */
  16958. void QCPItemCurve::draw(QCPPainter *painter)
  16959. {
  16960. QPointF startVec(start->pixelPoint());
  16961. QPointF startDirVec(startDir->pixelPoint());
  16962. QPointF endDirVec(endDir->pixelPoint());
  16963. QPointF endVec(end->pixelPoint());
  16964. if (QVector2D(endVec-startVec).length() > 1e10f) // too large curves cause crash
  16965. return;
  16966. QPainterPath cubicPath(startVec);
  16967. cubicPath.cubicTo(startDirVec, endDirVec, endVec);
  16968. // paint visible segment, if existent:
  16969. QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
  16970. QRect cubicRect = cubicPath.controlPointRect().toRect();
  16971. if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position
  16972. cubicRect.adjust(0, 0, 1, 1);
  16973. if (clip.intersects(cubicRect))
  16974. {
  16975. painter->setPen(mainPen());
  16976. painter->drawPath(cubicPath);
  16977. painter->setBrush(Qt::SolidPattern);
  16978. if (mTail.style() != QCPLineEnding::esNone)
  16979. mTail.draw(painter, QVector2D(startVec), M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI);
  16980. if (mHead.style() != QCPLineEnding::esNone)
  16981. mHead.draw(painter, QVector2D(endVec), -cubicPath.angleAtPercent(1)/180.0*M_PI);
  16982. }
  16983. }
  16984. /*! \internal
  16985. Returns the pen that should be used for drawing lines. Returns mPen when the
  16986. item is not selected and mSelectedPen when it is.
  16987. */
  16988. QPen QCPItemCurve::mainPen() const
  16989. {
  16990. return mSelected ? mSelectedPen : mPen;
  16991. }
  16992. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16993. //////////////////// QCPItemRect
  16994. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16995. /*! \class QCPItemRect
  16996. \brief A rectangle
  16997. \image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions."
  16998. It has two positions, \a topLeft and \a bottomRight, which define the rectangle.
  16999. */
  17000. /*!
  17001. Creates a rectangle item and sets default values.
  17002. The constructed item can be added to the plot with QCustomPlot::addItem.
  17003. */
  17004. QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) :
  17005. QCPAbstractItem(parentPlot),
  17006. topLeft(createPosition("topLeft")),
  17007. bottomRight(createPosition("bottomRight")),
  17008. top(createAnchor("top", aiTop)),
  17009. topRight(createAnchor("topRight", aiTopRight)),
  17010. right(createAnchor("right", aiRight)),
  17011. bottom(createAnchor("bottom", aiBottom)),
  17012. bottomLeft(createAnchor("bottomLeft", aiBottomLeft)),
  17013. left(createAnchor("left", aiLeft))
  17014. {
  17015. topLeft->setCoords(0, 1);
  17016. bottomRight->setCoords(1, 0);
  17017. setPen(QPen(Qt::black));
  17018. setSelectedPen(QPen(Qt::blue,2));
  17019. setBrush(Qt::NoBrush);
  17020. setSelectedBrush(Qt::NoBrush);
  17021. }
  17022. QCPItemRect::~QCPItemRect()
  17023. {
  17024. }
  17025. /*!
  17026. Sets the pen that will be used to draw the line of the rectangle
  17027. \see setSelectedPen, setBrush
  17028. */
  17029. void QCPItemRect::setPen(const QPen &pen)
  17030. {
  17031. mPen = pen;
  17032. }
  17033. /*!
  17034. Sets the pen that will be used to draw the line of the rectangle when selected
  17035. \see setPen, setSelected
  17036. */
  17037. void QCPItemRect::setSelectedPen(const QPen &pen)
  17038. {
  17039. mSelectedPen = pen;
  17040. }
  17041. /*!
  17042. Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to
  17043. Qt::NoBrush.
  17044. \see setSelectedBrush, setPen
  17045. */
  17046. void QCPItemRect::setBrush(const QBrush &brush)
  17047. {
  17048. mBrush = brush;
  17049. }
  17050. /*!
  17051. Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a
  17052. brush to Qt::NoBrush.
  17053. \see setBrush
  17054. */
  17055. void QCPItemRect::setSelectedBrush(const QBrush &brush)
  17056. {
  17057. mSelectedBrush = brush;
  17058. }
  17059. /* inherits documentation from base class */
  17060. double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  17061. {
  17062. Q_UNUSED(details)
  17063. if (onlySelectable && !mSelectable)
  17064. return -1;
  17065. QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()).normalized();
  17066. bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
  17067. return rectSelectTest(rect, pos, filledRect);
  17068. }
  17069. /* inherits documentation from base class */
  17070. void QCPItemRect::draw(QCPPainter *painter)
  17071. {
  17072. QPointF p1 = topLeft->pixelPoint();
  17073. QPointF p2 = bottomRight->pixelPoint();
  17074. if (p1.toPoint() == p2.toPoint())
  17075. return;
  17076. QRectF rect = QRectF(p1, p2).normalized();
  17077. double clipPad = mainPen().widthF();
  17078. QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  17079. if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect
  17080. {
  17081. painter->setPen(mainPen());
  17082. painter->setBrush(mainBrush());
  17083. painter->drawRect(rect);
  17084. }
  17085. }
  17086. /* inherits documentation from base class */
  17087. QPointF QCPItemRect::anchorPixelPoint(int anchorId) const
  17088. {
  17089. QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint());
  17090. switch (anchorId)
  17091. {
  17092. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  17093. case aiTopRight: return rect.topRight();
  17094. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  17095. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  17096. case aiBottomLeft: return rect.bottomLeft();
  17097. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
  17098. }
  17099. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  17100. return QPointF();
  17101. }
  17102. /*! \internal
  17103. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  17104. and mSelectedPen when it is.
  17105. */
  17106. QPen QCPItemRect::mainPen() const
  17107. {
  17108. return mSelected ? mSelectedPen : mPen;
  17109. }
  17110. /*! \internal
  17111. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  17112. is not selected and mSelectedBrush when it is.
  17113. */
  17114. QBrush QCPItemRect::mainBrush() const
  17115. {
  17116. return mSelected ? mSelectedBrush : mBrush;
  17117. }
  17118. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17119. //////////////////// QCPItemText
  17120. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17121. /*! \class QCPItemText
  17122. \brief A text label
  17123. \image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions."
  17124. Its position is defined by the member \a position and the setting of \ref setPositionAlignment.
  17125. The latter controls which part of the text rect shall be aligned with \a position.
  17126. The text alignment itself (i.e. left, center, right) can be controlled with \ref
  17127. setTextAlignment.
  17128. The text may be rotated around the \a position point with \ref setRotation.
  17129. */
  17130. /*!
  17131. Creates a text item and sets default values.
  17132. The constructed item can be added to the plot with QCustomPlot::addItem.
  17133. */
  17134. QCPItemText::QCPItemText(QCustomPlot *parentPlot) :
  17135. QCPAbstractItem(parentPlot),
  17136. position(createPosition("position")),
  17137. topLeft(createAnchor("topLeft", aiTopLeft)),
  17138. top(createAnchor("top", aiTop)),
  17139. topRight(createAnchor("topRight", aiTopRight)),
  17140. right(createAnchor("right", aiRight)),
  17141. bottomRight(createAnchor("bottomRight", aiBottomRight)),
  17142. bottom(createAnchor("bottom", aiBottom)),
  17143. bottomLeft(createAnchor("bottomLeft", aiBottomLeft)),
  17144. left(createAnchor("left", aiLeft))
  17145. {
  17146. position->setCoords(0, 0);
  17147. setRotation(0);
  17148. setTextAlignment(Qt::AlignTop|Qt::AlignHCenter);
  17149. setPositionAlignment(Qt::AlignCenter);
  17150. setText("text");
  17151. setPen(Qt::NoPen);
  17152. setSelectedPen(Qt::NoPen);
  17153. setBrush(Qt::NoBrush);
  17154. setSelectedBrush(Qt::NoBrush);
  17155. setColor(Qt::black);
  17156. setSelectedColor(Qt::blue);
  17157. }
  17158. QCPItemText::~QCPItemText()
  17159. {
  17160. }
  17161. /*!
  17162. Sets the color of the text.
  17163. */
  17164. void QCPItemText::setColor(const QColor &color)
  17165. {
  17166. mColor = color;
  17167. }
  17168. /*!
  17169. Sets the color of the text that will be used when the item is selected.
  17170. */
  17171. void QCPItemText::setSelectedColor(const QColor &color)
  17172. {
  17173. mSelectedColor = color;
  17174. }
  17175. /*!
  17176. Sets the pen that will be used do draw a rectangular border around the text. To disable the
  17177. border, set \a pen to Qt::NoPen.
  17178. \see setSelectedPen, setBrush, setPadding
  17179. */
  17180. void QCPItemText::setPen(const QPen &pen)
  17181. {
  17182. mPen = pen;
  17183. }
  17184. /*!
  17185. Sets the pen that will be used do draw a rectangular border around the text, when the item is
  17186. selected. To disable the border, set \a pen to Qt::NoPen.
  17187. \see setPen
  17188. */
  17189. void QCPItemText::setSelectedPen(const QPen &pen)
  17190. {
  17191. mSelectedPen = pen;
  17192. }
  17193. /*!
  17194. Sets the brush that will be used do fill the background of the text. To disable the
  17195. background, set \a brush to Qt::NoBrush.
  17196. \see setSelectedBrush, setPen, setPadding
  17197. */
  17198. void QCPItemText::setBrush(const QBrush &brush)
  17199. {
  17200. mBrush = brush;
  17201. }
  17202. /*!
  17203. Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the
  17204. background, set \a brush to Qt::NoBrush.
  17205. \see setBrush
  17206. */
  17207. void QCPItemText::setSelectedBrush(const QBrush &brush)
  17208. {
  17209. mSelectedBrush = brush;
  17210. }
  17211. /*!
  17212. Sets the font of the text.
  17213. \see setSelectedFont, setColor
  17214. */
  17215. void QCPItemText::setFont(const QFont &font)
  17216. {
  17217. mFont = font;
  17218. }
  17219. /*!
  17220. Sets the font of the text that will be used when the item is selected.
  17221. \see setFont
  17222. */
  17223. void QCPItemText::setSelectedFont(const QFont &font)
  17224. {
  17225. mSelectedFont = font;
  17226. }
  17227. /*!
  17228. Sets the text that will be displayed. Multi-line texts are supported by inserting a line break
  17229. character, e.g. '\n'.
  17230. \see setFont, setColor, setTextAlignment
  17231. */
  17232. void QCPItemText::setText(const QString &text)
  17233. {
  17234. mText = text;
  17235. }
  17236. /*!
  17237. Sets which point of the text rect shall be aligned with \a position.
  17238. Examples:
  17239. \li If \a alignment is <tt>Qt::AlignHCenter | Qt::AlignTop</tt>, the text will be positioned such
  17240. that the top of the text rect will be horizontally centered on \a position.
  17241. \li If \a alignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt>, \a position will indicate the
  17242. bottom left corner of the text rect.
  17243. If you want to control the alignment of (multi-lined) text within the text rect, use \ref
  17244. setTextAlignment.
  17245. */
  17246. void QCPItemText::setPositionAlignment(Qt::Alignment alignment)
  17247. {
  17248. mPositionAlignment = alignment;
  17249. }
  17250. /*!
  17251. Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or Qt::AlignRight).
  17252. */
  17253. void QCPItemText::setTextAlignment(Qt::Alignment alignment)
  17254. {
  17255. mTextAlignment = alignment;
  17256. }
  17257. /*!
  17258. Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated
  17259. around \a position.
  17260. */
  17261. void QCPItemText::setRotation(double degrees)
  17262. {
  17263. mRotation = degrees;
  17264. }
  17265. /*!
  17266. Sets the distance between the border of the text rectangle and the text. The appearance (and
  17267. visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush.
  17268. */
  17269. void QCPItemText::setPadding(const QMargins &padding)
  17270. {
  17271. mPadding = padding;
  17272. }
  17273. /* inherits documentation from base class */
  17274. double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  17275. {
  17276. Q_UNUSED(details)
  17277. if (onlySelectable && !mSelectable)
  17278. return -1;
  17279. // The rect may be rotated, so we transform the actual clicked pos to the rotated
  17280. // coordinate system, so we can use the normal rectSelectTest function for non-rotated rects:
  17281. QPointF positionPixels(position->pixelPoint());
  17282. QTransform inputTransform;
  17283. inputTransform.translate(positionPixels.x(), positionPixels.y());
  17284. inputTransform.rotate(-mRotation);
  17285. inputTransform.translate(-positionPixels.x(), -positionPixels.y());
  17286. QPointF rotatedPos = inputTransform.map(pos);
  17287. QFontMetrics fontMetrics(mFont);
  17288. QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  17289. QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  17290. QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment);
  17291. textBoxRect.moveTopLeft(textPos.toPoint());
  17292. return rectSelectTest(textBoxRect, rotatedPos, true);
  17293. }
  17294. /* inherits documentation from base class */
  17295. void QCPItemText::draw(QCPPainter *painter)
  17296. {
  17297. QPointF pos(position->pixelPoint());
  17298. QTransform transform = painter->transform();
  17299. transform.translate(pos.x(), pos.y());
  17300. if (!qFuzzyIsNull(mRotation))
  17301. transform.rotate(mRotation);
  17302. painter->setFont(mainFont());
  17303. QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  17304. QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  17305. QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
  17306. textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top()));
  17307. textBoxRect.moveTopLeft(textPos.toPoint());
  17308. double clipPad = mainPen().widthF();
  17309. QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  17310. if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect())))
  17311. {
  17312. painter->setTransform(transform);
  17313. if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) ||
  17314. (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0))
  17315. {
  17316. painter->setPen(mainPen());
  17317. painter->setBrush(mainBrush());
  17318. painter->drawRect(textBoxRect);
  17319. }
  17320. painter->setBrush(Qt::NoBrush);
  17321. painter->setPen(QPen(mainColor()));
  17322. painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText);
  17323. }
  17324. }
  17325. /* inherits documentation from base class */
  17326. QPointF QCPItemText::anchorPixelPoint(int anchorId) const
  17327. {
  17328. // get actual rect points (pretty much copied from draw function):
  17329. QPointF pos(position->pixelPoint());
  17330. QTransform transform;
  17331. transform.translate(pos.x(), pos.y());
  17332. if (!qFuzzyIsNull(mRotation))
  17333. transform.rotate(mRotation);
  17334. QFontMetrics fontMetrics(mainFont());
  17335. QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  17336. QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  17337. QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
  17338. textBoxRect.moveTopLeft(textPos.toPoint());
  17339. QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect));
  17340. switch (anchorId)
  17341. {
  17342. case aiTopLeft: return rectPoly.at(0);
  17343. case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5;
  17344. case aiTopRight: return rectPoly.at(1);
  17345. case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5;
  17346. case aiBottomRight: return rectPoly.at(2);
  17347. case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5;
  17348. case aiBottomLeft: return rectPoly.at(3);
  17349. case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5;
  17350. }
  17351. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  17352. return QPointF();
  17353. }
  17354. /*! \internal
  17355. Returns the point that must be given to the QPainter::drawText function (which expects the top
  17356. left point of the text rect), according to the position \a pos, the text bounding box \a rect and
  17357. the requested \a positionAlignment.
  17358. For example, if \a positionAlignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt> the returned point
  17359. will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally
  17360. drawn at that point, the lower left corner of the resulting text rect is at \a pos.
  17361. */
  17362. QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const
  17363. {
  17364. if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop))
  17365. return pos;
  17366. QPointF result = pos; // start at top left
  17367. if (positionAlignment.testFlag(Qt::AlignHCenter))
  17368. result.rx() -= rect.width()/2.0;
  17369. else if (positionAlignment.testFlag(Qt::AlignRight))
  17370. result.rx() -= rect.width();
  17371. if (positionAlignment.testFlag(Qt::AlignVCenter))
  17372. result.ry() -= rect.height()/2.0;
  17373. else if (positionAlignment.testFlag(Qt::AlignBottom))
  17374. result.ry() -= rect.height();
  17375. return result;
  17376. }
  17377. /*! \internal
  17378. Returns the font that should be used for drawing text. Returns mFont when the item is not selected
  17379. and mSelectedFont when it is.
  17380. */
  17381. QFont QCPItemText::mainFont() const
  17382. {
  17383. return mSelected ? mSelectedFont : mFont;
  17384. }
  17385. /*! \internal
  17386. Returns the color that should be used for drawing text. Returns mColor when the item is not
  17387. selected and mSelectedColor when it is.
  17388. */
  17389. QColor QCPItemText::mainColor() const
  17390. {
  17391. return mSelected ? mSelectedColor : mColor;
  17392. }
  17393. /*! \internal
  17394. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  17395. and mSelectedPen when it is.
  17396. */
  17397. QPen QCPItemText::mainPen() const
  17398. {
  17399. return mSelected ? mSelectedPen : mPen;
  17400. }
  17401. /*! \internal
  17402. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  17403. is not selected and mSelectedBrush when it is.
  17404. */
  17405. QBrush QCPItemText::mainBrush() const
  17406. {
  17407. return mSelected ? mSelectedBrush : mBrush;
  17408. }
  17409. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17410. //////////////////// QCPItemEllipse
  17411. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17412. /*! \class QCPItemEllipse
  17413. \brief An ellipse
  17414. \image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions."
  17415. It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be drawn in.
  17416. */
  17417. /*!
  17418. Creates an ellipse item and sets default values.
  17419. The constructed item can be added to the plot with QCustomPlot::addItem.
  17420. */
  17421. QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) :
  17422. QCPAbstractItem(parentPlot),
  17423. topLeft(createPosition("topLeft")),
  17424. bottomRight(createPosition("bottomRight")),
  17425. topLeftRim(createAnchor("topLeftRim", aiTopLeftRim)),
  17426. top(createAnchor("top", aiTop)),
  17427. topRightRim(createAnchor("topRightRim", aiTopRightRim)),
  17428. right(createAnchor("right", aiRight)),
  17429. bottomRightRim(createAnchor("bottomRightRim", aiBottomRightRim)),
  17430. bottom(createAnchor("bottom", aiBottom)),
  17431. bottomLeftRim(createAnchor("bottomLeftRim", aiBottomLeftRim)),
  17432. left(createAnchor("left", aiLeft)),
  17433. center(createAnchor("center", aiCenter))
  17434. {
  17435. topLeft->setCoords(0, 1);
  17436. bottomRight->setCoords(1, 0);
  17437. setPen(QPen(Qt::black));
  17438. setSelectedPen(QPen(Qt::blue, 2));
  17439. setBrush(Qt::NoBrush);
  17440. setSelectedBrush(Qt::NoBrush);
  17441. }
  17442. QCPItemEllipse::~QCPItemEllipse()
  17443. {
  17444. }
  17445. /*!
  17446. Sets the pen that will be used to draw the line of the ellipse
  17447. \see setSelectedPen, setBrush
  17448. */
  17449. void QCPItemEllipse::setPen(const QPen &pen)
  17450. {
  17451. mPen = pen;
  17452. }
  17453. /*!
  17454. Sets the pen that will be used to draw the line of the ellipse when selected
  17455. \see setPen, setSelected
  17456. */
  17457. void QCPItemEllipse::setSelectedPen(const QPen &pen)
  17458. {
  17459. mSelectedPen = pen;
  17460. }
  17461. /*!
  17462. Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to
  17463. Qt::NoBrush.
  17464. \see setSelectedBrush, setPen
  17465. */
  17466. void QCPItemEllipse::setBrush(const QBrush &brush)
  17467. {
  17468. mBrush = brush;
  17469. }
  17470. /*!
  17471. Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a
  17472. brush to Qt::NoBrush.
  17473. \see setBrush
  17474. */
  17475. void QCPItemEllipse::setSelectedBrush(const QBrush &brush)
  17476. {
  17477. mSelectedBrush = brush;
  17478. }
  17479. /* inherits documentation from base class */
  17480. double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  17481. {
  17482. Q_UNUSED(details)
  17483. if (onlySelectable && !mSelectable)
  17484. return -1;
  17485. double result = -1;
  17486. QPointF p1 = topLeft->pixelPoint();
  17487. QPointF p2 = bottomRight->pixelPoint();
  17488. QPointF center((p1+p2)/2.0);
  17489. double a = qAbs(p1.x()-p2.x())/2.0;
  17490. double b = qAbs(p1.y()-p2.y())/2.0;
  17491. double x = pos.x()-center.x();
  17492. double y = pos.y()-center.y();
  17493. // distance to border:
  17494. double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b));
  17495. result = qAbs(c-1)*qSqrt(x*x+y*y);
  17496. // filled ellipse, allow click inside to count as hit:
  17497. if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
  17498. {
  17499. if (x*x/(a*a) + y*y/(b*b) <= 1)
  17500. result = mParentPlot->selectionTolerance()*0.99;
  17501. }
  17502. return result;
  17503. }
  17504. /* inherits documentation from base class */
  17505. void QCPItemEllipse::draw(QCPPainter *painter)
  17506. {
  17507. QPointF p1 = topLeft->pixelPoint();
  17508. QPointF p2 = bottomRight->pixelPoint();
  17509. if (p1.toPoint() == p2.toPoint())
  17510. return;
  17511. QRectF ellipseRect = QRectF(p1, p2).normalized();
  17512. QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
  17513. if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect
  17514. {
  17515. painter->setPen(mainPen());
  17516. painter->setBrush(mainBrush());
  17517. #ifdef __EXCEPTIONS
  17518. try // drawEllipse sometimes throws exceptions if ellipse is too big
  17519. {
  17520. #endif
  17521. painter->drawEllipse(ellipseRect);
  17522. #ifdef __EXCEPTIONS
  17523. } catch (...)
  17524. {
  17525. qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible";
  17526. setVisible(false);
  17527. }
  17528. #endif
  17529. }
  17530. }
  17531. /* inherits documentation from base class */
  17532. QPointF QCPItemEllipse::anchorPixelPoint(int anchorId) const
  17533. {
  17534. QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint());
  17535. switch (anchorId)
  17536. {
  17537. case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2);
  17538. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  17539. case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2);
  17540. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  17541. case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2);
  17542. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  17543. case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2);
  17544. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
  17545. case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5;
  17546. }
  17547. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  17548. return QPointF();
  17549. }
  17550. /*! \internal
  17551. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  17552. and mSelectedPen when it is.
  17553. */
  17554. QPen QCPItemEllipse::mainPen() const
  17555. {
  17556. return mSelected ? mSelectedPen : mPen;
  17557. }
  17558. /*! \internal
  17559. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  17560. is not selected and mSelectedBrush when it is.
  17561. */
  17562. QBrush QCPItemEllipse::mainBrush() const
  17563. {
  17564. return mSelected ? mSelectedBrush : mBrush;
  17565. }
  17566. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17567. //////////////////// QCPItemPixmap
  17568. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17569. /*! \class QCPItemPixmap
  17570. \brief An arbitrary pixmap
  17571. \image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions."
  17572. It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will
  17573. be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to
  17574. fit the rectangle or be drawn aligned to the topLeft position.
  17575. If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown
  17576. on the right side of the example image), the pixmap will be flipped in the respective
  17577. orientations.
  17578. */
  17579. /*!
  17580. Creates a rectangle item and sets default values.
  17581. The constructed item can be added to the plot with QCustomPlot::addItem.
  17582. */
  17583. QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) :
  17584. QCPAbstractItem(parentPlot),
  17585. topLeft(createPosition("topLeft")),
  17586. bottomRight(createPosition("bottomRight")),
  17587. top(createAnchor("top", aiTop)),
  17588. topRight(createAnchor("topRight", aiTopRight)),
  17589. right(createAnchor("right", aiRight)),
  17590. bottom(createAnchor("bottom", aiBottom)),
  17591. bottomLeft(createAnchor("bottomLeft", aiBottomLeft)),
  17592. left(createAnchor("left", aiLeft))
  17593. {
  17594. topLeft->setCoords(0, 1);
  17595. bottomRight->setCoords(1, 0);
  17596. setPen(Qt::NoPen);
  17597. setSelectedPen(QPen(Qt::blue));
  17598. setScaled(false, Qt::KeepAspectRatio);
  17599. }
  17600. QCPItemPixmap::~QCPItemPixmap()
  17601. {
  17602. }
  17603. /*!
  17604. Sets the pixmap that will be displayed.
  17605. */
  17606. void QCPItemPixmap::setPixmap(const QPixmap &pixmap)
  17607. {
  17608. mPixmap = pixmap;
  17609. if (mPixmap.isNull())
  17610. qDebug() << Q_FUNC_INFO << "pixmap is null";
  17611. }
  17612. /*!
  17613. Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a
  17614. bottomRight positions.
  17615. */
  17616. void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode)
  17617. {
  17618. mScaled = scaled;
  17619. mAspectRatioMode = aspectRatioMode;
  17620. updateScaledPixmap();
  17621. }
  17622. /*!
  17623. Sets the pen that will be used to draw a border around the pixmap.
  17624. \see setSelectedPen, setBrush
  17625. */
  17626. void QCPItemPixmap::setPen(const QPen &pen)
  17627. {
  17628. mPen = pen;
  17629. }
  17630. /*!
  17631. Sets the pen that will be used to draw a border around the pixmap when selected
  17632. \see setPen, setSelected
  17633. */
  17634. void QCPItemPixmap::setSelectedPen(const QPen &pen)
  17635. {
  17636. mSelectedPen = pen;
  17637. }
  17638. /* inherits documentation from base class */
  17639. double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  17640. {
  17641. Q_UNUSED(details)
  17642. if (onlySelectable && !mSelectable)
  17643. return -1;
  17644. return rectSelectTest(getFinalRect(), pos, true);
  17645. }
  17646. /* inherits documentation from base class */
  17647. void QCPItemPixmap::draw(QCPPainter *painter)
  17648. {
  17649. bool flipHorz = false;
  17650. bool flipVert = false;
  17651. QRect rect = getFinalRect(&flipHorz, &flipVert);
  17652. double clipPad = mainPen().style() == Qt::NoPen ? 0 : mainPen().widthF();
  17653. QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  17654. if (boundingRect.intersects(clipRect()))
  17655. {
  17656. updateScaledPixmap(rect, flipHorz, flipVert);
  17657. painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap);
  17658. QPen pen = mainPen();
  17659. if (pen.style() != Qt::NoPen)
  17660. {
  17661. painter->setPen(pen);
  17662. painter->setBrush(Qt::NoBrush);
  17663. painter->drawRect(rect);
  17664. }
  17665. }
  17666. }
  17667. /* inherits documentation from base class */
  17668. QPointF QCPItemPixmap::anchorPixelPoint(int anchorId) const
  17669. {
  17670. bool flipHorz;
  17671. bool flipVert;
  17672. QRect rect = getFinalRect(&flipHorz, &flipVert);
  17673. // we actually want denormal rects (negative width/height) here, so restore
  17674. // the flipped state:
  17675. if (flipHorz)
  17676. rect.adjust(rect.width(), 0, -rect.width(), 0);
  17677. if (flipVert)
  17678. rect.adjust(0, rect.height(), 0, -rect.height());
  17679. switch (anchorId)
  17680. {
  17681. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  17682. case aiTopRight: return rect.topRight();
  17683. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  17684. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  17685. case aiBottomLeft: return rect.bottomLeft();
  17686. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;;
  17687. }
  17688. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  17689. return QPointF();
  17690. }
  17691. /*! \internal
  17692. Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The
  17693. parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped
  17694. horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a
  17695. bottomRight.)
  17696. This function only creates the scaled pixmap when the buffered pixmap has a different size than
  17697. the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does
  17698. not cause expensive rescaling every time.
  17699. If scaling is disabled, sets mScaledPixmap to a null QPixmap.
  17700. */
  17701. void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert)
  17702. {
  17703. if (mPixmap.isNull())
  17704. return;
  17705. if (mScaled)
  17706. {
  17707. if (finalRect.isNull())
  17708. finalRect = getFinalRect(&flipHorz, &flipVert);
  17709. if (finalRect.size() != mScaledPixmap.size())
  17710. {
  17711. mScaledPixmap = mPixmap.scaled(finalRect.size(), mAspectRatioMode, Qt::SmoothTransformation);
  17712. if (flipHorz || flipVert)
  17713. mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert));
  17714. }
  17715. } else if (!mScaledPixmap.isNull())
  17716. mScaledPixmap = QPixmap();
  17717. }
  17718. /*! \internal
  17719. Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions
  17720. and scaling settings.
  17721. The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn
  17722. flipped horizontally or vertically in the returned rect. (The returned rect itself is always
  17723. normalized, i.e. the top left corner of the rect is actually further to the top/left than the
  17724. bottom right corner). This is the case when the item position \a topLeft is further to the
  17725. bottom/right than \a bottomRight.
  17726. If scaling is disabled, returns a rect with size of the original pixmap and the top left corner
  17727. aligned with the item position \a topLeft. The position \a bottomRight is ignored.
  17728. */
  17729. QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const
  17730. {
  17731. QRect result;
  17732. bool flipHorz = false;
  17733. bool flipVert = false;
  17734. QPoint p1 = topLeft->pixelPoint().toPoint();
  17735. QPoint p2 = bottomRight->pixelPoint().toPoint();
  17736. if (p1 == p2)
  17737. return QRect(p1, QSize(0, 0));
  17738. if (mScaled)
  17739. {
  17740. QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y());
  17741. QPoint topLeft = p1;
  17742. if (newSize.width() < 0)
  17743. {
  17744. flipHorz = true;
  17745. newSize.rwidth() *= -1;
  17746. topLeft.setX(p2.x());
  17747. }
  17748. if (newSize.height() < 0)
  17749. {
  17750. flipVert = true;
  17751. newSize.rheight() *= -1;
  17752. topLeft.setY(p2.y());
  17753. }
  17754. QSize scaledSize = mPixmap.size();
  17755. scaledSize.scale(newSize, mAspectRatioMode);
  17756. result = QRect(topLeft, scaledSize);
  17757. } else
  17758. {
  17759. result = QRect(p1, mPixmap.size());
  17760. }
  17761. if (flippedHorz)
  17762. *flippedHorz = flipHorz;
  17763. if (flippedVert)
  17764. *flippedVert = flipVert;
  17765. return result;
  17766. }
  17767. /*! \internal
  17768. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  17769. and mSelectedPen when it is.
  17770. */
  17771. QPen QCPItemPixmap::mainPen() const
  17772. {
  17773. return mSelected ? mSelectedPen : mPen;
  17774. }
  17775. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17776. //////////////////// QCPItemTracer
  17777. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17778. /*! \class QCPItemTracer
  17779. \brief Item that sticks to QCPGraph data points
  17780. \image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs are positions."
  17781. The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt
  17782. the coordinate axes of the graph and update its \a position to be on the graph's data. This means
  17783. the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a
  17784. QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a
  17785. position will have no effect because they will be overriden in the next redraw (this is when the
  17786. coordinate update happens).
  17787. If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will
  17788. stay at the corresponding end of the graph.
  17789. With \ref setInterpolating you may specify whether the tracer may only stay exactly on data
  17790. points or whether it interpolates data points linearly, if given a key that lies between two data
  17791. points of the graph.
  17792. The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer
  17793. have no own visual appearance (set the style to \ref tsNone), and just connect other item
  17794. positions to the tracer \a position (used as an anchor) via \ref
  17795. QCPItemPosition::setParentAnchor.
  17796. \note The tracer position is only automatically updated upon redraws. So when the data of the
  17797. graph changes and immediately afterwards (without a redraw) the a position coordinates of the
  17798. tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref
  17799. updatePosition must be called manually, prior to reading the tracer coordinates.
  17800. */
  17801. /*!
  17802. Creates a tracer item and sets default values.
  17803. The constructed item can be added to the plot with QCustomPlot::addItem.
  17804. */
  17805. QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) :
  17806. QCPAbstractItem(parentPlot),
  17807. position(createPosition("position")),
  17808. mGraph(0)
  17809. {
  17810. position->setCoords(0, 0);
  17811. setBrush(Qt::NoBrush);
  17812. setSelectedBrush(Qt::NoBrush);
  17813. setPen(QPen(Qt::black));
  17814. setSelectedPen(QPen(Qt::blue, 2));
  17815. setStyle(tsCrosshair);
  17816. setSize(6);
  17817. setInterpolating(false);
  17818. setGraphKey(0);
  17819. }
  17820. QCPItemTracer::~QCPItemTracer()
  17821. {
  17822. }
  17823. /*!
  17824. Sets the pen that will be used to draw the line of the tracer
  17825. \see setSelectedPen, setBrush
  17826. */
  17827. void QCPItemTracer::setPen(const QPen &pen)
  17828. {
  17829. mPen = pen;
  17830. }
  17831. /*!
  17832. Sets the pen that will be used to draw the line of the tracer when selected
  17833. \see setPen, setSelected
  17834. */
  17835. void QCPItemTracer::setSelectedPen(const QPen &pen)
  17836. {
  17837. mSelectedPen = pen;
  17838. }
  17839. /*!
  17840. Sets the brush that will be used to draw any fills of the tracer
  17841. \see setSelectedBrush, setPen
  17842. */
  17843. void QCPItemTracer::setBrush(const QBrush &brush)
  17844. {
  17845. mBrush = brush;
  17846. }
  17847. /*!
  17848. Sets the brush that will be used to draw any fills of the tracer, when selected.
  17849. \see setBrush, setSelected
  17850. */
  17851. void QCPItemTracer::setSelectedBrush(const QBrush &brush)
  17852. {
  17853. mSelectedBrush = brush;
  17854. }
  17855. /*!
  17856. Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare
  17857. does, \ref tsCrosshair does not).
  17858. */
  17859. void QCPItemTracer::setSize(double size)
  17860. {
  17861. mSize = size;
  17862. }
  17863. /*!
  17864. Sets the style/visual appearance of the tracer.
  17865. If you only want to use the tracer \a position as an anchor for other items, set \a style to
  17866. \ref tsNone.
  17867. */
  17868. void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style)
  17869. {
  17870. mStyle = style;
  17871. }
  17872. /*!
  17873. Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type
  17874. QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph.
  17875. To free the tracer from any graph, set \a graph to 0. The tracer \a position can then be placed
  17876. freely like any other item position. This is the state the tracer will assume when its graph gets
  17877. deleted while still attached to it.
  17878. \see setGraphKey
  17879. */
  17880. void QCPItemTracer::setGraph(QCPGraph *graph)
  17881. {
  17882. if (graph)
  17883. {
  17884. if (graph->parentPlot() == mParentPlot)
  17885. {
  17886. position->setType(QCPItemPosition::ptPlotCoords);
  17887. position->setAxes(graph->keyAxis(), graph->valueAxis());
  17888. mGraph = graph;
  17889. updatePosition();
  17890. } else
  17891. qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item";
  17892. } else
  17893. {
  17894. mGraph = 0;
  17895. }
  17896. }
  17897. /*!
  17898. Sets the key of the graph's data point the tracer will be positioned at. This is the only free
  17899. coordinate of a tracer when attached to a graph.
  17900. Depending on \ref setInterpolating, the tracer will be either positioned on the data point
  17901. closest to \a key, or will stay exactly at \a key and interpolate the value linearly.
  17902. \see setGraph, setInterpolating
  17903. */
  17904. void QCPItemTracer::setGraphKey(double key)
  17905. {
  17906. mGraphKey = key;
  17907. }
  17908. /*!
  17909. Sets whether the value of the graph's data points shall be interpolated, when positioning the
  17910. tracer.
  17911. If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on
  17912. the data point of the graph which is closest to the key, but which is not necessarily exactly
  17913. there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and
  17914. the appropriate value will be interpolated from the graph's data points linearly.
  17915. \see setGraph, setGraphKey
  17916. */
  17917. void QCPItemTracer::setInterpolating(bool enabled)
  17918. {
  17919. mInterpolating = enabled;
  17920. }
  17921. /* inherits documentation from base class */
  17922. double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  17923. {
  17924. Q_UNUSED(details)
  17925. if (onlySelectable && !mSelectable)
  17926. return -1;
  17927. QPointF center(position->pixelPoint());
  17928. double w = mSize/2.0;
  17929. QRect clip = clipRect();
  17930. switch (mStyle)
  17931. {
  17932. case tsNone: return -1;
  17933. case tsPlus:
  17934. {
  17935. if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  17936. return qSqrt(qMin(distSqrToLine(center+QPointF(-w, 0), center+QPointF(w, 0), pos),
  17937. distSqrToLine(center+QPointF(0, -w), center+QPointF(0, w), pos)));
  17938. break;
  17939. }
  17940. case tsCrosshair:
  17941. {
  17942. return qSqrt(qMin(distSqrToLine(QPointF(clip.left(), center.y()), QPointF(clip.right(), center.y()), pos),
  17943. distSqrToLine(QPointF(center.x(), clip.top()), QPointF(center.x(), clip.bottom()), pos)));
  17944. }
  17945. case tsCircle:
  17946. {
  17947. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  17948. {
  17949. // distance to border:
  17950. double centerDist = QVector2D(center-pos).length();
  17951. double circleLine = w;
  17952. double result = qAbs(centerDist-circleLine);
  17953. // filled ellipse, allow click inside to count as hit:
  17954. if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
  17955. {
  17956. if (centerDist <= circleLine)
  17957. result = mParentPlot->selectionTolerance()*0.99;
  17958. }
  17959. return result;
  17960. }
  17961. break;
  17962. }
  17963. case tsSquare:
  17964. {
  17965. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  17966. {
  17967. QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w));
  17968. bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
  17969. return rectSelectTest(rect, pos, filledRect);
  17970. }
  17971. break;
  17972. }
  17973. }
  17974. return -1;
  17975. }
  17976. /* inherits documentation from base class */
  17977. void QCPItemTracer::draw(QCPPainter *painter)
  17978. {
  17979. updatePosition();
  17980. if (mStyle == tsNone)
  17981. return;
  17982. painter->setPen(mainPen());
  17983. painter->setBrush(mainBrush());
  17984. QPointF center(position->pixelPoint());
  17985. double w = mSize/2.0;
  17986. QRect clip = clipRect();
  17987. switch (mStyle)
  17988. {
  17989. case tsNone: return;
  17990. case tsPlus:
  17991. {
  17992. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  17993. {
  17994. painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0)));
  17995. painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w)));
  17996. }
  17997. break;
  17998. }
  17999. case tsCrosshair:
  18000. {
  18001. if (center.y() > clip.top() && center.y() < clip.bottom())
  18002. painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y()));
  18003. if (center.x() > clip.left() && center.x() < clip.right())
  18004. painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom()));
  18005. break;
  18006. }
  18007. case tsCircle:
  18008. {
  18009. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  18010. painter->drawEllipse(center, w, w);
  18011. break;
  18012. }
  18013. case tsSquare:
  18014. {
  18015. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  18016. painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w)));
  18017. break;
  18018. }
  18019. }
  18020. }
  18021. /*!
  18022. If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a
  18023. position to reside on the graph data, depending on the configured key (\ref setGraphKey).
  18024. It is called automatically on every redraw and normally doesn't need to be called manually. One
  18025. exception is when you want to read the tracer coordinates via \a position and are not sure that
  18026. the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw.
  18027. In that situation, call this function before accessing \a position, to make sure you don't get
  18028. out-of-date coordinates.
  18029. If there is no graph set on this tracer, this function does nothing.
  18030. */
  18031. void QCPItemTracer::updatePosition()
  18032. {
  18033. if (mGraph)
  18034. {
  18035. if (mParentPlot->hasPlottable(mGraph))
  18036. {
  18037. if (mGraph->data()->size() > 1)
  18038. {
  18039. QCPDataMap::const_iterator first = mGraph->data()->constBegin();
  18040. QCPDataMap::const_iterator last = mGraph->data()->constEnd()-1;
  18041. if (mGraphKey < first.key())
  18042. position->setCoords(first.key(), first.value().value);
  18043. else if (mGraphKey > last.key())
  18044. position->setCoords(last.key(), last.value().value);
  18045. else
  18046. {
  18047. QCPDataMap::const_iterator it = mGraph->data()->lowerBound(mGraphKey);
  18048. if (it != first) // mGraphKey is somewhere between iterators
  18049. {
  18050. QCPDataMap::const_iterator prevIt = it-1;
  18051. if (mInterpolating)
  18052. {
  18053. // interpolate between iterators around mGraphKey:
  18054. double slope = 0;
  18055. if (!qFuzzyCompare((double)it.key(), (double)prevIt.key()))
  18056. slope = (it.value().value-prevIt.value().value)/(it.key()-prevIt.key());
  18057. position->setCoords(mGraphKey, (mGraphKey-prevIt.key())*slope+prevIt.value().value);
  18058. } else
  18059. {
  18060. // find iterator with key closest to mGraphKey:
  18061. if (mGraphKey < (prevIt.key()+it.key())*0.5)
  18062. it = prevIt;
  18063. position->setCoords(it.key(), it.value().value);
  18064. }
  18065. } else // mGraphKey is exactly on first iterator
  18066. position->setCoords(it.key(), it.value().value);
  18067. }
  18068. } else if (mGraph->data()->size() == 1)
  18069. {
  18070. QCPDataMap::const_iterator it = mGraph->data()->constBegin();
  18071. position->setCoords(it.key(), it.value().value);
  18072. } else
  18073. qDebug() << Q_FUNC_INFO << "graph has no data";
  18074. } else
  18075. qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)";
  18076. }
  18077. }
  18078. /*! \internal
  18079. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  18080. and mSelectedPen when it is.
  18081. */
  18082. QPen QCPItemTracer::mainPen() const
  18083. {
  18084. return mSelected ? mSelectedPen : mPen;
  18085. }
  18086. /*! \internal
  18087. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  18088. is not selected and mSelectedBrush when it is.
  18089. */
  18090. QBrush QCPItemTracer::mainBrush() const
  18091. {
  18092. return mSelected ? mSelectedBrush : mBrush;
  18093. }
  18094. ////////////////////////////////////////////////////////////////////////////////////////////////////
  18095. //////////////////// QCPItemBracket
  18096. ////////////////////////////////////////////////////////////////////////////////////////////////////
  18097. /*! \class QCPItemBracket
  18098. \brief A bracket for referencing/highlighting certain parts in the plot.
  18099. \image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs are positions."
  18100. It has two positions, \a left and \a right, which define the span of the bracket. If \a left is
  18101. actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the
  18102. example image.
  18103. The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket
  18104. stretches away from the embraced span, can be controlled with \ref setLength.
  18105. \image html QCPItemBracket-length.png
  18106. <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
  18107. bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
  18108. It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine
  18109. or QCPItemCurve) or a text label (QCPItemText), to the bracket.
  18110. */
  18111. /*!
  18112. Creates a bracket item and sets default values.
  18113. The constructed item can be added to the plot with QCustomPlot::addItem.
  18114. */
  18115. QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) :
  18116. QCPAbstractItem(parentPlot),
  18117. left(createPosition("left")),
  18118. right(createPosition("right")),
  18119. center(createAnchor("center", aiCenter))
  18120. {
  18121. left->setCoords(0, 0);
  18122. right->setCoords(1, 1);
  18123. setPen(QPen(Qt::black));
  18124. setSelectedPen(QPen(Qt::blue, 2));
  18125. setLength(8);
  18126. setStyle(bsCalligraphic);
  18127. }
  18128. QCPItemBracket::~QCPItemBracket()
  18129. {
  18130. }
  18131. /*!
  18132. Sets the pen that will be used to draw the bracket.
  18133. Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the
  18134. stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use
  18135. \ref setLength, which has a similar effect.
  18136. \see setSelectedPen
  18137. */
  18138. void QCPItemBracket::setPen(const QPen &pen)
  18139. {
  18140. mPen = pen;
  18141. }
  18142. /*!
  18143. Sets the pen that will be used to draw the bracket when selected
  18144. \see setPen, setSelected
  18145. */
  18146. void QCPItemBracket::setSelectedPen(const QPen &pen)
  18147. {
  18148. mSelectedPen = pen;
  18149. }
  18150. /*!
  18151. Sets the \a length in pixels how far the bracket extends in the direction towards the embraced
  18152. span of the bracket (i.e. perpendicular to the <i>left</i>-<i>right</i>-direction)
  18153. \image html QCPItemBracket-length.png
  18154. <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
  18155. bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
  18156. */
  18157. void QCPItemBracket::setLength(double length)
  18158. {
  18159. mLength = length;
  18160. }
  18161. /*!
  18162. Sets the style of the bracket, i.e. the shape/visual appearance.
  18163. \see setPen
  18164. */
  18165. void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style)
  18166. {
  18167. mStyle = style;
  18168. }
  18169. /* inherits documentation from base class */
  18170. double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  18171. {
  18172. Q_UNUSED(details)
  18173. if (onlySelectable && !mSelectable)
  18174. return -1;
  18175. QVector2D leftVec(left->pixelPoint());
  18176. QVector2D rightVec(right->pixelPoint());
  18177. if (leftVec.toPoint() == rightVec.toPoint())
  18178. return -1;
  18179. QVector2D widthVec = (rightVec-leftVec)*0.5f;
  18180. QVector2D lengthVec(-widthVec.y(), widthVec.x());
  18181. lengthVec = lengthVec.normalized()*mLength;
  18182. QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec;
  18183. return qSqrt(distSqrToLine((centerVec-widthVec).toPointF(), (centerVec+widthVec).toPointF(), pos));
  18184. }
  18185. /* inherits documentation from base class */
  18186. void QCPItemBracket::draw(QCPPainter *painter)
  18187. {
  18188. QVector2D leftVec(left->pixelPoint());
  18189. QVector2D rightVec(right->pixelPoint());
  18190. if (leftVec.toPoint() == rightVec.toPoint())
  18191. return;
  18192. QVector2D widthVec = (rightVec-leftVec)*0.5f;
  18193. QVector2D lengthVec(-widthVec.y(), widthVec.x());
  18194. lengthVec = lengthVec.normalized()*mLength;
  18195. QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec;
  18196. QPolygon boundingPoly;
  18197. boundingPoly << leftVec.toPoint() << rightVec.toPoint()
  18198. << (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint();
  18199. QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
  18200. if (clip.intersects(boundingPoly.boundingRect()))
  18201. {
  18202. painter->setPen(mainPen());
  18203. switch (mStyle)
  18204. {
  18205. case bsSquare:
  18206. {
  18207. painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF());
  18208. painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
  18209. painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  18210. break;
  18211. }
  18212. case bsRound:
  18213. {
  18214. painter->setBrush(Qt::NoBrush);
  18215. QPainterPath path;
  18216. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  18217. path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF());
  18218. path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  18219. painter->drawPath(path);
  18220. break;
  18221. }
  18222. case bsCurly:
  18223. {
  18224. painter->setBrush(Qt::NoBrush);
  18225. QPainterPath path;
  18226. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  18227. path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+lengthVec).toPointF(), centerVec.toPointF());
  18228. path.cubicTo((centerVec-0.4f*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  18229. painter->drawPath(path);
  18230. break;
  18231. }
  18232. case bsCalligraphic:
  18233. {
  18234. painter->setPen(Qt::NoPen);
  18235. painter->setBrush(QBrush(mainPen().color()));
  18236. QPainterPath path;
  18237. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  18238. path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+0.8f*lengthVec).toPointF(), centerVec.toPointF());
  18239. path.cubicTo((centerVec-0.4f*widthVec+0.8f*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  18240. path.cubicTo((centerVec-widthVec-lengthVec*0.5f).toPointF(), (centerVec-0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+lengthVec*0.2f).toPointF());
  18241. path.cubicTo((centerVec+0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5f).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
  18242. painter->drawPath(path);
  18243. break;
  18244. }
  18245. }
  18246. }
  18247. }
  18248. /* inherits documentation from base class */
  18249. QPointF QCPItemBracket::anchorPixelPoint(int anchorId) const
  18250. {
  18251. QVector2D leftVec(left->pixelPoint());
  18252. QVector2D rightVec(right->pixelPoint());
  18253. if (leftVec.toPoint() == rightVec.toPoint())
  18254. return leftVec.toPointF();
  18255. QVector2D widthVec = (rightVec-leftVec)*0.5f;
  18256. QVector2D lengthVec(-widthVec.y(), widthVec.x());
  18257. lengthVec = lengthVec.normalized()*mLength;
  18258. QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec;
  18259. switch (anchorId)
  18260. {
  18261. case aiCenter:
  18262. return centerVec.toPointF();
  18263. }
  18264. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  18265. return QPointF();
  18266. }
  18267. /*! \internal
  18268. Returns the pen that should be used for drawing lines. Returns mPen when the
  18269. item is not selected and mSelectedPen when it is.
  18270. */
  18271. QPen QCPItemBracket::mainPen() const
  18272. {
  18273. return mSelected ? mSelectedPen : mPen;
  18274. }