Нет описания

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 "qcustomplot.h"
  26. ////////////////////////////////////////////////////////////////////////////////////////////////////
  27. //////////////////// QCPPainter
  28. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29. /*! \class QCPPainter
  30. \brief QPainter subclass used internally
  31. This QPainter subclass is used to provide some extended functionality e.g. for tweaking position
  32. consistency between antialiased and non-antialiased painting. Further it provides workarounds
  33. for QPainter quirks.
  34. \warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and
  35. restore. So while it is possible to pass a QCPPainter instance to a function that expects a
  36. QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because
  37. it will call the base class implementations of the functions actually hidden by QCPPainter).
  38. */
  39. /*!
  40. Creates a new QCPPainter instance and sets default values
  41. */
  42. QCPPainter::QCPPainter() :
  43. QPainter(),
  44. mModes(pmDefault),
  45. mIsAntialiasing(false)
  46. {
  47. // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and
  48. // a call to begin() will follow
  49. }
  50. /*!
  51. Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just
  52. like the analogous QPainter constructor, begins painting on \a device immediately.
  53. Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5.
  54. */
  55. QCPPainter::QCPPainter(QPaintDevice *device) :
  56. QPainter(device),
  57. mModes(pmDefault),
  58. mIsAntialiasing(false)
  59. {
  60. #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.
  61. if (isActive())
  62. setRenderHint(QPainter::NonCosmeticDefaultPen);
  63. #endif
  64. }
  65. QCPPainter::~QCPPainter()
  66. {
  67. }
  68. /*!
  69. Sets the pen of the painter and applies certain fixes to it, depending on the mode of this
  70. QCPPainter.
  71. \note this function hides the non-virtual base class implementation.
  72. */
  73. void QCPPainter::setPen(const QPen &pen)
  74. {
  75. QPainter::setPen(pen);
  76. if (mModes.testFlag(pmNonCosmetic))
  77. makeNonCosmetic();
  78. }
  79. /*! \overload
  80. Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of
  81. this QCPPainter.
  82. \note this function hides the non-virtual base class implementation.
  83. */
  84. void QCPPainter::setPen(const QColor &color)
  85. {
  86. QPainter::setPen(color);
  87. if (mModes.testFlag(pmNonCosmetic))
  88. makeNonCosmetic();
  89. }
  90. /*! \overload
  91. Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of
  92. this QCPPainter.
  93. \note this function hides the non-virtual base class implementation.
  94. */
  95. void QCPPainter::setPen(Qt::PenStyle penStyle)
  96. {
  97. QPainter::setPen(penStyle);
  98. if (mModes.testFlag(pmNonCosmetic))
  99. makeNonCosmetic();
  100. }
  101. /*! \overload
  102. Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when
  103. antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to
  104. integer coordinates and then passes it to the original drawLine.
  105. \note this function hides the non-virtual base class implementation.
  106. */
  107. void QCPPainter::drawLine(const QLineF &line)
  108. {
  109. if (mIsAntialiasing || mModes.testFlag(pmVectorized))
  110. QPainter::drawLine(line);
  111. else
  112. QPainter::drawLine(line.toLine());
  113. }
  114. /*!
  115. Sets whether painting uses antialiasing or not. Use this method instead of using setRenderHint
  116. with QPainter::Antialiasing directly, as it allows QCPPainter to regain pixel exactness between
  117. antialiased and non-antialiased painting (Since Qt < 5.0 uses slightly different coordinate systems for
  118. AA/Non-AA painting).
  119. */
  120. void QCPPainter::setAntialiasing(bool enabled)
  121. {
  122. setRenderHint(QPainter::Antialiasing, enabled);
  123. if (mIsAntialiasing != enabled)
  124. {
  125. mIsAntialiasing = enabled;
  126. if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs
  127. {
  128. if (mIsAntialiasing)
  129. translate(0.5, 0.5);
  130. else
  131. translate(-0.5, -0.5);
  132. }
  133. }
  134. }
  135. /*!
  136. Sets the mode of the painter. This controls whether the painter shall adjust its
  137. fixes/workarounds optimized for certain output devices.
  138. */
  139. void QCPPainter::setModes(QCPPainter::PainterModes modes)
  140. {
  141. mModes = modes;
  142. }
  143. /*!
  144. Sets the QPainter::NonCosmeticDefaultPen in Qt versions before Qt5 after beginning painting on \a
  145. device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5,
  146. all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that
  147. behaviour.
  148. The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets
  149. the render hint as appropriate.
  150. \note this function hides the non-virtual base class implementation.
  151. */
  152. bool QCPPainter::begin(QPaintDevice *device)
  153. {
  154. bool result = QPainter::begin(device);
  155. #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.
  156. if (result)
  157. setRenderHint(QPainter::NonCosmeticDefaultPen);
  158. #endif
  159. return result;
  160. }
  161. /*! \overload
  162. Sets the mode of the painter. This controls whether the painter shall adjust its
  163. fixes/workarounds optimized for certain output devices.
  164. */
  165. void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled)
  166. {
  167. if (!enabled && mModes.testFlag(mode))
  168. mModes &= ~mode;
  169. else if (enabled && !mModes.testFlag(mode))
  170. mModes |= mode;
  171. }
  172. /*!
  173. Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to
  174. QPainter, the save/restore functions are reimplemented to also save/restore those members.
  175. \note this function hides the non-virtual base class implementation.
  176. \see restore
  177. */
  178. void QCPPainter::save()
  179. {
  180. mAntialiasingStack.push(mIsAntialiasing);
  181. QPainter::save();
  182. }
  183. /*!
  184. Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to
  185. QPainter, the save/restore functions are reimplemented to also save/restore those members.
  186. \note this function hides the non-virtual base class implementation.
  187. \see save
  188. */
  189. void QCPPainter::restore()
  190. {
  191. if (!mAntialiasingStack.isEmpty())
  192. mIsAntialiasing = mAntialiasingStack.pop();
  193. else
  194. qDebug() << Q_FUNC_INFO << "Unbalanced save/restore";
  195. QPainter::restore();
  196. }
  197. /*!
  198. Changes the pen width to 1 if it currently is 0. This function is called in the \ref setPen
  199. overrides when the \ref pmNonCosmetic mode is set.
  200. */
  201. void QCPPainter::makeNonCosmetic()
  202. {
  203. if (qFuzzyIsNull(pen().widthF()))
  204. {
  205. QPen p = pen();
  206. p.setWidth(1);
  207. QPainter::setPen(p);
  208. }
  209. }
  210. ////////////////////////////////////////////////////////////////////////////////////////////////////
  211. //////////////////// QCPScatterStyle
  212. ////////////////////////////////////////////////////////////////////////////////////////////////////
  213. /*! \class QCPScatterStyle
  214. \brief Represents the visual appearance of scatter points
  215. This class holds information about shape, color and size of scatter points. In plottables like
  216. QCPGraph it is used to store how scatter points shall be drawn. For example, \ref
  217. QCPGraph::setScatterStyle takes a QCPScatterStyle instance.
  218. A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a
  219. fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can
  220. be controlled with \ref setSize.
  221. \section QCPScatterStyle-defining Specifying a scatter style
  222. You can set all these configurations either by calling the respective functions on an instance:
  223. \code
  224. QCPScatterStyle myScatter;
  225. myScatter.setShape(QCPScatterStyle::ssCircle);
  226. myScatter.setPen(Qt::blue);
  227. myScatter.setBrush(Qt::white);
  228. myScatter.setSize(5);
  229. customPlot->graph(0)->setScatterStyle(myScatter);
  230. \endcode
  231. Or you can use one of the various constructors that take different parameter combinations, making
  232. it easy to specify a scatter style in a single call, like so:
  233. \code
  234. customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, Qt::white, 5));
  235. \endcode
  236. \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable
  237. There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref
  238. QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref
  239. isPenDefined will return false. It leads to scatter points that inherit the pen from the
  240. plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line
  241. color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes
  242. it very convenient to set up typical scatter settings:
  243. \code
  244. customPlot->graph(0)->setScatterStyle(QCPScatterStyle::ssPlus);
  245. \endcode
  246. Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works
  247. because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly
  248. into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size)
  249. constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref
  250. ScatterShape, where actually a QCPScatterStyle is expected.
  251. \section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps
  252. QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points.
  253. For custom shapes, you can provide a QPainterPath with the desired shape to the \ref
  254. setCustomPath function or call the constructor that takes a painter path. The scatter shape will
  255. automatically be set to \ref ssCustom.
  256. For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the
  257. constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap.
  258. Note that \ref setSize does not influence the appearance of the pixmap.
  259. */
  260. /* start documentation of inline functions */
  261. /*! \fn bool QCPScatterStyle::isNone() const
  262. Returns whether the scatter shape is \ref ssNone.
  263. \see setShape
  264. */
  265. /*! \fn bool QCPScatterStyle::isPenDefined() const
  266. Returns whether a pen has been defined for this scatter style.
  267. The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those are
  268. \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen is
  269. left undefined, the scatter color will be inherited from the plottable that uses this scatter
  270. style.
  271. \see setPen
  272. */
  273. /* end documentation of inline functions */
  274. /*!
  275. Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined.
  276. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
  277. from the plottable that uses this scatter style.
  278. */
  279. QCPScatterStyle::QCPScatterStyle() :
  280. mSize(6),
  281. mShape(ssNone),
  282. mPen(Qt::NoPen),
  283. mBrush(Qt::NoBrush),
  284. mPenDefined(false)
  285. {
  286. }
  287. /*!
  288. Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or
  289. brush is defined.
  290. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
  291. from the plottable that uses this scatter style.
  292. */
  293. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) :
  294. mSize(size),
  295. mShape(shape),
  296. mPen(Qt::NoPen),
  297. mBrush(Qt::NoBrush),
  298. mPenDefined(false)
  299. {
  300. }
  301. /*!
  302. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
  303. and size to \a size. No brush is defined, i.e. the scatter point will not be filled.
  304. */
  305. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) :
  306. mSize(size),
  307. mShape(shape),
  308. mPen(QPen(color)),
  309. mBrush(Qt::NoBrush),
  310. mPenDefined(true)
  311. {
  312. }
  313. /*!
  314. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
  315. the brush color to \a fill (with a solid pattern), and size to \a size.
  316. */
  317. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) :
  318. mSize(size),
  319. mShape(shape),
  320. mPen(QPen(color)),
  321. mBrush(QBrush(fill)),
  322. mPenDefined(true)
  323. {
  324. }
  325. /*!
  326. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the
  327. brush to \a brush, and size to \a size.
  328. \warning In some cases it might be tempting to directly use a pen style like <tt>Qt::NoPen</tt> as \a pen
  329. and a color like <tt>Qt::blue</tt> as \a brush. Notice however, that the corresponding call\n
  330. <tt>QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)</tt>\n
  331. doesn't necessarily lead C++ to use this constructor in some cases, but might mistake
  332. <tt>Qt::NoPen</tt> for a QColor and use the
  333. \ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size)
  334. constructor instead (which will lead to an unexpected look of the scatter points). To prevent
  335. this, be more explicit with the parameter types. For example, use <tt>QBrush(Qt::blue)</tt>
  336. instead of just <tt>Qt::blue</tt>, to clearly point out to the compiler that this constructor is
  337. wanted.
  338. */
  339. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) :
  340. mSize(size),
  341. mShape(shape),
  342. mPen(pen),
  343. mBrush(brush),
  344. mPenDefined(pen.style() != Qt::NoPen)
  345. {
  346. }
  347. /*!
  348. Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape
  349. is set to \ref ssPixmap.
  350. */
  351. QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) :
  352. mSize(5),
  353. mShape(ssPixmap),
  354. mPen(Qt::NoPen),
  355. mBrush(Qt::NoBrush),
  356. mPixmap(pixmap),
  357. mPenDefined(false)
  358. {
  359. }
  360. /*!
  361. Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The
  362. scatter shape is set to \ref ssCustom.
  363. The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly
  364. different meaning than for built-in scatter points: The custom path will be drawn scaled by a
  365. factor of \a size/6.0. Since the default \a size is 6, the custom path will appear at a its
  366. natural size by default. To double the size of the path for example, set \a size to 12.
  367. */
  368. QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) :
  369. mSize(size),
  370. mShape(ssCustom),
  371. mPen(pen),
  372. mBrush(brush),
  373. mCustomPath(customPath),
  374. mPenDefined(false)
  375. {
  376. }
  377. /*!
  378. Sets the size (pixel diameter) of the drawn scatter points to \a size.
  379. \see setShape
  380. */
  381. void QCPScatterStyle::setSize(double size)
  382. {
  383. mSize = size;
  384. }
  385. /*!
  386. Sets the shape to \a shape.
  387. Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref
  388. ssPixmap and \ref ssCustom, respectively.
  389. \see setSize
  390. */
  391. void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape)
  392. {
  393. mShape = shape;
  394. }
  395. /*!
  396. Sets the pen that will be used to draw scatter points to \a pen.
  397. If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after
  398. a call to this function, even if \a pen is <tt>Qt::NoPen</tt>.
  399. \see setBrush
  400. */
  401. void QCPScatterStyle::setPen(const QPen &pen)
  402. {
  403. mPenDefined = true;
  404. mPen = pen;
  405. }
  406. /*!
  407. Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter
  408. shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does.
  409. \see setPen
  410. */
  411. void QCPScatterStyle::setBrush(const QBrush &brush)
  412. {
  413. mBrush = brush;
  414. }
  415. /*!
  416. Sets the pixmap that will be drawn as scatter point to \a pixmap.
  417. Note that \ref setSize does not influence the appearance of the pixmap.
  418. The scatter shape is automatically set to \ref ssPixmap.
  419. */
  420. void QCPScatterStyle::setPixmap(const QPixmap &pixmap)
  421. {
  422. setShape(ssPixmap);
  423. mPixmap = pixmap;
  424. }
  425. /*!
  426. Sets the custom shape that will be drawn as scatter point to \a customPath.
  427. The scatter shape is automatically set to \ref ssCustom.
  428. */
  429. void QCPScatterStyle::setCustomPath(const QPainterPath &customPath)
  430. {
  431. setShape(ssCustom);
  432. mCustomPath = customPath;
  433. }
  434. /*!
  435. Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an
  436. undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead.
  437. This function is used by plottables (or any class that wants to draw scatters) just before a
  438. number of scatters with this style shall be drawn with the \a painter.
  439. \see drawShape
  440. */
  441. void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const
  442. {
  443. painter->setPen(mPenDefined ? mPen : defaultPen);
  444. painter->setBrush(mBrush);
  445. }
  446. /*!
  447. Draws the scatter shape with \a painter at position \a pos.
  448. This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be
  449. called before scatter points are drawn with \ref drawShape.
  450. \see applyTo
  451. */
  452. void QCPScatterStyle::drawShape(QCPPainter *painter, QPointF pos) const
  453. {
  454. drawShape(painter, pos.x(), pos.y());
  455. }
  456. /*! \overload
  457. Draws the scatter shape with \a painter at position \a x and \a y.
  458. */
  459. void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const
  460. {
  461. double w = mSize/2.0;
  462. switch (mShape)
  463. {
  464. case ssNone: break;
  465. case ssDot:
  466. {
  467. painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y));
  468. break;
  469. }
  470. case ssCross:
  471. {
  472. painter->drawLine(QLineF(x-w, y-w, x+w, y+w));
  473. painter->drawLine(QLineF(x-w, y+w, x+w, y-w));
  474. break;
  475. }
  476. case ssPlus:
  477. {
  478. painter->drawLine(QLineF(x-w, y, x+w, y));
  479. painter->drawLine(QLineF( x, y+w, x, y-w));
  480. break;
  481. }
  482. case ssCircle:
  483. {
  484. painter->drawEllipse(QPointF(x , y), w, w);
  485. break;
  486. }
  487. case ssDisc:
  488. {
  489. QBrush b = painter->brush();
  490. painter->setBrush(painter->pen().color());
  491. painter->drawEllipse(QPointF(x , y), w, w);
  492. painter->setBrush(b);
  493. break;
  494. }
  495. case ssSquare:
  496. {
  497. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  498. break;
  499. }
  500. case ssDiamond:
  501. {
  502. painter->drawLine(QLineF(x-w, y, x, y-w));
  503. painter->drawLine(QLineF( x, y-w, x+w, y));
  504. painter->drawLine(QLineF(x+w, y, x, y+w));
  505. painter->drawLine(QLineF( x, y+w, x-w, y));
  506. break;
  507. }
  508. case ssStar:
  509. {
  510. painter->drawLine(QLineF(x-w, y, x+w, y));
  511. painter->drawLine(QLineF( x, y+w, x, y-w));
  512. painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707));
  513. painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707));
  514. break;
  515. }
  516. case ssTriangle:
  517. {
  518. painter->drawLine(QLineF(x-w, y+0.755*w, x+w, y+0.755*w));
  519. painter->drawLine(QLineF(x+w, y+0.755*w, x, y-0.977*w));
  520. painter->drawLine(QLineF( x, y-0.977*w, x-w, y+0.755*w));
  521. break;
  522. }
  523. case ssTriangleInverted:
  524. {
  525. painter->drawLine(QLineF(x-w, y-0.755*w, x+w, y-0.755*w));
  526. painter->drawLine(QLineF(x+w, y-0.755*w, x, y+0.977*w));
  527. painter->drawLine(QLineF( x, y+0.977*w, x-w, y-0.755*w));
  528. break;
  529. }
  530. case ssCrossSquare:
  531. {
  532. painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95));
  533. painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w));
  534. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  535. break;
  536. }
  537. case ssPlusSquare:
  538. {
  539. painter->drawLine(QLineF(x-w, y, x+w*0.95, y));
  540. painter->drawLine(QLineF( x, y+w, x, y-w));
  541. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  542. break;
  543. }
  544. case ssCrossCircle:
  545. {
  546. painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670));
  547. painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707));
  548. painter->drawEllipse(QPointF(x, y), w, w);
  549. break;
  550. }
  551. case ssPlusCircle:
  552. {
  553. painter->drawLine(QLineF(x-w, y, x+w, y));
  554. painter->drawLine(QLineF( x, y+w, x, y-w));
  555. painter->drawEllipse(QPointF(x, y), w, w);
  556. break;
  557. }
  558. case ssPeace:
  559. {
  560. painter->drawLine(QLineF(x, y-w, x, y+w));
  561. painter->drawLine(QLineF(x, y, x-w*0.707, y+w*0.707));
  562. painter->drawLine(QLineF(x, y, x+w*0.707, y+w*0.707));
  563. painter->drawEllipse(QPointF(x, y), w, w);
  564. break;
  565. }
  566. case ssPixmap:
  567. {
  568. painter->drawPixmap(x-mPixmap.width()*0.5, y-mPixmap.height()*0.5, mPixmap);
  569. break;
  570. }
  571. case ssCustom:
  572. {
  573. QTransform oldTransform = painter->transform();
  574. painter->translate(x, y);
  575. painter->scale(mSize/6.0, mSize/6.0);
  576. painter->drawPath(mCustomPath);
  577. painter->setTransform(oldTransform);
  578. break;
  579. }
  580. }
  581. }
  582. ////////////////////////////////////////////////////////////////////////////////////////////////////
  583. //////////////////// QCPLayer
  584. ////////////////////////////////////////////////////////////////////////////////////////////////////
  585. /*! \class QCPLayer
  586. \brief A layer that may contain objects, to control the rendering order
  587. The Layering system of QCustomPlot is the mechanism to control the rendering order of the
  588. elements inside the plot.
  589. It is based on the two classes QCPLayer and QCPLayerable. QCustomPlot holds an ordered list of
  590. one or more instances of QCPLayer (see QCustomPlot::addLayer, QCustomPlot::layer,
  591. QCustomPlot::moveLayer, etc.). When replotting, QCustomPlot goes through the list of layers
  592. bottom to top and successively draws the layerables of the layers.
  593. A QCPLayer contains an ordered list of QCPLayerable instances. QCPLayerable is an abstract base
  594. class from which almost all visible objects derive, like axes, grids, graphs, items, etc.
  595. Initially, QCustomPlot has five layers: "background", "grid", "main", "axes" and "legend" (in
  596. that order). The top two layers "axes" and "legend" contain the default axes and legend, so they
  597. will be drawn on top. In the middle, there is the "main" layer. It is initially empty and set as
  598. the current layer (see QCustomPlot::setCurrentLayer). This means, all new plottables, items etc.
  599. are created on this layer by default. Then comes the "grid" layer which contains the QCPGrid
  600. instances (which belong tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background
  601. shall be drawn behind everything else, thus the default QCPAxisRect instance is placed on the
  602. "background" layer. Of course, the layer affiliation of the individual objects can be changed as
  603. required (\ref QCPLayerable::setLayer).
  604. Controlling the ordering of objects is easy: Create a new layer in the position you want it to
  605. be, e.g. above "main", with QCustomPlot::addLayer. Then set the current layer with
  606. QCustomPlot::setCurrentLayer to that new layer and finally create the objects normally. They will
  607. be placed on the new layer automatically, due to the current layer setting. Alternatively you
  608. could have also ignored the current layer setting and just moved the objects with
  609. QCPLayerable::setLayer to the desired layer after creating them.
  610. It is also possible to move whole layers. For example, If you want the grid to be shown in front
  611. of all plottables/items on the "main" layer, just move it above "main" with
  612. QCustomPlot::moveLayer.
  613. The rendering order within one layer is simply by order of creation or insertion. The item
  614. created last (or added last to the layer), is drawn on top of all other objects on that layer.
  615. When a layer is deleted, the objects on it are not deleted with it, but fall on the layer below
  616. the deleted layer, see QCustomPlot::removeLayer.
  617. */
  618. /* start documentation of inline functions */
  619. /*! \fn QList<QCPLayerable*> QCPLayer::children() const
  620. Returns a list of all layerables on this layer. The order corresponds to the rendering order:
  621. layerables with higher indices are drawn above layerables with lower indices.
  622. */
  623. /*! \fn int QCPLayer::index() const
  624. Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be
  625. accessed via \ref QCustomPlot::layer.
  626. Layers with higher indices will be drawn above layers with lower indices.
  627. */
  628. /* end documentation of inline functions */
  629. /*!
  630. Creates a new QCPLayer instance.
  631. Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead.
  632. \warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot.
  633. This check is only performed by \ref QCustomPlot::addLayer.
  634. */
  635. QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) :
  636. QObject(parentPlot),
  637. mParentPlot(parentPlot),
  638. mName(layerName),
  639. mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function
  640. mVisible(true)
  641. {
  642. // Note: no need to make sure layerName is unique, because layer
  643. // management is done with QCustomPlot functions.
  644. }
  645. QCPLayer::~QCPLayer()
  646. {
  647. // If child layerables are still on this layer, detach them, so they don't try to reach back to this
  648. // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted
  649. // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to
  650. // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.)
  651. while (!mChildren.isEmpty())
  652. mChildren.last()->setLayer(0); // removes itself from mChildren via removeChild()
  653. if (mParentPlot->currentLayer() == this)
  654. 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.";
  655. }
  656. /*!
  657. Sets whether this layer is visible or not. If \a visible is set to false, all layerables on this
  658. layer will be invisible.
  659. This function doesn't change the visibility property of the layerables (\ref
  660. QCPLayerable::setVisible), but the \ref QCPLayerable::realVisibility of each layerable takes the
  661. visibility of the parent layer into account.
  662. */
  663. void QCPLayer::setVisible(bool visible)
  664. {
  665. mVisible = visible;
  666. }
  667. /*! \internal
  668. Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will
  669. be prepended to the list, i.e. be drawn beneath the other layerables already in the list.
  670. This function does not change the \a mLayer member of \a layerable to this layer. (Use
  671. QCPLayerable::setLayer to change the layer of an object, not this function.)
  672. \see removeChild
  673. */
  674. void QCPLayer::addChild(QCPLayerable *layerable, bool prepend)
  675. {
  676. if (!mChildren.contains(layerable))
  677. {
  678. if (prepend)
  679. mChildren.prepend(layerable);
  680. else
  681. mChildren.append(layerable);
  682. } else
  683. qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast<quintptr>(layerable);
  684. }
  685. /*! \internal
  686. Removes the \a layerable from the list of this layer.
  687. This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer
  688. to change the layer of an object, not this function.)
  689. \see addChild
  690. */
  691. void QCPLayer::removeChild(QCPLayerable *layerable)
  692. {
  693. if (!mChildren.removeOne(layerable))
  694. qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast<quintptr>(layerable);
  695. }
  696. ////////////////////////////////////////////////////////////////////////////////////////////////////
  697. //////////////////// QCPLayerable
  698. ////////////////////////////////////////////////////////////////////////////////////////////////////
  699. /*! \class QCPLayerable
  700. \brief Base class for all drawable objects
  701. This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid
  702. etc.
  703. Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking
  704. the layers accordingly.
  705. For details about the layering mechanism, see the QCPLayer documentation.
  706. */
  707. /* start documentation of inline functions */
  708. /*! \fn QCPLayerable *QCPLayerable::parentLayerable() const
  709. Returns the parent layerable of this layerable. The parent layerable is used to provide
  710. visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables
  711. only get drawn if their parent layerables are visible, too.
  712. Note that a parent layerable is not necessarily also the QObject parent for memory management.
  713. Further, a layerable doesn't always have a parent layerable, so this function may return 0.
  714. A parent layerable is set implicitly with when placed inside layout elements and doesn't need to be
  715. set manually by the user.
  716. */
  717. /* end documentation of inline functions */
  718. /* start documentation of pure virtual functions */
  719. /*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0
  720. \internal
  721. This function applies the default antialiasing setting to the specified \a painter, using the
  722. function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when
  723. \ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing
  724. setting may be specified individually, this function should set the antialiasing state of the
  725. most prominent entity. In this case however, the \ref draw function usually calls the specialized
  726. versions of this function before drawing each entity, effectively overriding the setting of the
  727. default antialiasing hint.
  728. <b>First example:</b> QCPGraph has multiple entities that have an antialiasing setting: The graph
  729. line, fills, scatters and error bars. Those can be configured via QCPGraph::setAntialiased,
  730. QCPGraph::setAntialiasedFill, QCPGraph::setAntialiasedScatters etc. Consequently, there isn't
  731. only the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's
  732. antialiasing), but specialized ones like QCPGraph::applyFillAntialiasingHint and
  733. QCPGraph::applyScattersAntialiasingHint. So before drawing one of those entities, QCPGraph::draw
  734. calls the respective specialized applyAntialiasingHint function.
  735. <b>Second example:</b> QCPItemLine consists only of a line so there is only one antialiasing
  736. setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by
  737. all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the
  738. respective layerable subclass.) Consequently it only has the normal
  739. QCPItemLine::applyDefaultAntialiasingHint. The \ref QCPItemLine::draw function doesn't need to
  740. care about setting any antialiasing states, because the default antialiasing hint is already set
  741. on the painter when the \ref draw function is called, and that's the state it wants to draw the
  742. line with.
  743. */
  744. /*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0
  745. \internal
  746. This function draws the layerable with the specified \a painter. It is only called by
  747. QCustomPlot, if the layerable is visible (\ref setVisible).
  748. Before this function is called, the painter's antialiasing state is set via \ref
  749. applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was
  750. set to \ref clipRect.
  751. */
  752. /* end documentation of pure virtual functions */
  753. /* start documentation of signals */
  754. /*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer);
  755. This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to
  756. a different layer.
  757. \see setLayer
  758. */
  759. /* end documentation of signals */
  760. /*!
  761. Creates a new QCPLayerable instance.
  762. Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the
  763. derived classes.
  764. If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a
  765. targetLayer is an empty string, it places itself on the current layer of the plot (see \ref
  766. QCustomPlot::setCurrentLayer).
  767. It is possible to provide 0 as \a plot. In that case, you should assign a parent plot at a later
  768. time with \ref initializeParentPlot.
  769. The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable parents
  770. are mainly used to control visibility in a hierarchy of layerables. This means a layerable is
  771. only drawn, if all its ancestor layerables are also visible. Note that \a parentLayerable does
  772. not become the QObject-parent (for memory management) of this layerable, \a plot does.
  773. */
  774. QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) :
  775. QObject(plot),
  776. mVisible(true),
  777. mParentPlot(plot),
  778. mParentLayerable(parentLayerable),
  779. mLayer(0),
  780. mAntialiased(true)
  781. {
  782. if (mParentPlot)
  783. {
  784. if (targetLayer.isEmpty())
  785. setLayer(mParentPlot->currentLayer());
  786. else if (!setLayer(targetLayer))
  787. qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed.";
  788. }
  789. }
  790. QCPLayerable::~QCPLayerable()
  791. {
  792. if (mLayer)
  793. {
  794. mLayer->removeChild(this);
  795. mLayer = 0;
  796. }
  797. }
  798. /*!
  799. Sets the visibility of this layerable object. If an object is not visible, it will not be drawn
  800. on the QCustomPlot surface, and user interaction with it (e.g. click and selection) is not
  801. possible.
  802. */
  803. void QCPLayerable::setVisible(bool on)
  804. {
  805. mVisible = on;
  806. }
  807. /*!
  808. Sets the \a layer of this layerable object. The object will be placed on top of the other objects
  809. already on \a layer.
  810. Returns true on success, i.e. if \a layer is a valid layer.
  811. */
  812. bool QCPLayerable::setLayer(QCPLayer *layer)
  813. {
  814. return moveToLayer(layer, false);
  815. }
  816. /*! \overload
  817. Sets the layer of this layerable object by name
  818. Returns true on success, i.e. if \a layerName is a valid layer name.
  819. */
  820. bool QCPLayerable::setLayer(const QString &layerName)
  821. {
  822. if (!mParentPlot)
  823. {
  824. qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
  825. return false;
  826. }
  827. if (QCPLayer *layer = mParentPlot->layer(layerName))
  828. {
  829. return setLayer(layer);
  830. } else
  831. {
  832. qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName;
  833. return false;
  834. }
  835. }
  836. /*!
  837. Sets whether this object will be drawn antialiased or not.
  838. Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and
  839. QCustomPlot::setNotAntialiasedElements.
  840. */
  841. void QCPLayerable::setAntialiased(bool enabled)
  842. {
  843. mAntialiased = enabled;
  844. }
  845. /*!
  846. Returns whether this layerable is visible, taking the visibility of the layerable parent and the
  847. visibility of the layer this layerable is on into account. This is the method that is consulted
  848. to decide whether a layerable shall be drawn or not.
  849. If this layerable has a direct layerable parent (usually set via hierarchies implemented in
  850. subclasses, like in the case of QCPLayoutElement), this function returns true only if this
  851. layerable has its visibility set to true and the parent layerable's \ref realVisibility returns
  852. true.
  853. If this layerable doesn't have a direct layerable parent, returns the state of this layerable's
  854. visibility.
  855. */
  856. bool QCPLayerable::realVisibility() const
  857. {
  858. return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility());
  859. }
  860. /*!
  861. This function is used to decide whether a click hits a layerable object or not.
  862. \a pos is a point in pixel coordinates on the QCustomPlot surface. This function returns the
  863. shortest pixel distance of this point to the object. If the object is either invisible or the
  864. distance couldn't be determined, -1.0 is returned. Further, if \a onlySelectable is true and the
  865. object is not selectable, -1.0 is returned, too.
  866. If the item is represented not by single lines but by an area like QCPItemRect or QCPItemText, a
  867. click inside the area returns a constant value greater zero (typically the selectionTolerance of
  868. the parent QCustomPlot multiplied by 0.99). If the click lies outside the area, this function
  869. returns -1.0.
  870. Providing a constant value for area objects allows selecting line objects even when they are
  871. obscured by such area objects, by clicking close to the lines (i.e. closer than
  872. 0.99*selectionTolerance).
  873. The actual setting of the selection state is not done by this function. This is handled by the
  874. parent QCustomPlot when the mouseReleaseEvent occurs, and the finally selected object is notified
  875. via the selectEvent/deselectEvent methods.
  876. \a details is an optional output parameter. Every layerable subclass may place any information
  877. in \a details. This information will be passed to \ref selectEvent when the parent QCustomPlot
  878. decides on the basis of this selectTest call, that the object was successfully selected. The
  879. subsequent call to \ref selectEvent will carry the \a details. This is useful for multi-part
  880. objects (like QCPAxis). This way, a possibly complex calculation to decide which part was clicked
  881. is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be
  882. placed in \a details. So in the subsequent \ref selectEvent, the decision which part was
  883. selected doesn't have to be done a second time for a single selection operation.
  884. You may pass 0 as \a details to indicate that you are not interested in those selection details.
  885. \see selectEvent, deselectEvent, QCustomPlot::setInteractions
  886. */
  887. double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  888. {
  889. Q_UNUSED(pos)
  890. Q_UNUSED(onlySelectable)
  891. Q_UNUSED(details)
  892. return -1.0;
  893. }
  894. /*! \internal
  895. Sets the parent plot of this layerable. Use this function once to set the parent plot if you have
  896. passed 0 in the constructor. It can not be used to move a layerable from one QCustomPlot to
  897. another one.
  898. Note that, unlike when passing a non-null parent plot in the constructor, this function does not
  899. make \a parentPlot the QObject-parent of this layerable. If you want this, call
  900. QObject::setParent(\a parentPlot) in addition to this function.
  901. Further, you will probably want to set a layer (\ref setLayer) after calling this function, to
  902. make the layerable appear on the QCustomPlot.
  903. The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized
  904. so they can react accordingly (e.g. also initialize the parent plot of child layerables, like
  905. QCPLayout does).
  906. */
  907. void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot)
  908. {
  909. if (mParentPlot)
  910. {
  911. qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized";
  912. return;
  913. }
  914. if (!parentPlot)
  915. qDebug() << Q_FUNC_INFO << "called with parentPlot zero";
  916. mParentPlot = parentPlot;
  917. parentPlotInitialized(mParentPlot);
  918. }
  919. /*! \internal
  920. Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not
  921. become the QObject-parent (for memory management) of this layerable.
  922. The parent layerable has influence on the return value of the \ref realVisibility method. Only
  923. layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be
  924. drawn.
  925. \see realVisibility
  926. */
  927. void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable)
  928. {
  929. mParentLayerable = parentLayerable;
  930. }
  931. /*! \internal
  932. Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to
  933. the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is
  934. false, the object will be appended.
  935. Returns true on success, i.e. if \a layer is a valid layer.
  936. */
  937. bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend)
  938. {
  939. if (layer && !mParentPlot)
  940. {
  941. qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
  942. return false;
  943. }
  944. if (layer && layer->parentPlot() != mParentPlot)
  945. {
  946. qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable";
  947. return false;
  948. }
  949. QCPLayer *oldLayer = mLayer;
  950. if (mLayer)
  951. mLayer->removeChild(this);
  952. mLayer = layer;
  953. if (mLayer)
  954. mLayer->addChild(this, prepend);
  955. if (mLayer != oldLayer)
  956. emit layerChanged(mLayer);
  957. return true;
  958. }
  959. /*! \internal
  960. Sets the QCPainter::setAntialiasing state on the provided \a painter, depending on the \a
  961. localAntialiased value as well as the overrides \ref QCustomPlot::setAntialiasedElements and \ref
  962. QCustomPlot::setNotAntialiasedElements. Which override enum this function takes into account is
  963. controlled via \a overrideElement.
  964. */
  965. void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const
  966. {
  967. if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement))
  968. painter->setAntialiasing(false);
  969. else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement))
  970. painter->setAntialiasing(true);
  971. else
  972. painter->setAntialiasing(localAntialiased);
  973. }
  974. /*! \internal
  975. This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting
  976. of a parent plot. This is the case when 0 was passed as parent plot in the constructor, and the
  977. parent plot is set at a later time.
  978. For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any
  979. QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level
  980. element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To
  981. propagate the parent plot to all the children of the hierarchy, the top level element then uses
  982. this function to pass the parent plot on to its child elements.
  983. The default implementation does nothing.
  984. \see initializeParentPlot
  985. */
  986. void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot)
  987. {
  988. Q_UNUSED(parentPlot)
  989. }
  990. /*! \internal
  991. Returns the selection category this layerable shall belong to. The selection category is used in
  992. conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and
  993. which aren't.
  994. Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref
  995. QCP::iSelectOther. This is what the default implementation returns.
  996. \see QCustomPlot::setInteractions
  997. */
  998. QCP::Interaction QCPLayerable::selectionCategory() const
  999. {
  1000. return QCP::iSelectOther;
  1001. }
  1002. /*! \internal
  1003. Returns the clipping rectangle of this layerable object. By default, this is the viewport of the
  1004. parent QCustomPlot. Specific subclasses may reimplement this function to provide different
  1005. clipping rects.
  1006. The returned clipping rect is set on the painter before the draw function of the respective
  1007. object is called.
  1008. */
  1009. QRect QCPLayerable::clipRect() const
  1010. {
  1011. if (mParentPlot)
  1012. return mParentPlot->viewport();
  1013. else
  1014. return QRect();
  1015. }
  1016. /*! \internal
  1017. This event is called when the layerable shall be selected, as a consequence of a click by the
  1018. user. Subclasses should react to it by setting their selection state appropriately. The default
  1019. implementation does nothing.
  1020. \a event is the mouse event that caused the selection. \a additive indicates, whether the user
  1021. was holding the multi-select-modifier while performing the selection (see \ref
  1022. QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled
  1023. (i.e. become selected when unselected and unselected when selected).
  1024. Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e.
  1025. returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot).
  1026. The \a details data you output from \ref selectTest is fed back via \a details here. You may
  1027. use it to transport any kind of information from the selectTest to the possibly subsequent
  1028. selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable
  1029. that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need
  1030. to do the calculation again to find out which part was actually clicked.
  1031. \a selectionStateChanged is an output parameter. If the pointer is non-null, this function must
  1032. set the value either to true or false, depending on whether the selection state of this layerable
  1033. was actually changed. For layerables that only are selectable as a whole and not in parts, this
  1034. is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the
  1035. selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the
  1036. layerable was previously unselected and now is switched to the selected state.
  1037. \see selectTest, deselectEvent
  1038. */
  1039. void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  1040. {
  1041. Q_UNUSED(event)
  1042. Q_UNUSED(additive)
  1043. Q_UNUSED(details)
  1044. Q_UNUSED(selectionStateChanged)
  1045. }
  1046. /*! \internal
  1047. This event is called when the layerable shall be deselected, either as consequence of a user
  1048. interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by
  1049. unsetting their selection appropriately.
  1050. just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must
  1051. return true or false when the selection state of this layerable has changed or not changed,
  1052. respectively.
  1053. \see selectTest, selectEvent
  1054. */
  1055. void QCPLayerable::deselectEvent(bool *selectionStateChanged)
  1056. {
  1057. Q_UNUSED(selectionStateChanged)
  1058. }
  1059. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1060. //////////////////// QCPRange
  1061. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1062. /*! \class QCPRange
  1063. \brief Represents the range an axis is encompassing.
  1064. contains a \a lower and \a upper double value and provides convenience input, output and
  1065. modification functions.
  1066. \see QCPAxis::setRange
  1067. */
  1068. /*!
  1069. Minimum range size (\a upper - \a lower) the range changing functions will accept. Smaller
  1070. intervals would cause errors due to the 11-bit exponent of double precision numbers,
  1071. corresponding to a minimum magnitude of roughly 1e-308.
  1072. \see validRange, maxRange
  1073. */
  1074. const double QCPRange::minRange = 1e-280;
  1075. /*!
  1076. Maximum values (negative and positive) the range will accept in range-changing functions.
  1077. Larger absolute values would cause errors due to the 11-bit exponent of double precision numbers,
  1078. corresponding to a maximum magnitude of roughly 1e308.
  1079. Since the number of planck-volumes in the entire visible universe is only ~1e183, this should
  1080. be enough.
  1081. \see validRange, minRange
  1082. */
  1083. const double QCPRange::maxRange = 1e250;
  1084. /*!
  1085. Constructs a range with \a lower and \a upper set to zero.
  1086. */
  1087. QCPRange::QCPRange() :
  1088. lower(0),
  1089. upper(0)
  1090. {
  1091. }
  1092. /*! \overload
  1093. Constructs a range with the specified \a lower and \a upper values.
  1094. */
  1095. QCPRange::QCPRange(double lower, double upper) :
  1096. lower(lower),
  1097. upper(upper)
  1098. {
  1099. normalize();
  1100. }
  1101. /*!
  1102. Returns the size of the range, i.e. \a upper-\a lower
  1103. */
  1104. double QCPRange::size() const
  1105. {
  1106. return upper-lower;
  1107. }
  1108. /*!
  1109. Returns the center of the range, i.e. (\a upper+\a lower)*0.5
  1110. */
  1111. double QCPRange::center() const
  1112. {
  1113. return (upper+lower)*0.5;
  1114. }
  1115. /*!
  1116. Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values
  1117. are swapped.
  1118. */
  1119. void QCPRange::normalize()
  1120. {
  1121. if (lower > upper)
  1122. qSwap(lower, upper);
  1123. }
  1124. /*!
  1125. Expands this range such that \a otherRange is contained in the new range. It is assumed that both
  1126. this range and \a otherRange are normalized (see \ref normalize).
  1127. If \a otherRange is already inside the current range, this function does nothing.
  1128. \see expanded
  1129. */
  1130. void QCPRange::expand(const QCPRange &otherRange)
  1131. {
  1132. if (lower > otherRange.lower)
  1133. lower = otherRange.lower;
  1134. if (upper < otherRange.upper)
  1135. upper = otherRange.upper;
  1136. }
  1137. /*!
  1138. Returns an expanded range that contains this and \a otherRange. It is assumed that both this
  1139. range and \a otherRange are normalized (see \ref normalize).
  1140. \see expand
  1141. */
  1142. QCPRange QCPRange::expanded(const QCPRange &otherRange) const
  1143. {
  1144. QCPRange result = *this;
  1145. result.expand(otherRange);
  1146. return result;
  1147. }
  1148. /*!
  1149. Returns a sanitized version of the range. Sanitized means for logarithmic scales, that
  1150. the range won't span the positive and negative sign domain, i.e. contain zero. Further
  1151. \a lower will always be numerically smaller (or equal) to \a upper.
  1152. If the original range does span positive and negative sign domains or contains zero,
  1153. the returned range will try to approximate the original range as good as possible.
  1154. If the positive interval of the original range is wider than the negative interval, the
  1155. returned range will only contain the positive interval, with lower bound set to \a rangeFac or
  1156. \a rangeFac *\a upper, whichever is closer to zero. Same procedure is used if the negative interval
  1157. is wider than the positive interval, this time by changing the \a upper bound.
  1158. */
  1159. QCPRange QCPRange::sanitizedForLogScale() const
  1160. {
  1161. double rangeFac = 1e-3;
  1162. QCPRange sanitizedRange(lower, upper);
  1163. sanitizedRange.normalize();
  1164. // can't have range spanning negative and positive values in log plot, so change range to fix it
  1165. //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1))
  1166. if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0)
  1167. {
  1168. // case lower is 0
  1169. if (rangeFac < sanitizedRange.upper*rangeFac)
  1170. sanitizedRange.lower = rangeFac;
  1171. else
  1172. sanitizedRange.lower = sanitizedRange.upper*rangeFac;
  1173. } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1))
  1174. else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0)
  1175. {
  1176. // case upper is 0
  1177. if (-rangeFac > sanitizedRange.lower*rangeFac)
  1178. sanitizedRange.upper = -rangeFac;
  1179. else
  1180. sanitizedRange.upper = sanitizedRange.lower*rangeFac;
  1181. } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0)
  1182. {
  1183. // find out whether negative or positive interval is wider to decide which sign domain will be chosen
  1184. if (-sanitizedRange.lower > sanitizedRange.upper)
  1185. {
  1186. // negative is wider, do same as in case upper is 0
  1187. if (-rangeFac > sanitizedRange.lower*rangeFac)
  1188. sanitizedRange.upper = -rangeFac;
  1189. else
  1190. sanitizedRange.upper = sanitizedRange.lower*rangeFac;
  1191. } else
  1192. {
  1193. // positive is wider, do same as in case lower is 0
  1194. if (rangeFac < sanitizedRange.upper*rangeFac)
  1195. sanitizedRange.lower = rangeFac;
  1196. else
  1197. sanitizedRange.lower = sanitizedRange.upper*rangeFac;
  1198. }
  1199. }
  1200. // due to normalization, case lower>0 && upper<0 should never occur, because that implies upper<lower
  1201. return sanitizedRange;
  1202. }
  1203. /*!
  1204. Returns a sanitized version of the range. Sanitized means for linear scales, that
  1205. \a lower will always be numerically smaller (or equal) to \a upper.
  1206. */
  1207. QCPRange QCPRange::sanitizedForLinScale() const
  1208. {
  1209. QCPRange sanitizedRange(lower, upper);
  1210. sanitizedRange.normalize();
  1211. return sanitizedRange;
  1212. }
  1213. /*!
  1214. Returns true when \a value lies within or exactly on the borders of the range.
  1215. */
  1216. bool QCPRange::contains(double value) const
  1217. {
  1218. return value >= lower && value <= upper;
  1219. }
  1220. /*!
  1221. Checks, whether the specified range is within valid bounds, which are defined
  1222. as QCPRange::maxRange and QCPRange::minRange.
  1223. A valid range means:
  1224. \li range bounds within -maxRange and maxRange
  1225. \li range size above minRange
  1226. \li range size below maxRange
  1227. */
  1228. bool QCPRange::validRange(double lower, double upper)
  1229. {
  1230. /*
  1231. return (lower > -maxRange &&
  1232. upper < maxRange &&
  1233. qAbs(lower-upper) > minRange &&
  1234. (lower < -minRange || lower > minRange) &&
  1235. (upper < -minRange || upper > minRange));
  1236. */
  1237. return (lower > -maxRange &&
  1238. upper < maxRange &&
  1239. qAbs(lower-upper) > minRange &&
  1240. qAbs(lower-upper) < maxRange);
  1241. }
  1242. /*!
  1243. \overload
  1244. Checks, whether the specified range is within valid bounds, which are defined
  1245. as QCPRange::maxRange and QCPRange::minRange.
  1246. A valid range means:
  1247. \li range bounds within -maxRange and maxRange
  1248. \li range size above minRange
  1249. \li range size below maxRange
  1250. */
  1251. bool QCPRange::validRange(const QCPRange &range)
  1252. {
  1253. /*
  1254. return (range.lower > -maxRange &&
  1255. range.upper < maxRange &&
  1256. qAbs(range.lower-range.upper) > minRange &&
  1257. qAbs(range.lower-range.upper) < maxRange &&
  1258. (range.lower < -minRange || range.lower > minRange) &&
  1259. (range.upper < -minRange || range.upper > minRange));
  1260. */
  1261. return (range.lower > -maxRange &&
  1262. range.upper < maxRange &&
  1263. qAbs(range.lower-range.upper) > minRange &&
  1264. qAbs(range.lower-range.upper) < maxRange);
  1265. }
  1266. /*! \page thelayoutsystem The Layout System
  1267. The layout system is responsible for positioning and scaling layout elements such as axis rects,
  1268. legends and plot titles in a QCustomPlot.
  1269. \section layoutsystem-classesandmechanisms Classes and mechanisms
  1270. The layout system is based on the abstract base class \ref QCPLayoutElement. All objects that
  1271. take part in the layout system derive from this class, either directly or indirectly.
  1272. Since QCPLayoutElement itself derives from \ref QCPLayerable, a layout element may draw its own
  1273. content. However, it is perfectly possible for a layout element to only serve as a structuring
  1274. and/or positioning element, not drawing anything on its own.
  1275. \subsection layoutsystem-rects Rects of a layout element
  1276. A layout element is a rectangular object described by two rects: the inner rect (\ref
  1277. QCPLayoutElement::rect) and the outer rect (\ref QCPLayoutElement::setOuterRect). The inner rect
  1278. is calculated automatically by applying the margin (\ref QCPLayoutElement::setMargins) inward
  1279. from the outer rect. The inner rect is meant for main content while the margin area may either be
  1280. left blank or serve for displaying peripheral graphics. For example, \ref QCPAxisRect positions
  1281. the four main axes at the sides of the inner rect, so graphs end up inside it and the axis labels
  1282. and tick labels are in the margin area.
  1283. \subsection layoutsystem-margins Margins
  1284. Each layout element may provide a mechanism to automatically determine its margins. Internally,
  1285. this is realized with the \ref QCPLayoutElement::calculateAutoMargin function which takes a \ref
  1286. QCP::MarginSide and returns an integer value which represents the ideal margin for the specified
  1287. side. The automatic margin will be used on the sides specified in \ref
  1288. QCPLayoutElement::setAutoMargins. By default, it is set to \ref QCP::msAll meaning automatic
  1289. margin calculation is enabled for all four sides. In this case, a minimum margin may be set with
  1290. \ref QCPLayoutElement::setMinimumMargins, to prevent the automatic margin mechanism from setting
  1291. margins smaller than desired for a specific situation. If automatic margin calculation is unset
  1292. for a specific side, the margin of that side can be controlled directy via \ref
  1293. QCPLayoutElement::setMargins.
  1294. If multiple layout ements are arranged next to or beneath each other, it may be desirable to
  1295. align their inner rects on certain sides. Since they all might have different automatic margins,
  1296. this usually isn't the case. The class \ref QCPMarginGroup and \ref
  1297. QCPLayoutElement::setMarginGroup fix this by allowing to synchronize multiple margins. See the
  1298. documentation there for details.
  1299. \subsection layoutsystem-layout Layouts
  1300. As mentioned, a QCPLayoutElement may have an arbitrary number of child layout elements and in
  1301. princple can have the only purpose to manage/arrange those child elements. This is what the
  1302. subclass \ref QCPLayout specializes on. It is a QCPLayoutElement itself but has no visual
  1303. representation. It defines an interface to add, remove and manage child layout elements.
  1304. QCPLayout isn't a usable layout though, it's an abstract base class that concrete layouts derive
  1305. from, like \ref QCPLayoutGrid which arranges its child elements in a grid and \ref QCPLayoutInset
  1306. which allows placing child elements freely inside its rect.
  1307. Since a QCPLayout is a layout element itself, it may be placed inside other layouts. This way,
  1308. complex hierarchies may be created, offering very flexible arrangements.
  1309. \image html LayoutsystemSketch.png
  1310. Above is a sketch of the default \ref QCPLayoutGrid accessible via \ref QCustomPlot::plotLayout.
  1311. It shows how two child layout elements are placed inside the grid layout next to each other in
  1312. cells (0, 0) and (0, 1).
  1313. \subsection layoutsystem-plotlayout The top level plot layout
  1314. Every QCustomPlot has one top level layout of type \ref QCPLayoutGrid. It is accessible via \ref
  1315. QCustomPlot::plotLayout and contains (directly or indirectly via other sub-layouts) all layout
  1316. elements in the QCustomPlot. By default, this top level grid layout contains a single cell which
  1317. holds the main axis rect.
  1318. \subsection layoutsystem-examples Examples
  1319. <b>Adding a plot title</b> is a typical and simple case to demonstrate basic workings of the layout system.
  1320. \code
  1321. // first we create and prepare a plot title layout element:
  1322. QCPPlotTitle *title = new QCPPlotTitle(customPlot);
  1323. title->setText("Plot Title Example");
  1324. title->setFont(QFont("sans", 12, QFont::Bold));
  1325. // then we add it to the main plot layout:
  1326. customPlot->plotLayout()->insertRow(0); // insert an empty row above the axis rect
  1327. customPlot->plotLayout()->addElement(0, 0, title); // place the title in the empty cell we've just created
  1328. \endcode
  1329. \image html layoutsystem-addingplottitle.png
  1330. <b>Arranging multiple axis rects</b> actually is the central purpose of the layout system.
  1331. \code
  1332. customPlot->plotLayout()->clear(); // let's start from scratch and remove the default axis rect
  1333. // add the first axis rect in second row (row index 1):
  1334. QCPAxisRect *topAxisRect = new QCPAxisRect(customPlot);
  1335. customPlot->plotLayout()->addElement(1, 0, topAxisRect);
  1336. // create a sub layout that we'll place in first row:
  1337. QCPLayoutGrid *subLayout = new QCPLayoutGrid;
  1338. customPlot->plotLayout()->addElement(0, 0, subLayout);
  1339. // add two axis rects in the sub layout next to each other:
  1340. QCPAxisRect *leftAxisRect = new QCPAxisRect(customPlot);
  1341. QCPAxisRect *rightAxisRect = new QCPAxisRect(customPlot);
  1342. subLayout->addElement(0, 0, leftAxisRect);
  1343. subLayout->addElement(0, 1, rightAxisRect);
  1344. subLayout->setColumnStretchFactor(0, 3); // left axis rect shall have 60% of width
  1345. subLayout->setColumnStretchFactor(1, 2); // right one only 40% (3:2 = 60:40)
  1346. // since we've created the axis rects and axes from scratch, we need to place them on
  1347. // according layers, if we don't want the grid to be drawn above the axes etc.
  1348. // place the axis on "axes" layer and grids on the "grid" layer, which is below "axes":
  1349. QList<QCPAxis*> allAxes;
  1350. allAxes << topAxisRect->axes() << leftAxisRect->axes() << rightAxisRect->axes();
  1351. foreach (QCPAxis *axis, allAxes)
  1352. {
  1353. axis->setLayer("axes");
  1354. axis->grid()->setLayer("grid");
  1355. }
  1356. \endcode
  1357. \image html layoutsystem-multipleaxisrects.png
  1358. */
  1359. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1360. //////////////////// QCPMarginGroup
  1361. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1362. /*! \class QCPMarginGroup
  1363. \brief A margin group allows synchronization of margin sides if working with multiple layout elements.
  1364. QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that
  1365. they will all have the same size, based on the largest required margin in the group.
  1366. \n
  1367. \image html QCPMarginGroup.png "Demonstration of QCPMarginGroup"
  1368. \n
  1369. In certain situations it is desirable that margins at specific sides are synchronized across
  1370. layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will
  1371. provide a cleaner look to the user if the left and right margins of the two axis rects are of the
  1372. same size. The left axis of the top axis rect will then be at the same horizontal position as the
  1373. left axis of the lower axis rect, making them appear aligned. The same applies for the right
  1374. axes. This is what QCPMarginGroup makes possible.
  1375. To add/remove a specific side of a layout element to/from a margin group, use the \ref
  1376. QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call
  1377. \ref clear, or just delete the margin group.
  1378. \section QCPMarginGroup-example Example
  1379. First create a margin group:
  1380. \code
  1381. QCPMarginGroup *group = new QCPMarginGroup(customPlot);
  1382. \endcode
  1383. Then set this group on the layout element sides:
  1384. \code
  1385. customPlot->axisRect(0)->setMarginGroup(QCP::msLeft|QCP::msRight, group);
  1386. customPlot->axisRect(1)->setMarginGroup(QCP::msLeft|QCP::msRight, group);
  1387. \endcode
  1388. Here, we've used the first two axis rects of the plot and synchronized their left margins with
  1389. each other and their right margins with each other.
  1390. */
  1391. /* start documentation of inline functions */
  1392. /*! \fn QList<QCPLayoutElement*> QCPMarginGroup::elements(QCP::MarginSide side) const
  1393. Returns a list of all layout elements that have their margin \a side associated with this margin
  1394. group.
  1395. */
  1396. /* end documentation of inline functions */
  1397. /*!
  1398. Creates a new QCPMarginGroup instance in \a parentPlot.
  1399. */
  1400. QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) :
  1401. QObject(parentPlot),
  1402. mParentPlot(parentPlot)
  1403. {
  1404. mChildren.insert(QCP::msLeft, QList<QCPLayoutElement*>());
  1405. mChildren.insert(QCP::msRight, QList<QCPLayoutElement*>());
  1406. mChildren.insert(QCP::msTop, QList<QCPLayoutElement*>());
  1407. mChildren.insert(QCP::msBottom, QList<QCPLayoutElement*>());
  1408. }
  1409. QCPMarginGroup::~QCPMarginGroup()
  1410. {
  1411. clear();
  1412. }
  1413. /*!
  1414. Returns whether this margin group is empty. If this function returns true, no layout elements use
  1415. this margin group to synchronize margin sides.
  1416. */
  1417. bool QCPMarginGroup::isEmpty() const
  1418. {
  1419. QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
  1420. while (it.hasNext())
  1421. {
  1422. it.next();
  1423. if (!it.value().isEmpty())
  1424. return false;
  1425. }
  1426. return true;
  1427. }
  1428. /*!
  1429. Clears this margin group. The synchronization of the margin sides that use this margin group is
  1430. lifted and they will use their individual margin sizes again.
  1431. */
  1432. void QCPMarginGroup::clear()
  1433. {
  1434. // make all children remove themselves from this margin group:
  1435. QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
  1436. while (it.hasNext())
  1437. {
  1438. it.next();
  1439. const QList<QCPLayoutElement*> elements = it.value();
  1440. for (int i=elements.size()-1; i>=0; --i)
  1441. elements.at(i)->setMarginGroup(it.key(), 0); // removes itself from mChildren via removeChild
  1442. }
  1443. }
  1444. /*! \internal
  1445. Returns the synchronized common margin for \a side. This is the margin value that will be used by
  1446. the layout element on the respective side, if it is part of this margin group.
  1447. The common margin is calculated by requesting the automatic margin (\ref
  1448. QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin
  1449. group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into
  1450. account, too.)
  1451. */
  1452. int QCPMarginGroup::commonMargin(QCP::MarginSide side) const
  1453. {
  1454. // query all automatic margins of the layout elements in this margin group side and find maximum:
  1455. int result = 0;
  1456. const QList<QCPLayoutElement*> elements = mChildren.value(side);
  1457. for (int i=0; i<elements.size(); ++i)
  1458. {
  1459. if (!elements.at(i)->autoMargins().testFlag(side))
  1460. continue;
  1461. int m = qMax(elements.at(i)->calculateAutoMargin(side), QCP::getMarginValue(elements.at(i)->minimumMargins(), side));
  1462. if (m > result)
  1463. result = m;
  1464. }
  1465. return result;
  1466. }
  1467. /*! \internal
  1468. Adds \a element to the internal list of child elements, for the margin \a side.
  1469. This function does not modify the margin group property of \a element.
  1470. */
  1471. void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element)
  1472. {
  1473. if (!mChildren[side].contains(element))
  1474. mChildren[side].append(element);
  1475. else
  1476. qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast<quintptr>(element);
  1477. }
  1478. /*! \internal
  1479. Removes \a element from the internal list of child elements, for the margin \a side.
  1480. This function does not modify the margin group property of \a element.
  1481. */
  1482. void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element)
  1483. {
  1484. if (!mChildren[side].removeOne(element))
  1485. qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast<quintptr>(element);
  1486. }
  1487. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1488. //////////////////// QCPLayoutElement
  1489. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1490. /*! \class QCPLayoutElement
  1491. \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system".
  1492. This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses.
  1493. A Layout element is a rectangular object which can be placed in layouts. It has an outer rect
  1494. (QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference
  1495. between outer and inner rect is called its margin. The margin can either be set to automatic or
  1496. manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be
  1497. set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic,
  1498. the layout element subclass will control the value itself (via \ref calculateAutoMargin).
  1499. Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level
  1500. layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref
  1501. QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested.
  1502. Thus in QCustomPlot one can divide layout elements into two categories: The ones that are
  1503. invisible by themselves, because they don't draw anything. Their only purpose is to manage the
  1504. position and size of other layout elements. This category of layout elements usually use
  1505. QCPLayout as base class. Then there is the category of layout elements which actually draw
  1506. something. For example, QCPAxisRect, QCPLegend and QCPPlotTitle are of this category. This does
  1507. not necessarily mean that the latter category can't have child layout elements. QCPLegend for
  1508. instance, actually derives from QCPLayoutGrid and the individual legend items are child layout
  1509. elements in the grid layout.
  1510. */
  1511. /* start documentation of inline functions */
  1512. /*! \fn QCPLayout *QCPLayoutElement::layout() const
  1513. Returns the parent layout of this layout element.
  1514. */
  1515. /*! \fn QRect QCPLayoutElement::rect() const
  1516. Returns the inner rect of this layout element. The inner rect is the outer rect (\ref
  1517. setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins).
  1518. In some cases, the area between outer and inner rect is left blank. In other cases the margin
  1519. area is used to display peripheral graphics while the main content is in the inner rect. This is
  1520. where automatic margin calculation becomes interesting because it allows the layout element to
  1521. adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect
  1522. draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if
  1523. \ref setAutoMargins is enabled) according to the space required by the labels of the axes.
  1524. */
  1525. /*! \fn virtual void QCPLayoutElement::mousePressEvent(QMouseEvent *event)
  1526. This event is called, if the mouse was pressed while being inside the outer rect of this layout
  1527. element.
  1528. */
  1529. /*! \fn virtual void QCPLayoutElement::mouseMoveEvent(QMouseEvent *event)
  1530. This event is called, if the mouse is moved inside the outer rect of this layout element.
  1531. */
  1532. /*! \fn virtual void QCPLayoutElement::mouseReleaseEvent(QMouseEvent *event)
  1533. This event is called, if the mouse was previously pressed inside the outer rect of this layout
  1534. element and is now released.
  1535. */
  1536. /*! \fn virtual void QCPLayoutElement::mouseDoubleClickEvent(QMouseEvent *event)
  1537. This event is called, if the mouse is double-clicked inside the outer rect of this layout
  1538. element.
  1539. */
  1540. /*! \fn virtual void QCPLayoutElement::wheelEvent(QWheelEvent *event)
  1541. This event is called, if the mouse wheel is scrolled while the cursor is inside the rect of this
  1542. layout element.
  1543. */
  1544. /* end documentation of inline functions */
  1545. /*!
  1546. Creates an instance of QCPLayoutElement and sets default values.
  1547. */
  1548. QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) :
  1549. QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout)
  1550. mParentLayout(0),
  1551. mMinimumSize(),
  1552. mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX),
  1553. mRect(0, 0, 0, 0),
  1554. mOuterRect(0, 0, 0, 0),
  1555. mMargins(0, 0, 0, 0),
  1556. mMinimumMargins(0, 0, 0, 0),
  1557. mAutoMargins(QCP::msAll)
  1558. {
  1559. }
  1560. QCPLayoutElement::~QCPLayoutElement()
  1561. {
  1562. setMarginGroup(QCP::msAll, 0); // unregister at margin groups, if there are any
  1563. // unregister at layout:
  1564. 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
  1565. mParentLayout->take(this);
  1566. }
  1567. /*!
  1568. Sets the outer rect of this layout element. If the layout element is inside a layout, the layout
  1569. sets the position and size of this layout element using this function.
  1570. Calling this function externally has no effect, since the layout will overwrite any changes to
  1571. the outer rect upon the next replot.
  1572. The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect.
  1573. \see rect
  1574. */
  1575. void QCPLayoutElement::setOuterRect(const QRect &rect)
  1576. {
  1577. if (mOuterRect != rect)
  1578. {
  1579. mOuterRect = rect;
  1580. mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
  1581. }
  1582. }
  1583. /*!
  1584. Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all
  1585. sides, this function is used to manually set the margin on those sides. Sides that are still set
  1586. to be handled automatically are ignored and may have any value in \a margins.
  1587. The margin is the distance between the outer rect (controlled by the parent layout via \ref
  1588. setOuterRect) and the inner \ref rect (which usually contains the main content of this layout
  1589. element).
  1590. \see setAutoMargins
  1591. */
  1592. void QCPLayoutElement::setMargins(const QMargins &margins)
  1593. {
  1594. if (mMargins != margins)
  1595. {
  1596. mMargins = margins;
  1597. mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
  1598. }
  1599. }
  1600. /*!
  1601. If \ref setAutoMargins is enabled on some or all margins, this function is used to provide
  1602. minimum values for those margins.
  1603. The minimum values are not enforced on margin sides that were set to be under manual control via
  1604. \ref setAutoMargins.
  1605. \see setAutoMargins
  1606. */
  1607. void QCPLayoutElement::setMinimumMargins(const QMargins &margins)
  1608. {
  1609. if (mMinimumMargins != margins)
  1610. {
  1611. mMinimumMargins = margins;
  1612. }
  1613. }
  1614. /*!
  1615. Sets on which sides the margin shall be calculated automatically. If a side is calculated
  1616. automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is
  1617. set to be controlled manually, the value may be specified with \ref setMargins.
  1618. Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref
  1619. setMarginGroup), to synchronize (align) it with other layout elements in the plot.
  1620. \see setMinimumMargins, setMargins
  1621. */
  1622. void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides)
  1623. {
  1624. mAutoMargins = sides;
  1625. }
  1626. /*!
  1627. Sets the minimum size for the inner \ref rect of this layout element. A parent layout tries to
  1628. respect the \a size here by changing row/column sizes in the layout accordingly.
  1629. If the parent layout size is not sufficient to satisfy all minimum size constraints of its child
  1630. layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot
  1631. propagates the layout's size constraints to the outside by setting its own minimum QWidget size
  1632. accordingly, so violations of \a size should be exceptions.
  1633. */
  1634. void QCPLayoutElement::setMinimumSize(const QSize &size)
  1635. {
  1636. if (mMinimumSize != size)
  1637. {
  1638. mMinimumSize = size;
  1639. if (mParentLayout)
  1640. mParentLayout->sizeConstraintsChanged();
  1641. }
  1642. }
  1643. /*! \overload
  1644. Sets the minimum size for the inner \ref rect of this layout element.
  1645. */
  1646. void QCPLayoutElement::setMinimumSize(int width, int height)
  1647. {
  1648. setMinimumSize(QSize(width, height));
  1649. }
  1650. /*!
  1651. Sets the maximum size for the inner \ref rect of this layout element. A parent layout tries to
  1652. respect the \a size here by changing row/column sizes in the layout accordingly.
  1653. */
  1654. void QCPLayoutElement::setMaximumSize(const QSize &size)
  1655. {
  1656. if (mMaximumSize != size)
  1657. {
  1658. mMaximumSize = size;
  1659. if (mParentLayout)
  1660. mParentLayout->sizeConstraintsChanged();
  1661. }
  1662. }
  1663. /*! \overload
  1664. Sets the maximum size for the inner \ref rect of this layout element.
  1665. */
  1666. void QCPLayoutElement::setMaximumSize(int width, int height)
  1667. {
  1668. setMaximumSize(QSize(width, height));
  1669. }
  1670. /*!
  1671. Sets the margin \a group of the specified margin \a sides.
  1672. Margin groups allow synchronizing specified margins across layout elements, see the documentation
  1673. of \ref QCPMarginGroup.
  1674. To unset the margin group of \a sides, set \a group to 0.
  1675. Note that margin groups only work for margin sides that are set to automatic (\ref
  1676. setAutoMargins).
  1677. */
  1678. void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group)
  1679. {
  1680. QVector<QCP::MarginSide> sideVector;
  1681. if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft);
  1682. if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight);
  1683. if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop);
  1684. if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom);
  1685. for (int i=0; i<sideVector.size(); ++i)
  1686. {
  1687. QCP::MarginSide side = sideVector.at(i);
  1688. if (marginGroup(side) != group)
  1689. {
  1690. QCPMarginGroup *oldGroup = marginGroup(side);
  1691. if (oldGroup) // unregister at old group
  1692. oldGroup->removeChild(side, this);
  1693. if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there
  1694. {
  1695. mMarginGroups.remove(side);
  1696. } else // setting to a new group
  1697. {
  1698. mMarginGroups[side] = group;
  1699. group->addChild(side, this);
  1700. }
  1701. }
  1702. }
  1703. }
  1704. /*!
  1705. Updates the layout element and sub-elements. This function is automatically called before every
  1706. replot by the parent layout element. It is called multiple times, once for every \ref
  1707. UpdatePhase. The phases are run through in the order of the enum values. For details about what
  1708. happens at the different phases, see the documentation of \ref UpdatePhase.
  1709. Layout elements that have child elements should call the \ref update method of their child
  1710. elements, and pass the current \a phase unchanged.
  1711. The default implementation executes the automatic margin mechanism in the \ref upMargins phase.
  1712. Subclasses should make sure to call the base class implementation.
  1713. */
  1714. void QCPLayoutElement::update(UpdatePhase phase)
  1715. {
  1716. if (phase == upMargins)
  1717. {
  1718. if (mAutoMargins != QCP::msNone)
  1719. {
  1720. // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group:
  1721. QMargins newMargins = mMargins;
  1722. foreach (QCP::MarginSide side, QList<QCP::MarginSide>() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom)
  1723. {
  1724. if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically
  1725. {
  1726. if (mMarginGroups.contains(side))
  1727. QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group
  1728. else
  1729. QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly
  1730. // apply minimum margin restrictions:
  1731. if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side))
  1732. QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side));
  1733. }
  1734. }
  1735. setMargins(newMargins);
  1736. }
  1737. }
  1738. }
  1739. /*!
  1740. Returns the minimum size this layout element (the inner \ref rect) may be compressed to.
  1741. if a minimum size (\ref setMinimumSize) was not set manually, parent layouts consult this
  1742. function to determine the minimum allowed size of this layout element. (A manual minimum size is
  1743. considered set if it is non-zero.)
  1744. */
  1745. QSize QCPLayoutElement::minimumSizeHint() const
  1746. {
  1747. return mMinimumSize;
  1748. }
  1749. /*!
  1750. Returns the maximum size this layout element (the inner \ref rect) may be expanded to.
  1751. if a maximum size (\ref setMaximumSize) was not set manually, parent layouts consult this
  1752. function to determine the maximum allowed size of this layout element. (A manual maximum size is
  1753. considered set if it is smaller than Qt's QWIDGETSIZE_MAX.)
  1754. */
  1755. QSize QCPLayoutElement::maximumSizeHint() const
  1756. {
  1757. return mMaximumSize;
  1758. }
  1759. /*!
  1760. Returns a list of all child elements in this layout element. If \a recursive is true, all
  1761. sub-child elements are included in the list, too.
  1762. \warning There may be entries with value 0 in the returned list. (For example, QCPLayoutGrid may have
  1763. empty cells which yield 0 at the respective index.)
  1764. */
  1765. QList<QCPLayoutElement*> QCPLayoutElement::elements(bool recursive) const
  1766. {
  1767. Q_UNUSED(recursive)
  1768. return QList<QCPLayoutElement*>();
  1769. }
  1770. /*!
  1771. Layout elements are sensitive to events inside their outer rect. If \a pos is within the outer
  1772. rect, this method returns a value corresponding to 0.99 times the parent plot's selection
  1773. tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is
  1774. true, -1.0 is returned.
  1775. See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
  1776. QCPLayoutElement subclasses may reimplement this method to provide more specific selection test
  1777. behaviour.
  1778. */
  1779. double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  1780. {
  1781. Q_UNUSED(details)
  1782. if (onlySelectable)
  1783. return -1;
  1784. if (QRectF(mOuterRect).contains(pos))
  1785. {
  1786. if (mParentPlot)
  1787. return mParentPlot->selectionTolerance()*0.99;
  1788. else
  1789. {
  1790. qDebug() << Q_FUNC_INFO << "parent plot not defined";
  1791. return -1;
  1792. }
  1793. } else
  1794. return -1;
  1795. }
  1796. /*! \internal
  1797. propagates the parent plot initialization to all child elements, by calling \ref
  1798. QCPLayerable::initializeParentPlot on them.
  1799. */
  1800. void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot)
  1801. {
  1802. foreach (QCPLayoutElement* el, elements(false))
  1803. {
  1804. if (!el->parentPlot())
  1805. el->initializeParentPlot(parentPlot);
  1806. }
  1807. }
  1808. /*! \internal
  1809. Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a
  1810. side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the
  1811. returned value will not be smaller than the specified minimum margin.
  1812. The default implementation just returns the respective manual margin (\ref setMargins) or the
  1813. minimum margin, whichever is larger.
  1814. */
  1815. int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side)
  1816. {
  1817. return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side));
  1818. }
  1819. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1820. //////////////////// QCPLayout
  1821. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1822. /*! \class QCPLayout
  1823. \brief The abstract base class for layouts
  1824. This is an abstract base class for layout elements whose main purpose is to define the position
  1825. and size of other child layout elements. In most cases, layouts don't draw anything themselves
  1826. (but there are exceptions to this, e.g. QCPLegend).
  1827. QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts.
  1828. QCPLayout introduces a common interface for accessing and manipulating the child elements. Those
  1829. functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref
  1830. simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions
  1831. to this interface which are more specialized to the form of the layout. For example, \ref
  1832. QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid
  1833. more conveniently.
  1834. Since this is an abstract base class, you can't instantiate it directly. Rather use one of its
  1835. subclasses like QCPLayoutGrid or QCPLayoutInset.
  1836. For a general introduction to the layout system, see the dedicated documentation page \ref
  1837. thelayoutsystem "The Layout System".
  1838. */
  1839. /* start documentation of pure virtual functions */
  1840. /*! \fn virtual int QCPLayout::elementCount() const = 0
  1841. Returns the number of elements/cells in the layout.
  1842. \see elements, elementAt
  1843. */
  1844. /*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0
  1845. Returns the element in the cell with the given \a index. If \a index is invalid, returns 0.
  1846. Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g.
  1847. QCPLayoutGrid), so this function may return 0 in those cases. You may use this function to check
  1848. whether a cell is empty or not.
  1849. \see elements, elementCount, takeAt
  1850. */
  1851. /*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0
  1852. Removes the element with the given \a index from the layout and returns it.
  1853. If the \a index is invalid or the cell with that index is empty, returns 0.
  1854. Note that some layouts don't remove the respective cell right away but leave an empty cell after
  1855. successful removal of the layout element. To collapse empty cells, use \ref simplify.
  1856. \see elementAt, take
  1857. */
  1858. /*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0
  1859. Removes the specified \a element from the layout and returns true on success.
  1860. If the \a element isn't in this layout, returns false.
  1861. Note that some layouts don't remove the respective cell right away but leave an empty cell after
  1862. successful removal of the layout element. To collapse empty cells, use \ref simplify.
  1863. \see takeAt
  1864. */
  1865. /* end documentation of pure virtual functions */
  1866. /*!
  1867. Creates an instance of QCPLayout and sets default values. Note that since QCPLayout
  1868. is an abstract base class, it can't be instantiated directly.
  1869. */
  1870. QCPLayout::QCPLayout()
  1871. {
  1872. }
  1873. /*!
  1874. First calls the QCPLayoutElement::update base class implementation to update the margins on this
  1875. layout.
  1876. Then calls \ref updateLayout which subclasses reimplement to reposition and resize their cells.
  1877. Finally, \ref update is called on all child elements.
  1878. */
  1879. void QCPLayout::update(UpdatePhase phase)
  1880. {
  1881. QCPLayoutElement::update(phase);
  1882. // set child element rects according to layout:
  1883. if (phase == upLayout)
  1884. updateLayout();
  1885. // propagate update call to child elements:
  1886. const int elCount = elementCount();
  1887. for (int i=0; i<elCount; ++i)
  1888. {
  1889. if (QCPLayoutElement *el = elementAt(i))
  1890. el->update(phase);
  1891. }
  1892. }
  1893. /* inherits documentation from base class */
  1894. QList<QCPLayoutElement*> QCPLayout::elements(bool recursive) const
  1895. {
  1896. const int c = elementCount();
  1897. QList<QCPLayoutElement*> result;
  1898. #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
  1899. result.reserve(c);
  1900. #endif
  1901. for (int i=0; i<c; ++i)
  1902. result.append(elementAt(i));
  1903. if (recursive)
  1904. {
  1905. for (int i=0; i<c; ++i)
  1906. {
  1907. if (result.at(i))
  1908. result << result.at(i)->elements(recursive);
  1909. }
  1910. }
  1911. return result;
  1912. }
  1913. /*!
  1914. Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the
  1915. default implementation does nothing.
  1916. Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit
  1917. simplification while QCPLayoutGrid does.
  1918. */
  1919. void QCPLayout::simplify()
  1920. {
  1921. }
  1922. /*!
  1923. Removes and deletes the element at the provided \a index. Returns true on success. If \a index is
  1924. invalid or points to an empty cell, returns false.
  1925. This function internally uses \ref takeAt to remove the element from the layout and then deletes
  1926. the returned element.
  1927. \see remove, takeAt
  1928. */
  1929. bool QCPLayout::removeAt(int index)
  1930. {
  1931. if (QCPLayoutElement *el = takeAt(index))
  1932. {
  1933. delete el;
  1934. return true;
  1935. } else
  1936. return false;
  1937. }
  1938. /*!
  1939. Removes and deletes the provided \a element. Returns true on success. If \a element is not in the
  1940. layout, returns false.
  1941. This function internally uses \ref takeAt to remove the element from the layout and then deletes
  1942. the element.
  1943. \see removeAt, take
  1944. */
  1945. bool QCPLayout::remove(QCPLayoutElement *element)
  1946. {
  1947. if (take(element))
  1948. {
  1949. delete element;
  1950. return true;
  1951. } else
  1952. return false;
  1953. }
  1954. /*!
  1955. Removes and deletes all layout elements in this layout.
  1956. \see remove, removeAt
  1957. */
  1958. void QCPLayout::clear()
  1959. {
  1960. for (int i=elementCount()-1; i>=0; --i)
  1961. {
  1962. if (elementAt(i))
  1963. removeAt(i);
  1964. }
  1965. simplify();
  1966. }
  1967. /*!
  1968. Subclasses call this method to report changed (minimum/maximum) size constraints.
  1969. If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref
  1970. sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of
  1971. QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout,
  1972. it may update itself and resize cells accordingly.
  1973. */
  1974. void QCPLayout::sizeConstraintsChanged() const
  1975. {
  1976. if (QWidget *w = qobject_cast<QWidget*>(parent()))
  1977. w->updateGeometry();
  1978. else if (QCPLayout *l = qobject_cast<QCPLayout*>(parent()))
  1979. l->sizeConstraintsChanged();
  1980. }
  1981. /*! \internal
  1982. Subclasses reimplement this method to update the position and sizes of the child elements/cells
  1983. via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing.
  1984. The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay
  1985. within that rect.
  1986. \ref getSectionSizes may help with the reimplementation of this function.
  1987. \see update
  1988. */
  1989. void QCPLayout::updateLayout()
  1990. {
  1991. }
  1992. /*! \internal
  1993. Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the
  1994. \ref QCPLayerable::parentLayerable and the QObject parent to this layout.
  1995. Further, if \a el didn't previously have a parent plot, calls \ref
  1996. QCPLayerable::initializeParentPlot on \a el to set the paret plot.
  1997. This method is used by subclass specific methods that add elements to the layout. Note that this
  1998. method only changes properties in \a el. The removal from the old layout and the insertion into
  1999. the new layout must be done additionally.
  2000. */
  2001. void QCPLayout::adoptElement(QCPLayoutElement *el)
  2002. {
  2003. if (el)
  2004. {
  2005. el->mParentLayout = this;
  2006. el->setParentLayerable(this);
  2007. el->setParent(this);
  2008. if (!el->parentPlot())
  2009. el->initializeParentPlot(mParentPlot);
  2010. } else
  2011. qDebug() << Q_FUNC_INFO << "Null element passed";
  2012. }
  2013. /*! \internal
  2014. Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout
  2015. and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent
  2016. QCustomPlot.
  2017. This method is used by subclass specific methods that remove elements from the layout (e.g. \ref
  2018. take or \ref takeAt). Note that this method only changes properties in \a el. The removal from
  2019. the old layout must be done additionally.
  2020. */
  2021. void QCPLayout::releaseElement(QCPLayoutElement *el)
  2022. {
  2023. if (el)
  2024. {
  2025. el->mParentLayout = 0;
  2026. el->setParentLayerable(0);
  2027. el->setParent(mParentPlot);
  2028. // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot
  2029. } else
  2030. qDebug() << Q_FUNC_INFO << "Null element passed";
  2031. }
  2032. /*! \internal
  2033. This is a helper function for the implementation of \ref updateLayout in subclasses.
  2034. It calculates the sizes of one-dimensional sections with provided constraints on maximum section
  2035. sizes, minimum section sizes, relative stretch factors and the final total size of all sections.
  2036. The QVector entries refer to the sections. Thus all QVectors must have the same size.
  2037. \a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size
  2038. imposed, set all vector values to Qt's QWIDGETSIZE_MAX.
  2039. \a minSizes gives the minimum allowed size of each section. If there shall be no minimum size
  2040. imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than
  2041. \a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words,
  2042. not exceeding the allowed total size is taken to be more important than not going below minimum
  2043. section sizes.)
  2044. \a stretchFactors give the relative proportions of the sections to each other. If all sections
  2045. shall be scaled equally, set all values equal. If the first section shall be double the size of
  2046. each individual other section, set the first number of \a stretchFactors to double the value of
  2047. the other individual values (e.g. {2, 1, 1, 1}).
  2048. \a totalSize is the value that the final section sizes will add up to. Due to rounding, the
  2049. actual sum may differ slightly. If you want the section sizes to sum up to exactly that value,
  2050. you could distribute the remaining difference on the sections.
  2051. The return value is a QVector containing the section sizes.
  2052. */
  2053. QVector<int> QCPLayout::getSectionSizes(QVector<int> maxSizes, QVector<int> minSizes, QVector<double> stretchFactors, int totalSize) const
  2054. {
  2055. if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size())
  2056. {
  2057. qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors;
  2058. return QVector<int>();
  2059. }
  2060. if (stretchFactors.isEmpty())
  2061. return QVector<int>();
  2062. int sectionCount = stretchFactors.size();
  2063. QVector<double> sectionSizes(sectionCount);
  2064. // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections):
  2065. int minSizeSum = 0;
  2066. for (int i=0; i<sectionCount; ++i)
  2067. minSizeSum += minSizes.at(i);
  2068. if (totalSize < minSizeSum)
  2069. {
  2070. // new stretch factors are minimum sizes and minimum sizes are set to zero:
  2071. for (int i=0; i<sectionCount; ++i)
  2072. {
  2073. stretchFactors[i] = minSizes.at(i);
  2074. minSizes[i] = 0;
  2075. }
  2076. }
  2077. QList<int> minimumLockedSections;
  2078. QList<int> unfinishedSections;
  2079. for (int i=0; i<sectionCount; ++i)
  2080. unfinishedSections.append(i);
  2081. double freeSize = totalSize;
  2082. int outerIterations = 0;
  2083. while (!unfinishedSections.isEmpty() && outerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
  2084. {
  2085. ++outerIterations;
  2086. int innerIterations = 0;
  2087. while (!unfinishedSections.isEmpty() && innerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
  2088. {
  2089. ++innerIterations;
  2090. // find section that hits its maximum next:
  2091. int nextId = -1;
  2092. double nextMax = 1e12;
  2093. for (int i=0; i<unfinishedSections.size(); ++i)
  2094. {
  2095. int secId = unfinishedSections.at(i);
  2096. double hitsMaxAt = (maxSizes.at(secId)-sectionSizes.at(secId))/stretchFactors.at(secId);
  2097. if (hitsMaxAt < nextMax)
  2098. {
  2099. nextMax = hitsMaxAt;
  2100. nextId = secId;
  2101. }
  2102. }
  2103. // 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
  2104. // actually hits its maximum, without exceeding the total size when we add up all sections)
  2105. double stretchFactorSum = 0;
  2106. for (int i=0; i<unfinishedSections.size(); ++i)
  2107. stretchFactorSum += stretchFactors.at(unfinishedSections.at(i));
  2108. double nextMaxLimit = freeSize/stretchFactorSum;
  2109. if (nextMax < nextMaxLimit) // next maximum is actually hit, move forward to that point and fix the size of that section
  2110. {
  2111. for (int i=0; i<unfinishedSections.size(); ++i)
  2112. {
  2113. sectionSizes[unfinishedSections.at(i)] += nextMax*stretchFactors.at(unfinishedSections.at(i)); // increment all sections
  2114. freeSize -= nextMax*stretchFactors.at(unfinishedSections.at(i));
  2115. }
  2116. unfinishedSections.removeOne(nextId); // exclude the section that is now at maximum from further changes
  2117. } else // next maximum isn't hit, just distribute rest of free space on remaining sections
  2118. {
  2119. for (int i=0; i<unfinishedSections.size(); ++i)
  2120. sectionSizes[unfinishedSections.at(i)] += nextMaxLimit*stretchFactors.at(unfinishedSections.at(i)); // increment all sections
  2121. unfinishedSections.clear();
  2122. }
  2123. }
  2124. if (innerIterations == sectionCount*2)
  2125. qDebug() << Q_FUNC_INFO << "Exceeded maximum expected inner iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
  2126. // now check whether the resulting section sizes violate minimum restrictions:
  2127. bool foundMinimumViolation = false;
  2128. for (int i=0; i<sectionSizes.size(); ++i)
  2129. {
  2130. if (minimumLockedSections.contains(i))
  2131. continue;
  2132. if (sectionSizes.at(i) < minSizes.at(i)) // section violates minimum
  2133. {
  2134. sectionSizes[i] = minSizes.at(i); // set it to minimum
  2135. foundMinimumViolation = true; // make sure we repeat the whole optimization process
  2136. minimumLockedSections.append(i);
  2137. }
  2138. }
  2139. if (foundMinimumViolation)
  2140. {
  2141. freeSize = totalSize;
  2142. for (int i=0; i<sectionCount; ++i)
  2143. {
  2144. if (!minimumLockedSections.contains(i)) // only put sections that haven't hit their minimum back into the pool
  2145. unfinishedSections.append(i);
  2146. else
  2147. freeSize -= sectionSizes.at(i); // remove size of minimum locked sections from available space in next round
  2148. }
  2149. // reset all section sizes to zero that are in unfinished sections (all others have been set to their minimum):
  2150. for (int i=0; i<unfinishedSections.size(); ++i)
  2151. sectionSizes[unfinishedSections.at(i)] = 0;
  2152. }
  2153. }
  2154. if (outerIterations == sectionCount*2)
  2155. qDebug() << Q_FUNC_INFO << "Exceeded maximum expected outer iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
  2156. QVector<int> result(sectionCount);
  2157. for (int i=0; i<sectionCount; ++i)
  2158. result[i] = qRound(sectionSizes.at(i));
  2159. return result;
  2160. }
  2161. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2162. //////////////////// QCPLayoutGrid
  2163. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2164. /*! \class QCPLayoutGrid
  2165. \brief A layout that arranges child elements in a grid
  2166. Elements are laid out in a grid with configurable stretch factors (\ref setColumnStretchFactor,
  2167. \ref setRowStretchFactor) and spacing (\ref setColumnSpacing, \ref setRowSpacing).
  2168. Elements can be added to cells via \ref addElement. The grid is expanded if the specified row or
  2169. column doesn't exist yet. Whether a cell contains a valid layout element can be checked with \ref
  2170. hasElement, that element can be retrieved with \ref element. If rows and columns that only have
  2171. empty cells shall be removed, call \ref simplify. Removal of elements is either done by just
  2172. adding the element to a different layout or by using the QCPLayout interface \ref take or \ref
  2173. remove.
  2174. Row and column insertion can be performed with \ref insertRow and \ref insertColumn.
  2175. */
  2176. /*!
  2177. Creates an instance of QCPLayoutGrid and sets default values.
  2178. */
  2179. QCPLayoutGrid::QCPLayoutGrid() :
  2180. mColumnSpacing(5),
  2181. mRowSpacing(5)
  2182. {
  2183. }
  2184. QCPLayoutGrid::~QCPLayoutGrid()
  2185. {
  2186. // clear all child layout elements. This is important because only the specific layouts know how
  2187. // to handle removing elements (clear calls virtual removeAt method to do that).
  2188. clear();
  2189. }
  2190. /*!
  2191. Returns the element in the cell in \a row and \a column.
  2192. Returns 0 if either the row/column is invalid or if the cell is empty. In those cases, a qDebug
  2193. message is printed. To check whether a cell exists and isn't empty, use \ref hasElement.
  2194. \see addElement, hasElement
  2195. */
  2196. QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const
  2197. {
  2198. if (row >= 0 && row < mElements.size())
  2199. {
  2200. if (column >= 0 && column < mElements.first().size())
  2201. {
  2202. if (QCPLayoutElement *result = mElements.at(row).at(column))
  2203. return result;
  2204. else
  2205. qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column;
  2206. } else
  2207. qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column;
  2208. } else
  2209. qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column;
  2210. return 0;
  2211. }
  2212. /*!
  2213. Returns the number of rows in the layout.
  2214. \see columnCount
  2215. */
  2216. int QCPLayoutGrid::rowCount() const
  2217. {
  2218. return mElements.size();
  2219. }
  2220. /*!
  2221. Returns the number of columns in the layout.
  2222. \see rowCount
  2223. */
  2224. int QCPLayoutGrid::columnCount() const
  2225. {
  2226. if (mElements.size() > 0)
  2227. return mElements.first().size();
  2228. else
  2229. return 0;
  2230. }
  2231. /*!
  2232. Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it
  2233. is first removed from there. If \a row or \a column don't exist yet, the layout is expanded
  2234. accordingly.
  2235. Returns true if the element was added successfully, i.e. if the cell at \a row and \a column
  2236. didn't already have an element.
  2237. \see element, hasElement, take, remove
  2238. */
  2239. bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element)
  2240. {
  2241. if (element)
  2242. {
  2243. if (!hasElement(row, column))
  2244. {
  2245. if (element->layout()) // remove from old layout first
  2246. element->layout()->take(element);
  2247. expandTo(row+1, column+1);
  2248. mElements[row][column] = element;
  2249. adoptElement(element);
  2250. return true;
  2251. } else
  2252. qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column;
  2253. } else
  2254. qDebug() << Q_FUNC_INFO << "Can't add null element to row/column:" << row << column;
  2255. return false;
  2256. }
  2257. /*!
  2258. Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't
  2259. empty.
  2260. \see element
  2261. */
  2262. bool QCPLayoutGrid::hasElement(int row, int column)
  2263. {
  2264. if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount())
  2265. return mElements.at(row).at(column);
  2266. else
  2267. return false;
  2268. }
  2269. /*!
  2270. Sets the stretch \a factor of \a column.
  2271. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  2272. their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
  2273. QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
  2274. The default stretch factor of newly created rows/columns is 1.
  2275. \see setColumnStretchFactors, setRowStretchFactor
  2276. */
  2277. void QCPLayoutGrid::setColumnStretchFactor(int column, double factor)
  2278. {
  2279. if (column >= 0 && column < columnCount())
  2280. {
  2281. if (factor > 0)
  2282. mColumnStretchFactors[column] = factor;
  2283. else
  2284. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
  2285. } else
  2286. qDebug() << Q_FUNC_INFO << "Invalid column:" << column;
  2287. }
  2288. /*!
  2289. Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount.
  2290. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  2291. their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
  2292. QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
  2293. The default stretch factor of newly created rows/columns is 1.
  2294. \see setColumnStretchFactor, setRowStretchFactors
  2295. */
  2296. void QCPLayoutGrid::setColumnStretchFactors(const QList<double> &factors)
  2297. {
  2298. if (factors.size() == mColumnStretchFactors.size())
  2299. {
  2300. mColumnStretchFactors = factors;
  2301. for (int i=0; i<mColumnStretchFactors.size(); ++i)
  2302. {
  2303. if (mColumnStretchFactors.at(i) <= 0)
  2304. {
  2305. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mColumnStretchFactors.at(i);
  2306. mColumnStretchFactors[i] = 1;
  2307. }
  2308. }
  2309. } else
  2310. qDebug() << Q_FUNC_INFO << "Column count not equal to passed stretch factor count:" << factors;
  2311. }
  2312. /*!
  2313. Sets the stretch \a factor of \a row.
  2314. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  2315. their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
  2316. QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
  2317. The default stretch factor of newly created rows/columns is 1.
  2318. \see setColumnStretchFactors, setRowStretchFactor
  2319. */
  2320. void QCPLayoutGrid::setRowStretchFactor(int row, double factor)
  2321. {
  2322. if (row >= 0 && row < rowCount())
  2323. {
  2324. if (factor > 0)
  2325. mRowStretchFactors[row] = factor;
  2326. else
  2327. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
  2328. } else
  2329. qDebug() << Q_FUNC_INFO << "Invalid row:" << row;
  2330. }
  2331. /*!
  2332. Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount.
  2333. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  2334. their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
  2335. QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
  2336. The default stretch factor of newly created rows/columns is 1.
  2337. \see setRowStretchFactor, setColumnStretchFactors
  2338. */
  2339. void QCPLayoutGrid::setRowStretchFactors(const QList<double> &factors)
  2340. {
  2341. if (factors.size() == mRowStretchFactors.size())
  2342. {
  2343. mRowStretchFactors = factors;
  2344. for (int i=0; i<mRowStretchFactors.size(); ++i)
  2345. {
  2346. if (mRowStretchFactors.at(i) <= 0)
  2347. {
  2348. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mRowStretchFactors.at(i);
  2349. mRowStretchFactors[i] = 1;
  2350. }
  2351. }
  2352. } else
  2353. qDebug() << Q_FUNC_INFO << "Row count not equal to passed stretch factor count:" << factors;
  2354. }
  2355. /*!
  2356. Sets the gap that is left blank between columns to \a pixels.
  2357. \see setRowSpacing
  2358. */
  2359. void QCPLayoutGrid::setColumnSpacing(int pixels)
  2360. {
  2361. mColumnSpacing = pixels;
  2362. }
  2363. /*!
  2364. Sets the gap that is left blank between rows to \a pixels.
  2365. \see setColumnSpacing
  2366. */
  2367. void QCPLayoutGrid::setRowSpacing(int pixels)
  2368. {
  2369. mRowSpacing = pixels;
  2370. }
  2371. /*!
  2372. Expands the layout to have \a newRowCount rows and \a newColumnCount columns. So the last valid
  2373. row index will be \a newRowCount-1, the last valid column index will be \a newColumnCount-1.
  2374. If the current column/row count is already larger or equal to \a newColumnCount/\a newRowCount,
  2375. this function does nothing in that dimension.
  2376. Newly created cells are empty, new rows and columns have the stretch factor 1.
  2377. Note that upon a call to \ref addElement, the layout is expanded automatically to contain the
  2378. specified row and column, using this function.
  2379. \see simplify
  2380. */
  2381. void QCPLayoutGrid::expandTo(int newRowCount, int newColumnCount)
  2382. {
  2383. // add rows as necessary:
  2384. while (rowCount() < newRowCount)
  2385. {
  2386. mElements.append(QList<QCPLayoutElement*>());
  2387. mRowStretchFactors.append(1);
  2388. }
  2389. // go through rows and expand columns as necessary:
  2390. int newColCount = qMax(columnCount(), newColumnCount);
  2391. for (int i=0; i<rowCount(); ++i)
  2392. {
  2393. while (mElements.at(i).size() < newColCount)
  2394. mElements[i].append(0);
  2395. }
  2396. while (mColumnStretchFactors.size() < newColCount)
  2397. mColumnStretchFactors.append(1);
  2398. }
  2399. /*!
  2400. Inserts a new row with empty cells at the row index \a newIndex. Valid values for \a newIndex
  2401. range from 0 (inserts a row at the top) to \a rowCount (appends a row at the bottom).
  2402. \see insertColumn
  2403. */
  2404. void QCPLayoutGrid::insertRow(int newIndex)
  2405. {
  2406. if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
  2407. {
  2408. expandTo(1, 1);
  2409. return;
  2410. }
  2411. if (newIndex < 0)
  2412. newIndex = 0;
  2413. if (newIndex > rowCount())
  2414. newIndex = rowCount();
  2415. mRowStretchFactors.insert(newIndex, 1);
  2416. QList<QCPLayoutElement*> newRow;
  2417. for (int col=0; col<columnCount(); ++col)
  2418. newRow.append((QCPLayoutElement*)0);
  2419. mElements.insert(newIndex, newRow);
  2420. }
  2421. /*!
  2422. Inserts a new column with empty cells at the column index \a newIndex. Valid values for \a
  2423. newIndex range from 0 (inserts a row at the left) to \a rowCount (appends a row at the right).
  2424. \see insertRow
  2425. */
  2426. void QCPLayoutGrid::insertColumn(int newIndex)
  2427. {
  2428. if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
  2429. {
  2430. expandTo(1, 1);
  2431. return;
  2432. }
  2433. if (newIndex < 0)
  2434. newIndex = 0;
  2435. if (newIndex > columnCount())
  2436. newIndex = columnCount();
  2437. mColumnStretchFactors.insert(newIndex, 1);
  2438. for (int row=0; row<rowCount(); ++row)
  2439. mElements[row].insert(newIndex, (QCPLayoutElement*)0);
  2440. }
  2441. /* inherits documentation from base class */
  2442. void QCPLayoutGrid::updateLayout()
  2443. {
  2444. QVector<int> minColWidths, minRowHeights, maxColWidths, maxRowHeights;
  2445. getMinimumRowColSizes(&minColWidths, &minRowHeights);
  2446. getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
  2447. int totalRowSpacing = (rowCount()-1) * mRowSpacing;
  2448. int totalColSpacing = (columnCount()-1) * mColumnSpacing;
  2449. QVector<int> colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing);
  2450. QVector<int> rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing);
  2451. // go through cells and set rects accordingly:
  2452. int yOffset = mRect.top();
  2453. for (int row=0; row<rowCount(); ++row)
  2454. {
  2455. if (row > 0)
  2456. yOffset += rowHeights.at(row-1)+mRowSpacing;
  2457. int xOffset = mRect.left();
  2458. for (int col=0; col<columnCount(); ++col)
  2459. {
  2460. if (col > 0)
  2461. xOffset += colWidths.at(col-1)+mColumnSpacing;
  2462. if (mElements.at(row).at(col))
  2463. mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row)));
  2464. }
  2465. }
  2466. }
  2467. /* inherits documentation from base class */
  2468. int QCPLayoutGrid::elementCount() const
  2469. {
  2470. return rowCount()*columnCount();
  2471. }
  2472. /* inherits documentation from base class */
  2473. QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const
  2474. {
  2475. if (index >= 0 && index < elementCount())
  2476. return mElements.at(index / columnCount()).at(index % columnCount());
  2477. else
  2478. return 0;
  2479. }
  2480. /* inherits documentation from base class */
  2481. QCPLayoutElement *QCPLayoutGrid::takeAt(int index)
  2482. {
  2483. if (QCPLayoutElement *el = elementAt(index))
  2484. {
  2485. releaseElement(el);
  2486. mElements[index / columnCount()][index % columnCount()] = 0;
  2487. return el;
  2488. } else
  2489. {
  2490. qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
  2491. return 0;
  2492. }
  2493. }
  2494. /* inherits documentation from base class */
  2495. bool QCPLayoutGrid::take(QCPLayoutElement *element)
  2496. {
  2497. if (element)
  2498. {
  2499. for (int i=0; i<elementCount(); ++i)
  2500. {
  2501. if (elementAt(i) == element)
  2502. {
  2503. takeAt(i);
  2504. return true;
  2505. }
  2506. }
  2507. qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
  2508. } else
  2509. qDebug() << Q_FUNC_INFO << "Can't take null element";
  2510. return false;
  2511. }
  2512. /* inherits documentation from base class */
  2513. QList<QCPLayoutElement*> QCPLayoutGrid::elements(bool recursive) const
  2514. {
  2515. QList<QCPLayoutElement*> result;
  2516. int colC = columnCount();
  2517. int rowC = rowCount();
  2518. #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
  2519. result.reserve(colC*rowC);
  2520. #endif
  2521. for (int row=0; row<rowC; ++row)
  2522. {
  2523. for (int col=0; col<colC; ++col)
  2524. {
  2525. result.append(mElements.at(row).at(col));
  2526. }
  2527. }
  2528. if (recursive)
  2529. {
  2530. int c = result.size();
  2531. for (int i=0; i<c; ++i)
  2532. {
  2533. if (result.at(i))
  2534. result << result.at(i)->elements(recursive);
  2535. }
  2536. }
  2537. return result;
  2538. }
  2539. /*!
  2540. Simplifies the layout by collapsing rows and columns which only contain empty cells.
  2541. */
  2542. void QCPLayoutGrid::simplify()
  2543. {
  2544. // remove rows with only empty cells:
  2545. for (int row=rowCount()-1; row>=0; --row)
  2546. {
  2547. bool hasElements = false;
  2548. for (int col=0; col<columnCount(); ++col)
  2549. {
  2550. if (mElements.at(row).at(col))
  2551. {
  2552. hasElements = true;
  2553. break;
  2554. }
  2555. }
  2556. if (!hasElements)
  2557. {
  2558. mRowStretchFactors.removeAt(row);
  2559. mElements.removeAt(row);
  2560. if (mElements.isEmpty()) // removed last element, also remove stretch factor (wouldn't happen below because also columnCount changed to 0 now)
  2561. mColumnStretchFactors.clear();
  2562. }
  2563. }
  2564. // remove columns with only empty cells:
  2565. for (int col=columnCount()-1; col>=0; --col)
  2566. {
  2567. bool hasElements = false;
  2568. for (int row=0; row<rowCount(); ++row)
  2569. {
  2570. if (mElements.at(row).at(col))
  2571. {
  2572. hasElements = true;
  2573. break;
  2574. }
  2575. }
  2576. if (!hasElements)
  2577. {
  2578. mColumnStretchFactors.removeAt(col);
  2579. for (int row=0; row<rowCount(); ++row)
  2580. mElements[row].removeAt(col);
  2581. }
  2582. }
  2583. }
  2584. /* inherits documentation from base class */
  2585. QSize QCPLayoutGrid::minimumSizeHint() const
  2586. {
  2587. QVector<int> minColWidths, minRowHeights;
  2588. getMinimumRowColSizes(&minColWidths, &minRowHeights);
  2589. QSize result(0, 0);
  2590. for (int i=0; i<minColWidths.size(); ++i)
  2591. result.rwidth() += minColWidths.at(i);
  2592. for (int i=0; i<minRowHeights.size(); ++i)
  2593. result.rheight() += minRowHeights.at(i);
  2594. result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing + mMargins.left() + mMargins.right();
  2595. result.rheight() += qMax(0, rowCount()-1) * mRowSpacing + mMargins.top() + mMargins.bottom();
  2596. return result;
  2597. }
  2598. /* inherits documentation from base class */
  2599. QSize QCPLayoutGrid::maximumSizeHint() const
  2600. {
  2601. QVector<int> maxColWidths, maxRowHeights;
  2602. getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
  2603. QSize result(0, 0);
  2604. for (int i=0; i<maxColWidths.size(); ++i)
  2605. result.setWidth(qMin(result.width()+maxColWidths.at(i), QWIDGETSIZE_MAX));
  2606. for (int i=0; i<maxRowHeights.size(); ++i)
  2607. result.setHeight(qMin(result.height()+maxRowHeights.at(i), QWIDGETSIZE_MAX));
  2608. result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing + mMargins.left() + mMargins.right();
  2609. result.rheight() += qMax(0, rowCount()-1) * mRowSpacing + mMargins.top() + mMargins.bottom();
  2610. return result;
  2611. }
  2612. /*! \internal
  2613. Places the minimum column widths and row heights into \a minColWidths and \a minRowHeights
  2614. respectively.
  2615. The minimum height of a row is the largest minimum height of any element in that row. The minimum
  2616. width of a column is the largest minimum width of any element in that column.
  2617. This is a helper function for \ref updateLayout.
  2618. \see getMaximumRowColSizes
  2619. */
  2620. void QCPLayoutGrid::getMinimumRowColSizes(QVector<int> *minColWidths, QVector<int> *minRowHeights) const
  2621. {
  2622. *minColWidths = QVector<int>(columnCount(), 0);
  2623. *minRowHeights = QVector<int>(rowCount(), 0);
  2624. for (int row=0; row<rowCount(); ++row)
  2625. {
  2626. for (int col=0; col<columnCount(); ++col)
  2627. {
  2628. if (mElements.at(row).at(col))
  2629. {
  2630. QSize minHint = mElements.at(row).at(col)->minimumSizeHint();
  2631. QSize min = mElements.at(row).at(col)->minimumSize();
  2632. QSize final(min.width() > 0 ? min.width() : minHint.width(), min.height() > 0 ? min.height() : minHint.height());
  2633. if (minColWidths->at(col) < final.width())
  2634. (*minColWidths)[col] = final.width();
  2635. if (minRowHeights->at(row) < final.height())
  2636. (*minRowHeights)[row] = final.height();
  2637. }
  2638. }
  2639. }
  2640. }
  2641. /*! \internal
  2642. Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights
  2643. respectively.
  2644. The maximum height of a row is the smallest maximum height of any element in that row. The
  2645. maximum width of a column is the smallest maximum width of any element in that column.
  2646. This is a helper function for \ref updateLayout.
  2647. \see getMinimumRowColSizes
  2648. */
  2649. void QCPLayoutGrid::getMaximumRowColSizes(QVector<int> *maxColWidths, QVector<int> *maxRowHeights) const
  2650. {
  2651. *maxColWidths = QVector<int>(columnCount(), QWIDGETSIZE_MAX);
  2652. *maxRowHeights = QVector<int>(rowCount(), QWIDGETSIZE_MAX);
  2653. for (int row=0; row<rowCount(); ++row)
  2654. {
  2655. for (int col=0; col<columnCount(); ++col)
  2656. {
  2657. if (mElements.at(row).at(col))
  2658. {
  2659. QSize maxHint = mElements.at(row).at(col)->maximumSizeHint();
  2660. QSize max = mElements.at(row).at(col)->maximumSize();
  2661. QSize final(max.width() < QWIDGETSIZE_MAX ? max.width() : maxHint.width(), max.height() < QWIDGETSIZE_MAX ? max.height() : maxHint.height());
  2662. if (maxColWidths->at(col) > final.width())
  2663. (*maxColWidths)[col] = final.width();
  2664. if (maxRowHeights->at(row) > final.height())
  2665. (*maxRowHeights)[row] = final.height();
  2666. }
  2667. }
  2668. }
  2669. }
  2670. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2671. //////////////////// QCPLayoutInset
  2672. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2673. /*! \class QCPLayoutInset
  2674. \brief A layout that places child elements aligned to the border or arbitrarily positioned
  2675. Elements are placed either aligned to the border or at arbitrary position in the area of the
  2676. layout. Which placement applies is controlled with the \ref InsetPlacement (\ref
  2677. setInsetPlacement).
  2678. Elements are added via \ref addElement(QCPLayoutElement *element, Qt::Alignment alignment) or
  2679. addElement(QCPLayoutElement *element, const QRectF &rect). If the first method is used, the inset
  2680. placement will default to \ref ipBorderAligned and the element will be aligned according to the
  2681. \a alignment parameter. The second method defaults to \ref ipFree and allows placing elements at
  2682. arbitrary position and size, defined by \a rect.
  2683. The alignment or rect can be set via \ref setInsetAlignment or \ref setInsetRect, respectively.
  2684. This is the layout that every QCPAxisRect has as \ref QCPAxisRect::insetLayout.
  2685. */
  2686. /* start documentation of inline functions */
  2687. /*! \fn virtual void QCPLayoutInset::simplify()
  2688. The QCPInsetLayout does not need simplification since it can never have empty cells due to its
  2689. linear index structure. This method does nothing.
  2690. */
  2691. /* end documentation of inline functions */
  2692. /*!
  2693. Creates an instance of QCPLayoutInset and sets default values.
  2694. */
  2695. QCPLayoutInset::QCPLayoutInset()
  2696. {
  2697. }
  2698. QCPLayoutInset::~QCPLayoutInset()
  2699. {
  2700. // clear all child layout elements. This is important because only the specific layouts know how
  2701. // to handle removing elements (clear calls virtual removeAt method to do that).
  2702. clear();
  2703. }
  2704. /*!
  2705. Returns the placement type of the element with the specified \a index.
  2706. */
  2707. QCPLayoutInset::InsetPlacement QCPLayoutInset::insetPlacement(int index) const
  2708. {
  2709. if (elementAt(index))
  2710. return mInsetPlacement.at(index);
  2711. else
  2712. {
  2713. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  2714. return ipFree;
  2715. }
  2716. }
  2717. /*!
  2718. Returns the alignment of the element with the specified \a index. The alignment only has a
  2719. meaning, if the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned.
  2720. */
  2721. Qt::Alignment QCPLayoutInset::insetAlignment(int index) const
  2722. {
  2723. if (elementAt(index))
  2724. return mInsetAlignment.at(index);
  2725. else
  2726. {
  2727. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  2728. return 0;
  2729. }
  2730. }
  2731. /*!
  2732. Returns the rect of the element with the specified \a index. The rect only has a
  2733. meaning, if the inset placement (\ref setInsetPlacement) is \ref ipFree.
  2734. */
  2735. QRectF QCPLayoutInset::insetRect(int index) const
  2736. {
  2737. if (elementAt(index))
  2738. return mInsetRect.at(index);
  2739. else
  2740. {
  2741. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  2742. return QRectF();
  2743. }
  2744. }
  2745. /*!
  2746. Sets the inset placement type of the element with the specified \a index to \a placement.
  2747. \see InsetPlacement
  2748. */
  2749. void QCPLayoutInset::setInsetPlacement(int index, QCPLayoutInset::InsetPlacement placement)
  2750. {
  2751. if (elementAt(index))
  2752. mInsetPlacement[index] = placement;
  2753. else
  2754. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  2755. }
  2756. /*!
  2757. If the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned, this function
  2758. is used to set the alignment of the element with the specified \a index to \a alignment.
  2759. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
  2760. Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
  2761. alignment flags will be ignored.
  2762. */
  2763. void QCPLayoutInset::setInsetAlignment(int index, Qt::Alignment alignment)
  2764. {
  2765. if (elementAt(index))
  2766. mInsetAlignment[index] = alignment;
  2767. else
  2768. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  2769. }
  2770. /*!
  2771. If the inset placement (\ref setInsetPlacement) is \ref ipFree, this function is used to set the
  2772. position and size of the element with the specified \a index to \a rect.
  2773. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
  2774. will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
  2775. corner of the layout, with 35% width and height of the parent layout.
  2776. Note that the minimum and maximum sizes of the embedded element (\ref
  2777. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize) are enforced.
  2778. */
  2779. void QCPLayoutInset::setInsetRect(int index, const QRectF &rect)
  2780. {
  2781. if (elementAt(index))
  2782. mInsetRect[index] = rect;
  2783. else
  2784. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  2785. }
  2786. /* inherits documentation from base class */
  2787. void QCPLayoutInset::updateLayout()
  2788. {
  2789. for (int i=0; i<mElements.size(); ++i)
  2790. {
  2791. QRect insetRect;
  2792. QSize finalMinSize, finalMaxSize;
  2793. QSize minSizeHint = mElements.at(i)->minimumSizeHint();
  2794. QSize maxSizeHint = mElements.at(i)->maximumSizeHint();
  2795. finalMinSize.setWidth(mElements.at(i)->minimumSize().width() > 0 ? mElements.at(i)->minimumSize().width() : minSizeHint.width());
  2796. finalMinSize.setHeight(mElements.at(i)->minimumSize().height() > 0 ? mElements.at(i)->minimumSize().height() : minSizeHint.height());
  2797. finalMaxSize.setWidth(mElements.at(i)->maximumSize().width() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().width() : maxSizeHint.width());
  2798. finalMaxSize.setHeight(mElements.at(i)->maximumSize().height() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().height() : maxSizeHint.height());
  2799. if (mInsetPlacement.at(i) == ipFree)
  2800. {
  2801. insetRect = QRect(rect().x()+rect().width()*mInsetRect.at(i).x(),
  2802. rect().y()+rect().height()*mInsetRect.at(i).y(),
  2803. rect().width()*mInsetRect.at(i).width(),
  2804. rect().height()*mInsetRect.at(i).height());
  2805. if (insetRect.size().width() < finalMinSize.width())
  2806. insetRect.setWidth(finalMinSize.width());
  2807. if (insetRect.size().height() < finalMinSize.height())
  2808. insetRect.setHeight(finalMinSize.height());
  2809. if (insetRect.size().width() > finalMaxSize.width())
  2810. insetRect.setWidth(finalMaxSize.width());
  2811. if (insetRect.size().height() > finalMaxSize.height())
  2812. insetRect.setHeight(finalMaxSize.height());
  2813. } else if (mInsetPlacement.at(i) == ipBorderAligned)
  2814. {
  2815. insetRect.setSize(finalMinSize);
  2816. Qt::Alignment al = mInsetAlignment.at(i);
  2817. if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x());
  2818. else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width());
  2819. else insetRect.moveLeft(rect().x()+rect().width()*0.5-finalMinSize.width()*0.5); // default to Qt::AlignHCenter
  2820. if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y());
  2821. else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height());
  2822. else insetRect.moveTop(rect().y()+rect().height()*0.5-finalMinSize.height()*0.5); // default to Qt::AlignVCenter
  2823. }
  2824. mElements.at(i)->setOuterRect(insetRect);
  2825. }
  2826. }
  2827. /* inherits documentation from base class */
  2828. int QCPLayoutInset::elementCount() const
  2829. {
  2830. return mElements.size();
  2831. }
  2832. /* inherits documentation from base class */
  2833. QCPLayoutElement *QCPLayoutInset::elementAt(int index) const
  2834. {
  2835. if (index >= 0 && index < mElements.size())
  2836. return mElements.at(index);
  2837. else
  2838. return 0;
  2839. }
  2840. /* inherits documentation from base class */
  2841. QCPLayoutElement *QCPLayoutInset::takeAt(int index)
  2842. {
  2843. if (QCPLayoutElement *el = elementAt(index))
  2844. {
  2845. releaseElement(el);
  2846. mElements.removeAt(index);
  2847. mInsetPlacement.removeAt(index);
  2848. mInsetAlignment.removeAt(index);
  2849. mInsetRect.removeAt(index);
  2850. return el;
  2851. } else
  2852. {
  2853. qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
  2854. return 0;
  2855. }
  2856. }
  2857. /* inherits documentation from base class */
  2858. bool QCPLayoutInset::take(QCPLayoutElement *element)
  2859. {
  2860. if (element)
  2861. {
  2862. for (int i=0; i<elementCount(); ++i)
  2863. {
  2864. if (elementAt(i) == element)
  2865. {
  2866. takeAt(i);
  2867. return true;
  2868. }
  2869. }
  2870. qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
  2871. } else
  2872. qDebug() << Q_FUNC_INFO << "Can't take null element";
  2873. return false;
  2874. }
  2875. /*!
  2876. The inset layout is sensitive to events only at areas where its (visible) child elements are
  2877. sensitive. If the selectTest method of any of the child elements returns a positive number for \a
  2878. pos, this method returns a value corresponding to 0.99 times the parent plot's selection
  2879. tolerance. The inset layout is not selectable itself by default. So if \a onlySelectable is true,
  2880. -1.0 is returned.
  2881. See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
  2882. */
  2883. double QCPLayoutInset::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  2884. {
  2885. Q_UNUSED(details)
  2886. if (onlySelectable)
  2887. return -1;
  2888. for (int i=0; i<mElements.size(); ++i)
  2889. {
  2890. // inset layout shall only return positive selectTest, if actually an inset object is at pos
  2891. // else it would block the entire underlying QCPAxisRect with its surface.
  2892. if (mElements.at(i)->realVisibility() && mElements.at(i)->selectTest(pos, onlySelectable) >= 0)
  2893. return mParentPlot->selectionTolerance()*0.99;
  2894. }
  2895. return -1;
  2896. }
  2897. /*!
  2898. Adds the specified \a element to the layout as an inset aligned at the border (\ref
  2899. setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a
  2900. alignment.
  2901. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
  2902. Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
  2903. alignment flags will be ignored.
  2904. \see addElement(QCPLayoutElement *element, const QRectF &rect)
  2905. */
  2906. void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment)
  2907. {
  2908. if (element)
  2909. {
  2910. if (element->layout()) // remove from old layout first
  2911. element->layout()->take(element);
  2912. mElements.append(element);
  2913. mInsetPlacement.append(ipBorderAligned);
  2914. mInsetAlignment.append(alignment);
  2915. mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4));
  2916. adoptElement(element);
  2917. } else
  2918. qDebug() << Q_FUNC_INFO << "Can't add null element";
  2919. }
  2920. /*!
  2921. Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref
  2922. setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a
  2923. rect.
  2924. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
  2925. will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
  2926. corner of the layout, with 35% width and height of the parent layout.
  2927. \see addElement(QCPLayoutElement *element, Qt::Alignment alignment)
  2928. */
  2929. void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect)
  2930. {
  2931. if (element)
  2932. {
  2933. if (element->layout()) // remove from old layout first
  2934. element->layout()->take(element);
  2935. mElements.append(element);
  2936. mInsetPlacement.append(ipFree);
  2937. mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop);
  2938. mInsetRect.append(rect);
  2939. adoptElement(element);
  2940. } else
  2941. qDebug() << Q_FUNC_INFO << "Can't add null element";
  2942. }
  2943. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2944. //////////////////// QCPLineEnding
  2945. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2946. /*! \class QCPLineEnding
  2947. \brief Handles the different ending decorations for line-like items
  2948. \image html QCPLineEnding.png "The various ending styles currently supported"
  2949. For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine
  2950. has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail.
  2951. The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can
  2952. be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of
  2953. the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item.
  2954. For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite
  2955. directions, e.g. "outward". This can be changed by \ref setInverted, which would make the
  2956. respective arrow point inward.
  2957. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a
  2958. QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g. \code
  2959. myItemLine->setHead(QCPLineEnding::esSpikeArrow) \endcode
  2960. */
  2961. /*!
  2962. Creates a QCPLineEnding instance with default values (style \ref esNone).
  2963. */
  2964. QCPLineEnding::QCPLineEnding() :
  2965. mStyle(esNone),
  2966. mWidth(8),
  2967. mLength(10),
  2968. mInverted(false)
  2969. {
  2970. }
  2971. /*!
  2972. Creates a QCPLineEnding instance with the specified values.
  2973. */
  2974. QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) :
  2975. mStyle(style),
  2976. mWidth(width),
  2977. mLength(length),
  2978. mInverted(inverted)
  2979. {
  2980. }
  2981. /*!
  2982. Sets the style of the ending decoration.
  2983. */
  2984. void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style)
  2985. {
  2986. mStyle = style;
  2987. }
  2988. /*!
  2989. Sets the width of the ending decoration, if the style supports it. On arrows, for example, the
  2990. width defines the size perpendicular to the arrow's pointing direction.
  2991. \see setLength
  2992. */
  2993. void QCPLineEnding::setWidth(double width)
  2994. {
  2995. mWidth = width;
  2996. }
  2997. /*!
  2998. Sets the length of the ending decoration, if the style supports it. On arrows, for example, the
  2999. length defines the size in pointing direction.
  3000. \see setWidth
  3001. */
  3002. void QCPLineEnding::setLength(double length)
  3003. {
  3004. mLength = length;
  3005. }
  3006. /*!
  3007. Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point
  3008. inward when \a inverted is set to true.
  3009. Note that also the \a width direction is inverted. For symmetrical ending styles like arrows or
  3010. discs, this doesn't make a difference. However, asymmetric styles like \ref esHalfBar are
  3011. affected by it, which can be used to control to which side the half bar points to.
  3012. */
  3013. void QCPLineEnding::setInverted(bool inverted)
  3014. {
  3015. mInverted = inverted;
  3016. }
  3017. /*! \internal
  3018. Returns the maximum pixel radius the ending decoration might cover, starting from the position
  3019. the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item).
  3020. This is relevant for clipping. Only omit painting of the decoration when the position where the
  3021. decoration is supposed to be drawn is farther away from the clipping rect than the returned
  3022. distance.
  3023. */
  3024. double QCPLineEnding::boundingDistance() const
  3025. {
  3026. switch (mStyle)
  3027. {
  3028. case esNone:
  3029. return 0;
  3030. case esFlatArrow:
  3031. case esSpikeArrow:
  3032. case esLineArrow:
  3033. case esSkewedBar:
  3034. return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length
  3035. case esDisc:
  3036. case esSquare:
  3037. case esDiamond:
  3038. case esBar:
  3039. case esHalfBar:
  3040. return mWidth*1.42; // items that only have a width -> width*sqrt(2)
  3041. }
  3042. return 0;
  3043. }
  3044. /*!
  3045. Starting from the origin of this line ending (which is style specific), returns the length
  3046. covered by the line ending symbol, in backward direction.
  3047. For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if
  3048. both have the same \ref setLength value, because the spike arrow has an inward curved back, which
  3049. reduces the length along its center axis (the drawing origin for arrows is at the tip).
  3050. This function is used for precise, style specific placement of line endings, for example in
  3051. QCPAxes.
  3052. */
  3053. double QCPLineEnding::realLength() const
  3054. {
  3055. switch (mStyle)
  3056. {
  3057. case esNone:
  3058. case esLineArrow:
  3059. case esSkewedBar:
  3060. case esBar:
  3061. case esHalfBar:
  3062. return 0;
  3063. case esFlatArrow:
  3064. return mLength;
  3065. case esDisc:
  3066. case esSquare:
  3067. case esDiamond:
  3068. return mWidth*0.5;
  3069. case esSpikeArrow:
  3070. return mLength*0.8;
  3071. }
  3072. return 0;
  3073. }
  3074. /*! \internal
  3075. Draws the line ending with the specified \a painter at the position \a pos. The direction of the
  3076. line ending is controlled with \a dir.
  3077. */
  3078. void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const
  3079. {
  3080. if (mStyle == esNone)
  3081. return;
  3082. QVector2D lengthVec(dir.normalized());
  3083. if (lengthVec.isNull())
  3084. lengthVec = QVector2D(1, 0);
  3085. QVector2D widthVec(-lengthVec.y(), lengthVec.x());
  3086. lengthVec *= (float)(mLength*(mInverted ? -1 : 1));
  3087. widthVec *= (float)(mWidth*0.5*(mInverted ? -1 : 1));
  3088. QPen penBackup = painter->pen();
  3089. QBrush brushBackup = painter->brush();
  3090. QPen miterPen = penBackup;
  3091. miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey
  3092. QBrush brush(painter->pen().color(), Qt::SolidPattern);
  3093. switch (mStyle)
  3094. {
  3095. case esNone: break;
  3096. case esFlatArrow:
  3097. {
  3098. QPointF points[3] = {pos.toPointF(),
  3099. (pos-lengthVec+widthVec).toPointF(),
  3100. (pos-lengthVec-widthVec).toPointF()
  3101. };
  3102. painter->setPen(miterPen);
  3103. painter->setBrush(brush);
  3104. painter->drawConvexPolygon(points, 3);
  3105. painter->setBrush(brushBackup);
  3106. painter->setPen(penBackup);
  3107. break;
  3108. }
  3109. case esSpikeArrow:
  3110. {
  3111. QPointF points[4] = {pos.toPointF(),
  3112. (pos-lengthVec+widthVec).toPointF(),
  3113. (pos-lengthVec*0.8f).toPointF(),
  3114. (pos-lengthVec-widthVec).toPointF()
  3115. };
  3116. painter->setPen(miterPen);
  3117. painter->setBrush(brush);
  3118. painter->drawConvexPolygon(points, 4);
  3119. painter->setBrush(brushBackup);
  3120. painter->setPen(penBackup);
  3121. break;
  3122. }
  3123. case esLineArrow:
  3124. {
  3125. QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(),
  3126. pos.toPointF(),
  3127. (pos-lengthVec-widthVec).toPointF()
  3128. };
  3129. painter->setPen(miterPen);
  3130. painter->drawPolyline(points, 3);
  3131. painter->setPen(penBackup);
  3132. break;
  3133. }
  3134. case esDisc:
  3135. {
  3136. painter->setBrush(brush);
  3137. painter->drawEllipse(pos.toPointF(), mWidth*0.5, mWidth*0.5);
  3138. painter->setBrush(brushBackup);
  3139. break;
  3140. }
  3141. case esSquare:
  3142. {
  3143. QVector2D widthVecPerp(-widthVec.y(), widthVec.x());
  3144. QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(),
  3145. (pos-widthVecPerp-widthVec).toPointF(),
  3146. (pos+widthVecPerp-widthVec).toPointF(),
  3147. (pos+widthVecPerp+widthVec).toPointF()
  3148. };
  3149. painter->setPen(miterPen);
  3150. painter->setBrush(brush);
  3151. painter->drawConvexPolygon(points, 4);
  3152. painter->setBrush(brushBackup);
  3153. painter->setPen(penBackup);
  3154. break;
  3155. }
  3156. case esDiamond:
  3157. {
  3158. QVector2D widthVecPerp(-widthVec.y(), widthVec.x());
  3159. QPointF points[4] = {(pos-widthVecPerp).toPointF(),
  3160. (pos-widthVec).toPointF(),
  3161. (pos+widthVecPerp).toPointF(),
  3162. (pos+widthVec).toPointF()
  3163. };
  3164. painter->setPen(miterPen);
  3165. painter->setBrush(brush);
  3166. painter->drawConvexPolygon(points, 4);
  3167. painter->setBrush(brushBackup);
  3168. painter->setPen(penBackup);
  3169. break;
  3170. }
  3171. case esBar:
  3172. {
  3173. painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF());
  3174. break;
  3175. }
  3176. case esHalfBar:
  3177. {
  3178. painter->drawLine((pos+widthVec).toPointF(), pos.toPointF());
  3179. break;
  3180. }
  3181. case esSkewedBar:
  3182. {
  3183. if (qFuzzyIsNull(painter->pen().widthF()) && !painter->modes().testFlag(QCPPainter::pmNonCosmetic))
  3184. {
  3185. // if drawing with cosmetic pen (perfectly thin stroke, happens only in vector exports), draw bar exactly on tip of line
  3186. painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)).toPointF(),
  3187. (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)).toPointF());
  3188. } else
  3189. {
  3190. // if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly
  3191. painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF(),
  3192. (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF());
  3193. }
  3194. break;
  3195. }
  3196. }
  3197. }
  3198. /*! \internal
  3199. \overload
  3200. Draws the line ending. The direction is controlled with the \a angle parameter in radians.
  3201. */
  3202. void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, double angle) const
  3203. {
  3204. draw(painter, pos, QVector2D(qCos(angle), qSin(angle)));
  3205. }
  3206. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3207. //////////////////// QCPGrid
  3208. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3209. /*! \class QCPGrid
  3210. \brief Responsible for drawing the grid of a QCPAxis.
  3211. This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the
  3212. grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref
  3213. QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself.
  3214. The axis and grid drawing was split into two classes to allow them to be placed on different
  3215. layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid
  3216. in the background and the axes in the foreground, and any plottables/items in between. This
  3217. described situation is the default setup, see the QCPLayer documentation.
  3218. */
  3219. /*!
  3220. Creates a QCPGrid instance and sets default values.
  3221. You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid.
  3222. */
  3223. QCPGrid::QCPGrid(QCPAxis *parentAxis) :
  3224. QCPLayerable(parentAxis->parentPlot(), "", parentAxis),
  3225. mParentAxis(parentAxis)
  3226. {
  3227. // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called
  3228. setParent(parentAxis);
  3229. setPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
  3230. setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
  3231. setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine));
  3232. setSubGridVisible(false);
  3233. setAntialiased(false);
  3234. setAntialiasedSubGrid(false);
  3235. setAntialiasedZeroLine(false);
  3236. }
  3237. /*!
  3238. Sets whether grid lines at sub tick marks are drawn.
  3239. \see setSubGridPen
  3240. */
  3241. void QCPGrid::setSubGridVisible(bool visible)
  3242. {
  3243. mSubGridVisible = visible;
  3244. }
  3245. /*!
  3246. Sets whether sub grid lines are drawn antialiased.
  3247. */
  3248. void QCPGrid::setAntialiasedSubGrid(bool enabled)
  3249. {
  3250. mAntialiasedSubGrid = enabled;
  3251. }
  3252. /*!
  3253. Sets whether zero lines are drawn antialiased.
  3254. */
  3255. void QCPGrid::setAntialiasedZeroLine(bool enabled)
  3256. {
  3257. mAntialiasedZeroLine = enabled;
  3258. }
  3259. /*!
  3260. Sets the pen with which (major) grid lines are drawn.
  3261. */
  3262. void QCPGrid::setPen(const QPen &pen)
  3263. {
  3264. mPen = pen;
  3265. }
  3266. /*!
  3267. Sets the pen with which sub grid lines are drawn.
  3268. */
  3269. void QCPGrid::setSubGridPen(const QPen &pen)
  3270. {
  3271. mSubGridPen = pen;
  3272. }
  3273. /*!
  3274. Sets the pen with which zero lines are drawn.
  3275. Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid
  3276. lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen.
  3277. */
  3278. void QCPGrid::setZeroLinePen(const QPen &pen)
  3279. {
  3280. mZeroLinePen = pen;
  3281. }
  3282. /*! \internal
  3283. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  3284. before drawing the major grid lines.
  3285. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  3286. This function takes into account the local setting of the antialiasing flag as well as the
  3287. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  3288. QCustomPlot::setNotAntialiasedElements.
  3289. \see setAntialiased
  3290. */
  3291. void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const
  3292. {
  3293. applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid);
  3294. }
  3295. /*! \internal
  3296. Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning
  3297. over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen).
  3298. */
  3299. void QCPGrid::draw(QCPPainter *painter)
  3300. {
  3301. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  3302. if (mSubGridVisible)
  3303. drawSubGridLines(painter);
  3304. drawGridLines(painter);
  3305. }
  3306. /*! \internal
  3307. Draws the main grid lines and possibly a zero line with the specified painter.
  3308. This is a helper function called by \ref draw.
  3309. */
  3310. void QCPGrid::drawGridLines(QCPPainter *painter) const
  3311. {
  3312. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  3313. int lowTick = mParentAxis->mLowestVisibleTick;
  3314. int highTick = mParentAxis->mHighestVisibleTick;
  3315. double t; // helper variable, result of coordinate-to-pixel transforms
  3316. if (mParentAxis->orientation() == Qt::Horizontal)
  3317. {
  3318. // draw zeroline:
  3319. int zeroLineIndex = -1;
  3320. if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
  3321. {
  3322. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  3323. painter->setPen(mZeroLinePen);
  3324. double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero
  3325. for (int i=lowTick; i <= highTick; ++i)
  3326. {
  3327. if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
  3328. {
  3329. zeroLineIndex = i;
  3330. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
  3331. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  3332. break;
  3333. }
  3334. }
  3335. }
  3336. // draw grid lines:
  3337. applyDefaultAntialiasingHint(painter);
  3338. painter->setPen(mPen);
  3339. for (int i=lowTick; i <= highTick; ++i)
  3340. {
  3341. if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
  3342. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
  3343. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  3344. }
  3345. } else
  3346. {
  3347. // draw zeroline:
  3348. int zeroLineIndex = -1;
  3349. if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
  3350. {
  3351. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  3352. painter->setPen(mZeroLinePen);
  3353. double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero
  3354. for (int i=lowTick; i <= highTick; ++i)
  3355. {
  3356. if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
  3357. {
  3358. zeroLineIndex = i;
  3359. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
  3360. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  3361. break;
  3362. }
  3363. }
  3364. }
  3365. // draw grid lines:
  3366. applyDefaultAntialiasingHint(painter);
  3367. painter->setPen(mPen);
  3368. for (int i=lowTick; i <= highTick; ++i)
  3369. {
  3370. if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
  3371. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
  3372. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  3373. }
  3374. }
  3375. }
  3376. /*! \internal
  3377. Draws the sub grid lines with the specified painter.
  3378. This is a helper function called by \ref draw.
  3379. */
  3380. void QCPGrid::drawSubGridLines(QCPPainter *painter) const
  3381. {
  3382. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  3383. applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid);
  3384. double t; // helper variable, result of coordinate-to-pixel transforms
  3385. painter->setPen(mSubGridPen);
  3386. if (mParentAxis->orientation() == Qt::Horizontal)
  3387. {
  3388. for (int i=0; i<mParentAxis->mSubTickVector.size(); ++i)
  3389. {
  3390. t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // x
  3391. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  3392. }
  3393. } else
  3394. {
  3395. for (int i=0; i<mParentAxis->mSubTickVector.size(); ++i)
  3396. {
  3397. t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // y
  3398. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  3399. }
  3400. }
  3401. }
  3402. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3403. //////////////////// QCPAxis
  3404. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3405. /*! \class QCPAxis
  3406. \brief Manages a single axis inside a QCustomPlot.
  3407. Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via
  3408. QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and
  3409. QCustomPlot::yAxis2 (right).
  3410. Axes are always part of an axis rect, see QCPAxisRect.
  3411. \image html AxisNamesOverview.png
  3412. <center>Naming convention of axis parts</center>
  3413. \n
  3414. \image html AxisRectSpacingOverview.png
  3415. <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line
  3416. on the left represents the QCustomPlot widget border.</center>
  3417. */
  3418. /* start of documentation of inline functions */
  3419. /*! \fn Qt::Orientation QCPAxis::orientation() const
  3420. Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced
  3421. from the axis type (left, top, right or bottom).
  3422. \see orientation(AxisType type)
  3423. */
  3424. /*! \fn QCPGrid *QCPAxis::grid() const
  3425. Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the
  3426. grid is displayed.
  3427. */
  3428. /*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type)
  3429. Returns the orientation of the specified axis type
  3430. \see orientation()
  3431. */
  3432. /* end of documentation of inline functions */
  3433. /* start of documentation of signals */
  3434. /*! \fn void QCPAxis::ticksRequest()
  3435. This signal is emitted when \ref setAutoTicks is false and the axis is about to generate tick
  3436. labels for a replot.
  3437. Modifying the tick positions can be done with \ref setTickVector. If you also want to control the
  3438. tick labels, set \ref setAutoTickLabels to false and also provide the labels with \ref
  3439. setTickVectorLabels.
  3440. If you only want static ticks you probably don't need this signal, since you can just set the
  3441. tick vector (and possibly tick label vector) once. However, if you want to provide ticks (and
  3442. maybe labels) dynamically, e.g. depending on the current axis range, connect a slot to this
  3443. signal and set the vector/vectors there.
  3444. */
  3445. /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange)
  3446. This signal is emitted when the range of this axis has changed. You can connect it to the \ref
  3447. setRange slot of another axis to communicate the new range to the other axis, in order for it to
  3448. be synchronized.
  3449. */
  3450. /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange)
  3451. \overload
  3452. Additionally to the new range, this signal also provides the previous range held by the axis as
  3453. \a oldRange.
  3454. */
  3455. /*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType);
  3456. This signal is emitted when the scale type changes, by calls to \ref setScaleType
  3457. */
  3458. /*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection)
  3459. This signal is emitted when the selection state of this axis has changed, either by user interaction
  3460. or by a direct call to \ref setSelectedParts.
  3461. */
  3462. /*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts);
  3463. This signal is emitted when the selectability changes, by calls to \ref setSelectableParts
  3464. */
  3465. /* end of documentation of signals */
  3466. /*!
  3467. Constructs an Axis instance of Type \a type for the axis rect \a parent.
  3468. You shouldn't instantiate axes directly, rather use \ref QCPAxisRect::addAxis.
  3469. */
  3470. QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) :
  3471. QCPLayerable(parent->parentPlot(), "", parent),
  3472. // axis base:
  3473. mAxisType(type),
  3474. mAxisRect(parent),
  3475. mPadding(5),
  3476. mOrientation(orientation(type)),
  3477. mSelectableParts(spAxis | spTickLabels | spAxisLabel),
  3478. mSelectedParts(spNone),
  3479. mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  3480. mSelectedBasePen(QPen(Qt::blue, 2)),
  3481. // axis label:
  3482. mLabel(""),
  3483. mLabelFont(mParentPlot->font()),
  3484. mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
  3485. mLabelColor(Qt::black),
  3486. mSelectedLabelColor(Qt::blue),
  3487. // tick labels:
  3488. mTickLabels(true),
  3489. mAutoTickLabels(true),
  3490. mTickLabelType(ltNumber),
  3491. mTickLabelFont(mParentPlot->font()),
  3492. mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
  3493. mTickLabelColor(Qt::black),
  3494. mSelectedTickLabelColor(Qt::blue),
  3495. mDateTimeFormat("hh:mm:ss\ndd.MM.yy"),
  3496. mDateTimeSpec(Qt::LocalTime),
  3497. mNumberPrecision(6),
  3498. mNumberFormatChar('g'),
  3499. mNumberBeautifulPowers(true),
  3500. // ticks and subticks:
  3501. mTicks(true),
  3502. mTickStep(1),
  3503. mSubTickCount(4),
  3504. mAutoTickCount(6),
  3505. mAutoTicks(true),
  3506. mAutoTickStep(true),
  3507. mAutoSubTicks(true),
  3508. mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  3509. mSelectedTickPen(QPen(Qt::blue, 2)),
  3510. mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  3511. mSelectedSubTickPen(QPen(Qt::blue, 2)),
  3512. // scale and range:
  3513. mRange(0, 5),
  3514. mRangeReversed(false),
  3515. mScaleType(stLinear),
  3516. mScaleLogBase(10),
  3517. mScaleLogBaseLogInv(1.0/qLn(mScaleLogBase)),
  3518. // internal members:
  3519. mGrid(new QCPGrid(this)),
  3520. mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())),
  3521. mLowestVisibleTick(0),
  3522. mHighestVisibleTick(-1),
  3523. mCachedMarginValid(false),
  3524. mCachedMargin(0)
  3525. {
  3526. mGrid->setVisible(false);
  3527. setAntialiased(false);
  3528. 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
  3529. if (type == atTop)
  3530. {
  3531. setTickLabelPadding(3);
  3532. setLabelPadding(6);
  3533. } else if (type == atRight)
  3534. {
  3535. setTickLabelPadding(7);
  3536. setLabelPadding(12);
  3537. } else if (type == atBottom)
  3538. {
  3539. setTickLabelPadding(3);
  3540. setLabelPadding(3);
  3541. } else if (type == atLeft)
  3542. {
  3543. setTickLabelPadding(5);
  3544. setLabelPadding(10);
  3545. }
  3546. }
  3547. QCPAxis::~QCPAxis()
  3548. {
  3549. delete mAxisPainter;
  3550. }
  3551. /* No documentation as it is a property getter */
  3552. int QCPAxis::tickLabelPadding() const
  3553. {
  3554. return mAxisPainter->tickLabelPadding;
  3555. }
  3556. /* No documentation as it is a property getter */
  3557. double QCPAxis::tickLabelRotation() const
  3558. {
  3559. return mAxisPainter->tickLabelRotation;
  3560. }
  3561. /* No documentation as it is a property getter */
  3562. QString QCPAxis::numberFormat() const
  3563. {
  3564. QString result;
  3565. result.append(mNumberFormatChar);
  3566. if (mNumberBeautifulPowers)
  3567. {
  3568. result.append("b");
  3569. if (mAxisPainter->numberMultiplyCross)
  3570. result.append("c");
  3571. }
  3572. return result;
  3573. }
  3574. /* No documentation as it is a property getter */
  3575. int QCPAxis::tickLengthIn() const
  3576. {
  3577. return mAxisPainter->tickLengthIn;
  3578. }
  3579. /* No documentation as it is a property getter */
  3580. int QCPAxis::tickLengthOut() const
  3581. {
  3582. return mAxisPainter->tickLengthOut;
  3583. }
  3584. /* No documentation as it is a property getter */
  3585. int QCPAxis::subTickLengthIn() const
  3586. {
  3587. return mAxisPainter->subTickLengthIn;
  3588. }
  3589. /* No documentation as it is a property getter */
  3590. int QCPAxis::subTickLengthOut() const
  3591. {
  3592. return mAxisPainter->subTickLengthOut;
  3593. }
  3594. /* No documentation as it is a property getter */
  3595. int QCPAxis::labelPadding() const
  3596. {
  3597. return mAxisPainter->labelPadding;
  3598. }
  3599. /* No documentation as it is a property getter */
  3600. int QCPAxis::offset() const
  3601. {
  3602. return mAxisPainter->offset;
  3603. }
  3604. /* No documentation as it is a property getter */
  3605. QCPLineEnding QCPAxis::lowerEnding() const
  3606. {
  3607. return mAxisPainter->lowerEnding;
  3608. }
  3609. /* No documentation as it is a property getter */
  3610. QCPLineEnding QCPAxis::upperEnding() const
  3611. {
  3612. return mAxisPainter->upperEnding;
  3613. }
  3614. /*!
  3615. Sets whether the axis uses a linear scale or a logarithmic scale. If \a type is set to \ref
  3616. stLogarithmic, the logarithm base can be set with \ref setScaleLogBase. In logarithmic axis
  3617. scaling, major tick marks appear at all powers of the logarithm base. Properties like tick step
  3618. (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but less major
  3619. ticks, consider choosing a logarithm base of 100, 1000 or even higher.
  3620. If \a type is \ref stLogarithmic and the number format (\ref setNumberFormat) uses the 'b' option
  3621. (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10
  3622. [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]"
  3623. part). To only display the decimal power, set the number precision to zero with
  3624. \ref setNumberPrecision.
  3625. */
  3626. void QCPAxis::setScaleType(QCPAxis::ScaleType type)
  3627. {
  3628. if (mScaleType != type)
  3629. {
  3630. mScaleType = type;
  3631. if (mScaleType == stLogarithmic)
  3632. setRange(mRange.sanitizedForLogScale());
  3633. mCachedMarginValid = false;
  3634. emit scaleTypeChanged(mScaleType);
  3635. }
  3636. }
  3637. /*!
  3638. If \ref setScaleType is set to \ref stLogarithmic, \a base will be the logarithm base of the
  3639. scaling. In logarithmic axis scaling, major tick marks appear at all powers of \a base.
  3640. Properties like tick step (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but
  3641. less major ticks, consider choosing \a base 100, 1000 or even higher.
  3642. */
  3643. void QCPAxis::setScaleLogBase(double base)
  3644. {
  3645. if (base > 1)
  3646. {
  3647. mScaleLogBase = base;
  3648. mScaleLogBaseLogInv = 1.0/qLn(mScaleLogBase); // buffer for faster baseLog() calculation
  3649. mCachedMarginValid = false;
  3650. } else
  3651. qDebug() << Q_FUNC_INFO << "Invalid logarithmic scale base (must be greater 1):" << base;
  3652. }
  3653. /*!
  3654. Sets the range of the axis.
  3655. This slot may be connected with the \ref rangeChanged signal of another axis so this axis
  3656. is always synchronized with the other axis range, when it changes.
  3657. To invert the direction of an axis, use \ref setRangeReversed.
  3658. */
  3659. void QCPAxis::setRange(const QCPRange &range)
  3660. {
  3661. if (range.lower == mRange.lower && range.upper == mRange.upper)
  3662. return;
  3663. if (!QCPRange::validRange(range)) return;
  3664. QCPRange oldRange = mRange;
  3665. if (mScaleType == stLogarithmic)
  3666. {
  3667. mRange = range.sanitizedForLogScale();
  3668. } else
  3669. {
  3670. mRange = range.sanitizedForLinScale();
  3671. }
  3672. mCachedMarginValid = false;
  3673. emit rangeChanged(mRange);
  3674. emit rangeChanged(mRange, oldRange);
  3675. }
  3676. /*!
  3677. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  3678. (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
  3679. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  3680. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  3681. directly.
  3682. \see SelectablePart, setSelectedParts
  3683. */
  3684. void QCPAxis::setSelectableParts(const SelectableParts &selectable)
  3685. {
  3686. if (mSelectableParts != selectable)
  3687. {
  3688. mSelectableParts = selectable;
  3689. emit selectableChanged(mSelectableParts);
  3690. }
  3691. }
  3692. /*!
  3693. Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
  3694. is selected, it uses a different pen/font.
  3695. The entire selection mechanism for axes is handled automatically when \ref
  3696. QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
  3697. wish to change the selection state manually.
  3698. This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
  3699. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  3700. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
  3701. setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
  3702. */
  3703. void QCPAxis::setSelectedParts(const SelectableParts &selected)
  3704. {
  3705. if (mSelectedParts != selected)
  3706. {
  3707. mSelectedParts = selected;
  3708. emit selectionChanged(mSelectedParts);
  3709. }
  3710. }
  3711. /*!
  3712. \overload
  3713. Sets the lower and upper bound of the axis range.
  3714. To invert the direction of an axis, use \ref setRangeReversed.
  3715. There is also a slot to set a range, see \ref setRange(const QCPRange &range).
  3716. */
  3717. void QCPAxis::setRange(double lower, double upper)
  3718. {
  3719. if (lower == mRange.lower && upper == mRange.upper)
  3720. return;
  3721. if (!QCPRange::validRange(lower, upper)) return;
  3722. QCPRange oldRange = mRange;
  3723. mRange.lower = lower;
  3724. mRange.upper = upper;
  3725. if (mScaleType == stLogarithmic)
  3726. {
  3727. mRange = mRange.sanitizedForLogScale();
  3728. } else
  3729. {
  3730. mRange = mRange.sanitizedForLinScale();
  3731. }
  3732. mCachedMarginValid = false;
  3733. emit rangeChanged(mRange);
  3734. emit rangeChanged(mRange, oldRange);
  3735. }
  3736. /*!
  3737. \overload
  3738. Sets the range of the axis.
  3739. The \a position coordinate indicates together with the \a alignment parameter, where the new
  3740. range will be positioned. \a size defines the size of the new axis range. \a alignment may be
  3741. Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
  3742. or center of the range to be aligned with \a position. Any other values of \a alignment will
  3743. default to Qt::AlignCenter.
  3744. */
  3745. void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment)
  3746. {
  3747. if (alignment == Qt::AlignLeft)
  3748. setRange(position, position+size);
  3749. else if (alignment == Qt::AlignRight)
  3750. setRange(position-size, position);
  3751. else // alignment == Qt::AlignCenter
  3752. setRange(position-size/2.0, position+size/2.0);
  3753. }
  3754. /*!
  3755. Sets the lower bound of the axis range. The upper bound is not changed.
  3756. \see setRange
  3757. */
  3758. void QCPAxis::setRangeLower(double lower)
  3759. {
  3760. if (mRange.lower == lower)
  3761. return;
  3762. QCPRange oldRange = mRange;
  3763. mRange.lower = lower;
  3764. if (mScaleType == stLogarithmic)
  3765. {
  3766. mRange = mRange.sanitizedForLogScale();
  3767. } else
  3768. {
  3769. mRange = mRange.sanitizedForLinScale();
  3770. }
  3771. mCachedMarginValid = false;
  3772. emit rangeChanged(mRange);
  3773. emit rangeChanged(mRange, oldRange);
  3774. }
  3775. /*!
  3776. Sets the upper bound of the axis range. The lower bound is not changed.
  3777. \see setRange
  3778. */
  3779. void QCPAxis::setRangeUpper(double upper)
  3780. {
  3781. if (mRange.upper == upper)
  3782. return;
  3783. QCPRange oldRange = mRange;
  3784. mRange.upper = upper;
  3785. if (mScaleType == stLogarithmic)
  3786. {
  3787. mRange = mRange.sanitizedForLogScale();
  3788. } else
  3789. {
  3790. mRange = mRange.sanitizedForLinScale();
  3791. }
  3792. mCachedMarginValid = false;
  3793. emit rangeChanged(mRange);
  3794. emit rangeChanged(mRange, oldRange);
  3795. }
  3796. /*!
  3797. Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
  3798. axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
  3799. direction of increasing values is inverted.
  3800. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
  3801. of the \ref setRange interface will still reference the mathematically smaller number than the \a
  3802. upper part.
  3803. */
  3804. void QCPAxis::setRangeReversed(bool reversed)
  3805. {
  3806. if (mRangeReversed != reversed)
  3807. {
  3808. mRangeReversed = reversed;
  3809. mCachedMarginValid = false;
  3810. }
  3811. }
  3812. /*!
  3813. Sets whether the tick positions should be calculated automatically (either from an automatically
  3814. generated tick step or a tick step provided manually via \ref setTickStep, see \ref setAutoTickStep).
  3815. If \a on is set to false, you must provide the tick positions manually via \ref setTickVector.
  3816. For these manual ticks you may let QCPAxis generate the appropriate labels automatically by
  3817. leaving \ref setAutoTickLabels set to true. If you also wish to control the displayed labels
  3818. manually, set \ref setAutoTickLabels to false and provide the label strings with \ref
  3819. setTickVectorLabels.
  3820. If you need dynamically calculated tick vectors (and possibly tick label vectors), set the
  3821. vectors in a slot connected to the \ref ticksRequest signal.
  3822. \see setAutoTickLabels, setAutoSubTicks, setAutoTickCount, setAutoTickStep
  3823. */
  3824. void QCPAxis::setAutoTicks(bool on)
  3825. {
  3826. if (mAutoTicks != on)
  3827. {
  3828. mAutoTicks = on;
  3829. mCachedMarginValid = false;
  3830. }
  3831. }
  3832. /*!
  3833. When \ref setAutoTickStep is true, \a approximateCount determines how many ticks should be
  3834. generated in the visible range, approximately.
  3835. It's not guaranteed that this number of ticks is met exactly, but approximately within a
  3836. tolerance of about two.
  3837. Only values greater than zero are accepted as \a approximateCount.
  3838. \see setAutoTickStep, setAutoTicks, setAutoSubTicks
  3839. */
  3840. void QCPAxis::setAutoTickCount(int approximateCount)
  3841. {
  3842. if (mAutoTickCount != approximateCount)
  3843. {
  3844. if (approximateCount > 0)
  3845. {
  3846. mAutoTickCount = approximateCount;
  3847. mCachedMarginValid = false;
  3848. } else
  3849. qDebug() << Q_FUNC_INFO << "approximateCount must be greater than zero:" << approximateCount;
  3850. }
  3851. }
  3852. /*!
  3853. Sets whether the tick labels are generated automatically. Depending on the tick label type (\ref
  3854. ltNumber or \ref ltDateTime), the labels will either show the coordinate as floating point
  3855. number (\ref setNumberFormat), or a date/time formatted according to \ref setDateTimeFormat.
  3856. If \a on is set to false, you should provide the tick labels via \ref setTickVectorLabels. This
  3857. is usually used in a combination with \ref setAutoTicks set to false for complete control over
  3858. tick positions and labels, e.g. when the ticks should be at multiples of pi and show "2pi", "3pi"
  3859. etc. as tick labels.
  3860. If you need dynamically calculated tick vectors (and possibly tick label vectors), set the
  3861. vectors in a slot connected to the \ref ticksRequest signal.
  3862. \see setAutoTicks
  3863. */
  3864. void QCPAxis::setAutoTickLabels(bool on)
  3865. {
  3866. if (mAutoTickLabels != on)
  3867. {
  3868. mAutoTickLabels = on;
  3869. mCachedMarginValid = false;
  3870. }
  3871. }
  3872. /*!
  3873. Sets whether the tick step, i.e. the interval between two (major) ticks, is calculated
  3874. automatically. If \a on is set to true, the axis finds a tick step that is reasonable for human
  3875. readable plots.
  3876. The number of ticks the algorithm aims for within the visible range can be specified with \ref
  3877. setAutoTickCount.
  3878. If \a on is set to false, you may set the tick step manually with \ref setTickStep.
  3879. \see setAutoTicks, setAutoSubTicks, setAutoTickCount
  3880. */
  3881. void QCPAxis::setAutoTickStep(bool on)
  3882. {
  3883. if (mAutoTickStep != on)
  3884. {
  3885. mAutoTickStep = on;
  3886. mCachedMarginValid = false;
  3887. }
  3888. }
  3889. /*!
  3890. Sets whether the number of sub ticks in one tick interval is determined automatically. This
  3891. works, as long as the tick step mantissa is a multiple of 0.5. When \ref setAutoTickStep is
  3892. enabled, this is always the case.
  3893. When \a on is set to false, you may set the sub tick count with \ref setSubTickCount manually.
  3894. \see setAutoTickCount, setAutoTicks, setAutoTickStep
  3895. */
  3896. void QCPAxis::setAutoSubTicks(bool on)
  3897. {
  3898. if (mAutoSubTicks != on)
  3899. {
  3900. mAutoSubTicks = on;
  3901. mCachedMarginValid = false;
  3902. }
  3903. }
  3904. /*!
  3905. Sets whether tick marks are displayed.
  3906. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
  3907. that, see \ref setTickLabels.
  3908. */
  3909. void QCPAxis::setTicks(bool show)
  3910. {
  3911. if (mTicks != show)
  3912. {
  3913. mTicks = show;
  3914. mCachedMarginValid = false;
  3915. }
  3916. }
  3917. /*!
  3918. Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
  3919. */
  3920. void QCPAxis::setTickLabels(bool show)
  3921. {
  3922. if (mTickLabels != show)
  3923. {
  3924. mTickLabels = show;
  3925. mCachedMarginValid = false;
  3926. }
  3927. }
  3928. /*!
  3929. Sets the distance between the axis base line (including any outward ticks) and the tick labels.
  3930. \see setLabelPadding, setPadding
  3931. */
  3932. void QCPAxis::setTickLabelPadding(int padding)
  3933. {
  3934. if (mAxisPainter->tickLabelPadding != padding)
  3935. {
  3936. mAxisPainter->tickLabelPadding = padding;
  3937. mCachedMarginValid = false;
  3938. }
  3939. }
  3940. /*!
  3941. Sets whether the tick labels display numbers or dates/times.
  3942. If \a type is set to \ref ltNumber, the format specifications of \ref setNumberFormat apply.
  3943. If \a type is set to \ref ltDateTime, the format specifications of \ref setDateTimeFormat apply.
  3944. In QCustomPlot, date/time coordinates are <tt>double</tt> numbers representing the seconds since
  3945. 1970-01-01T00:00:00 UTC. This format can be retrieved from QDateTime objects with the
  3946. QDateTime::toTime_t() function. Since this only gives a resolution of one second, there is also
  3947. the QDateTime::toMSecsSinceEpoch() function which returns the timespan described above in
  3948. milliseconds. Divide its return value by 1000.0 to get a value with the format needed for
  3949. date/time plotting, with a resolution of one millisecond.
  3950. Using the toMSecsSinceEpoch function allows dates that go back to 2nd January 4713 B.C.
  3951. (represented by a negative number), unlike the toTime_t function, which works with unsigned
  3952. integers and thus only goes back to 1st January 1970. So both for range and accuracy, use of
  3953. toMSecsSinceEpoch()/1000.0 should be preferred as key coordinate for date/time axes.
  3954. \see setTickLabels
  3955. */
  3956. void QCPAxis::setTickLabelType(LabelType type)
  3957. {
  3958. if (mTickLabelType != type)
  3959. {
  3960. mTickLabelType = type;
  3961. mCachedMarginValid = false;
  3962. }
  3963. }
  3964. /*!
  3965. Sets the font of the tick labels.
  3966. \see setTickLabels, setTickLabelColor
  3967. */
  3968. void QCPAxis::setTickLabelFont(const QFont &font)
  3969. {
  3970. if (font != mTickLabelFont)
  3971. {
  3972. mTickLabelFont = font;
  3973. mCachedMarginValid = false;
  3974. }
  3975. }
  3976. /*!
  3977. Sets the color of the tick labels.
  3978. \see setTickLabels, setTickLabelFont
  3979. */
  3980. void QCPAxis::setTickLabelColor(const QColor &color)
  3981. {
  3982. if (color != mTickLabelColor)
  3983. {
  3984. mTickLabelColor = color;
  3985. mCachedMarginValid = false;
  3986. }
  3987. }
  3988. /*!
  3989. Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
  3990. the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
  3991. from -90 to 90 degrees.
  3992. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
  3993. other angles, the label is drawn with an offset such that it seems to point toward or away from
  3994. the tick mark.
  3995. */
  3996. void QCPAxis::setTickLabelRotation(double degrees)
  3997. {
  3998. if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation))
  3999. {
  4000. mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0);
  4001. mCachedMarginValid = false;
  4002. }
  4003. }
  4004. /*!
  4005. Sets the format in which dates and times are displayed as tick labels, if \ref setTickLabelType is \ref ltDateTime.
  4006. for details about the \a format string, see the documentation of QDateTime::toString().
  4007. Newlines can be inserted with "\n".
  4008. \see setDateTimeSpec
  4009. */
  4010. void QCPAxis::setDateTimeFormat(const QString &format)
  4011. {
  4012. if (mDateTimeFormat != format)
  4013. {
  4014. mDateTimeFormat = format;
  4015. mCachedMarginValid = false;
  4016. }
  4017. }
  4018. /*!
  4019. Sets the time spec that is used for the date time values when \ref setTickLabelType is \ref
  4020. ltDateTime.
  4021. The default value of QDateTime objects (and also QCustomPlot) is <tt>Qt::LocalTime</tt>. However,
  4022. if the date time values passed to QCustomPlot are given in the UTC spec, set \a
  4023. timeSpec to <tt>Qt::UTC</tt> to get the correct axis labels.
  4024. \see setDateTimeFormat
  4025. */
  4026. void QCPAxis::setDateTimeSpec(const Qt::TimeSpec &timeSpec)
  4027. {
  4028. mDateTimeSpec = timeSpec;
  4029. }
  4030. /*!
  4031. Sets the number format for the numbers drawn as tick labels (if tick label type is \ref
  4032. ltNumber). This \a formatCode is an extended version of the format code used e.g. by
  4033. QString::number() and QLocale::toString(). For reference about that, see the "Argument Formats"
  4034. section in the detailed description of the QString class. \a formatCode is a string of one, two
  4035. or three characters. The first character is identical to the normal format code used by Qt. In
  4036. short, this means: 'e'/'E' scientific format, 'f' fixed format, 'g'/'G' scientific or fixed,
  4037. whichever is shorter.
  4038. The second and third characters are optional and specific to QCustomPlot:\n
  4039. If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
  4040. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for
  4041. "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
  4042. [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
  4043. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
  4044. be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
  4045. cross and 183 (0xB7) for the dot.
  4046. If the scale type (\ref setScaleType) is \ref stLogarithmic and the \a formatCode uses the 'b'
  4047. option (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10
  4048. [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]"
  4049. part). To only display the decimal power, set the number precision to zero with \ref
  4050. setNumberPrecision.
  4051. Examples for \a formatCode:
  4052. \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
  4053. normal scientific format is used
  4054. \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
  4055. beautifully typeset decimal powers and a dot as multiplication sign
  4056. \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
  4057. multiplication sign
  4058. \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
  4059. powers. Format code will be reduced to 'f'.
  4060. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
  4061. code will not be changed.
  4062. */
  4063. void QCPAxis::setNumberFormat(const QString &formatCode)
  4064. {
  4065. if (formatCode.isEmpty())
  4066. {
  4067. qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
  4068. return;
  4069. }
  4070. mCachedMarginValid = false;
  4071. // interpret first char as number format char:
  4072. QString allowedFormatChars = "eEfgG";
  4073. if (allowedFormatChars.contains(formatCode.at(0)))
  4074. {
  4075. mNumberFormatChar = formatCode.at(0).toLatin1();
  4076. } else
  4077. {
  4078. qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
  4079. return;
  4080. }
  4081. if (formatCode.length() < 2)
  4082. {
  4083. mNumberBeautifulPowers = false;
  4084. mAxisPainter->numberMultiplyCross = false;
  4085. return;
  4086. }
  4087. // interpret second char as indicator for beautiful decimal powers:
  4088. if (formatCode.at(1) == 'b' && (mNumberFormatChar == 'e' || mNumberFormatChar == 'g'))
  4089. {
  4090. mNumberBeautifulPowers = true;
  4091. } else
  4092. {
  4093. qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
  4094. return;
  4095. }
  4096. if (formatCode.length() < 3)
  4097. {
  4098. mAxisPainter->numberMultiplyCross = false;
  4099. return;
  4100. }
  4101. // interpret third char as indicator for dot or cross multiplication symbol:
  4102. if (formatCode.at(2) == 'c')
  4103. {
  4104. mAxisPainter->numberMultiplyCross = true;
  4105. } else if (formatCode.at(2) == 'd')
  4106. {
  4107. mAxisPainter->numberMultiplyCross = false;
  4108. } else
  4109. {
  4110. qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
  4111. return;
  4112. }
  4113. }
  4114. /*!
  4115. Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
  4116. for details. The effect of precisions are most notably for number Formats starting with 'e', see
  4117. \ref setNumberFormat
  4118. If the scale type (\ref setScaleType) is \ref stLogarithmic and the number format (\ref
  4119. setNumberFormat) uses the 'b' format code (beautifully typeset decimal powers), the display
  4120. usually is "1 [multiplication sign] 10 [superscript] n", which looks unnatural for logarithmic
  4121. scaling (the redundant "1 [multiplication sign]" part). To only display the decimal power "10
  4122. [superscript] n", set \a precision to zero.
  4123. */
  4124. void QCPAxis::setNumberPrecision(int precision)
  4125. {
  4126. if (mNumberPrecision != precision)
  4127. {
  4128. mNumberPrecision = precision;
  4129. mCachedMarginValid = false;
  4130. }
  4131. }
  4132. /*!
  4133. If \ref setAutoTickStep is set to false, use this function to set the tick step manually.
  4134. The tick step is the interval between (major) ticks, in plot coordinates.
  4135. \see setSubTickCount
  4136. */
  4137. void QCPAxis::setTickStep(double step)
  4138. {
  4139. if (mTickStep != step)
  4140. {
  4141. mTickStep = step;
  4142. mCachedMarginValid = false;
  4143. }
  4144. }
  4145. /*!
  4146. If you want full control over what ticks (and possibly labels) the axes show, this function is
  4147. used to set the coordinates at which ticks will appear.\ref setAutoTicks must be disabled, else
  4148. the provided tick vector will be overwritten with automatically generated tick coordinates upon
  4149. replot. The labels of the ticks can be generated automatically when \ref setAutoTickLabels is
  4150. left enabled. If it is disabled, you can set the labels manually with \ref setTickVectorLabels.
  4151. \a vec is a vector containing the positions of the ticks, in plot coordinates.
  4152. \warning \a vec must be sorted in ascending order, no additional checks are made to ensure this.
  4153. \see setTickVectorLabels
  4154. */
  4155. void QCPAxis::setTickVector(const QVector<double> &vec)
  4156. {
  4157. // don't check whether mTickVector != vec here, because it takes longer than we would save
  4158. mTickVector = vec;
  4159. mCachedMarginValid = false;
  4160. }
  4161. /*!
  4162. If you want full control over what ticks and labels the axes show, this function is used to set a
  4163. number of QStrings that will be displayed at the tick positions which you need to provide with
  4164. \ref setTickVector. These two vectors should have the same size. (Note that you need to disable
  4165. \ref setAutoTicks and \ref setAutoTickLabels first.)
  4166. \a vec is a vector containing the labels of the ticks. The entries correspond to the respective
  4167. indices in the tick vector, passed via \ref setTickVector.
  4168. \see setTickVector
  4169. */
  4170. void QCPAxis::setTickVectorLabels(const QVector<QString> &vec)
  4171. {
  4172. // don't check whether mTickVectorLabels != vec here, because it takes longer than we would save
  4173. mTickVectorLabels = vec;
  4174. mCachedMarginValid = false;
  4175. }
  4176. /*!
  4177. Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
  4178. plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
  4179. zero, the tick labels and axis label will increase their distance to the axis accordingly, so
  4180. they won't collide with the ticks.
  4181. \see setSubTickLength, setTickLengthIn, setTickLengthOut
  4182. */
  4183. void QCPAxis::setTickLength(int inside, int outside)
  4184. {
  4185. setTickLengthIn(inside);
  4186. setTickLengthOut(outside);
  4187. }
  4188. /*!
  4189. Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
  4190. inside the plot.
  4191. \see setTickLengthOut, setTickLength, setSubTickLength
  4192. */
  4193. void QCPAxis::setTickLengthIn(int inside)
  4194. {
  4195. if (mAxisPainter->tickLengthIn != inside)
  4196. {
  4197. mAxisPainter->tickLengthIn = inside;
  4198. }
  4199. }
  4200. /*!
  4201. Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
  4202. outside the plot. If \a outside is greater than zero, the tick labels and axis label will
  4203. increase their distance to the axis accordingly, so they won't collide with the ticks.
  4204. \see setTickLengthIn, setTickLength, setSubTickLength
  4205. */
  4206. void QCPAxis::setTickLengthOut(int outside)
  4207. {
  4208. if (mAxisPainter->tickLengthOut != outside)
  4209. {
  4210. mAxisPainter->tickLengthOut = outside;
  4211. mCachedMarginValid = false; // only outside tick length can change margin
  4212. }
  4213. }
  4214. /*!
  4215. Sets the number of sub ticks in one (major) tick step. A sub tick count of three for example,
  4216. divides the tick intervals in four sub intervals.
  4217. By default, the number of sub ticks is chosen automatically in a reasonable manner as long as the
  4218. mantissa of the tick step is a multiple of 0.5. When \ref setAutoTickStep is enabled, this is
  4219. always the case.
  4220. If you want to disable automatic sub tick count and use this function to set the count manually,
  4221. see \ref setAutoSubTicks.
  4222. */
  4223. void QCPAxis::setSubTickCount(int count)
  4224. {
  4225. mSubTickCount = count;
  4226. }
  4227. /*!
  4228. Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
  4229. the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
  4230. than zero, the tick labels and axis label will increase their distance to the axis accordingly,
  4231. so they won't collide with the ticks.
  4232. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
  4233. */
  4234. void QCPAxis::setSubTickLength(int inside, int outside)
  4235. {
  4236. setSubTickLengthIn(inside);
  4237. setSubTickLengthOut(outside);
  4238. }
  4239. /*!
  4240. Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
  4241. the plot.
  4242. \see setSubTickLengthOut, setSubTickLength, setTickLength
  4243. */
  4244. void QCPAxis::setSubTickLengthIn(int inside)
  4245. {
  4246. if (mAxisPainter->subTickLengthIn != inside)
  4247. {
  4248. mAxisPainter->subTickLengthIn = inside;
  4249. }
  4250. }
  4251. /*!
  4252. Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
  4253. outside the plot. If \a outside is greater than zero, the tick labels will increase their
  4254. distance to the axis accordingly, so they won't collide with the ticks.
  4255. \see setSubTickLengthIn, setSubTickLength, setTickLength
  4256. */
  4257. void QCPAxis::setSubTickLengthOut(int outside)
  4258. {
  4259. if (mAxisPainter->subTickLengthOut != outside)
  4260. {
  4261. mAxisPainter->subTickLengthOut = outside;
  4262. mCachedMarginValid = false; // only outside tick length can change margin
  4263. }
  4264. }
  4265. /*!
  4266. Sets the pen, the axis base line is drawn with.
  4267. \see setTickPen, setSubTickPen
  4268. */
  4269. void QCPAxis::setBasePen(const QPen &pen)
  4270. {
  4271. mBasePen = pen;
  4272. }
  4273. /*!
  4274. Sets the pen, tick marks will be drawn with.
  4275. \see setTickLength, setBasePen
  4276. */
  4277. void QCPAxis::setTickPen(const QPen &pen)
  4278. {
  4279. mTickPen = pen;
  4280. }
  4281. /*!
  4282. Sets the pen, subtick marks will be drawn with.
  4283. \see setSubTickCount, setSubTickLength, setBasePen
  4284. */
  4285. void QCPAxis::setSubTickPen(const QPen &pen)
  4286. {
  4287. mSubTickPen = pen;
  4288. }
  4289. /*!
  4290. Sets the font of the axis label.
  4291. \see setLabelColor
  4292. */
  4293. void QCPAxis::setLabelFont(const QFont &font)
  4294. {
  4295. if (mLabelFont != font)
  4296. {
  4297. mLabelFont = font;
  4298. mCachedMarginValid = false;
  4299. }
  4300. }
  4301. /*!
  4302. Sets the color of the axis label.
  4303. \see setLabelFont
  4304. */
  4305. void QCPAxis::setLabelColor(const QColor &color)
  4306. {
  4307. mLabelColor = color;
  4308. }
  4309. /*!
  4310. Sets the text of the axis label that will be shown below/above or next to the axis, depending on
  4311. its orientation. To disable axis labels, pass an empty string as \a str.
  4312. */
  4313. void QCPAxis::setLabel(const QString &str)
  4314. {
  4315. if (mLabel != str)
  4316. {
  4317. mLabel = str;
  4318. mCachedMarginValid = false;
  4319. }
  4320. }
  4321. /*!
  4322. Sets the distance between the tick labels and the axis label.
  4323. \see setTickLabelPadding, setPadding
  4324. */
  4325. void QCPAxis::setLabelPadding(int padding)
  4326. {
  4327. if (mAxisPainter->labelPadding != padding)
  4328. {
  4329. mAxisPainter->labelPadding = padding;
  4330. mCachedMarginValid = false;
  4331. }
  4332. }
  4333. /*!
  4334. Sets the padding of the axis.
  4335. When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space,
  4336. that is left blank.
  4337. The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled.
  4338. \see setLabelPadding, setTickLabelPadding
  4339. */
  4340. void QCPAxis::setPadding(int padding)
  4341. {
  4342. if (mPadding != padding)
  4343. {
  4344. mPadding = padding;
  4345. mCachedMarginValid = false;
  4346. }
  4347. }
  4348. /*!
  4349. Sets the offset the axis has to its axis rect side.
  4350. If an axis rect side has multiple axes and automatic margin calculation is enabled for that side,
  4351. only the offset of the inner most axis has meaning (even if it is set to be invisible). The
  4352. offset of the other, outer axes is controlled automatically, to place them at appropriate
  4353. positions.
  4354. */
  4355. void QCPAxis::setOffset(int offset)
  4356. {
  4357. mAxisPainter->offset = offset;
  4358. }
  4359. /*!
  4360. Sets the font that is used for tick labels when they are selected.
  4361. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4362. */
  4363. void QCPAxis::setSelectedTickLabelFont(const QFont &font)
  4364. {
  4365. if (font != mSelectedTickLabelFont)
  4366. {
  4367. mSelectedTickLabelFont = font;
  4368. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  4369. }
  4370. }
  4371. /*!
  4372. Sets the font that is used for the axis label when it is selected.
  4373. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4374. */
  4375. void QCPAxis::setSelectedLabelFont(const QFont &font)
  4376. {
  4377. mSelectedLabelFont = font;
  4378. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  4379. }
  4380. /*!
  4381. Sets the color that is used for tick labels when they are selected.
  4382. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4383. */
  4384. void QCPAxis::setSelectedTickLabelColor(const QColor &color)
  4385. {
  4386. if (color != mSelectedTickLabelColor)
  4387. {
  4388. mSelectedTickLabelColor = color;
  4389. }
  4390. }
  4391. /*!
  4392. Sets the color that is used for the axis label when it is selected.
  4393. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4394. */
  4395. void QCPAxis::setSelectedLabelColor(const QColor &color)
  4396. {
  4397. mSelectedLabelColor = color;
  4398. }
  4399. /*!
  4400. Sets the pen that is used to draw the axis base line when selected.
  4401. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4402. */
  4403. void QCPAxis::setSelectedBasePen(const QPen &pen)
  4404. {
  4405. mSelectedBasePen = pen;
  4406. }
  4407. /*!
  4408. Sets the pen that is used to draw the (major) ticks when selected.
  4409. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4410. */
  4411. void QCPAxis::setSelectedTickPen(const QPen &pen)
  4412. {
  4413. mSelectedTickPen = pen;
  4414. }
  4415. /*!
  4416. Sets the pen that is used to draw the subticks when selected.
  4417. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4418. */
  4419. void QCPAxis::setSelectedSubTickPen(const QPen &pen)
  4420. {
  4421. mSelectedSubTickPen = pen;
  4422. }
  4423. /*!
  4424. Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available
  4425. styles.
  4426. For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending.
  4427. Note that this meaning does not change when the axis range is reversed with \ref
  4428. setRangeReversed.
  4429. \see setUpperEnding
  4430. */
  4431. void QCPAxis::setLowerEnding(const QCPLineEnding &ending)
  4432. {
  4433. mAxisPainter->lowerEnding = ending;
  4434. }
  4435. /*!
  4436. Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available
  4437. styles.
  4438. For horizontal axes, this method refers to the right ending, for vertical axes the top ending.
  4439. Note that this meaning does not change when the axis range is reversed with \ref
  4440. setRangeReversed.
  4441. \see setLowerEnding
  4442. */
  4443. void QCPAxis::setUpperEnding(const QCPLineEnding &ending)
  4444. {
  4445. mAxisPainter->upperEnding = ending;
  4446. }
  4447. /*!
  4448. If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
  4449. bounds of the range. The range is simply moved by \a diff.
  4450. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
  4451. corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
  4452. */
  4453. void QCPAxis::moveRange(double diff)
  4454. {
  4455. QCPRange oldRange = mRange;
  4456. if (mScaleType == stLinear)
  4457. {
  4458. mRange.lower += diff;
  4459. mRange.upper += diff;
  4460. } else // mScaleType == stLogarithmic
  4461. {
  4462. mRange.lower *= diff;
  4463. mRange.upper *= diff;
  4464. }
  4465. mCachedMarginValid = false;
  4466. emit rangeChanged(mRange);
  4467. emit rangeChanged(mRange, oldRange);
  4468. }
  4469. /*!
  4470. Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
  4471. factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
  4472. coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
  4473. around 1.0 will have moved symmetrically closer to 1.0).
  4474. */
  4475. void QCPAxis::scaleRange(double factor, double center)
  4476. {
  4477. QCPRange oldRange = mRange;
  4478. if (mScaleType == stLinear)
  4479. {
  4480. QCPRange newRange;
  4481. newRange.lower = (mRange.lower-center)*factor + center;
  4482. newRange.upper = (mRange.upper-center)*factor + center;
  4483. if (QCPRange::validRange(newRange))
  4484. mRange = newRange.sanitizedForLinScale();
  4485. } else // mScaleType == stLogarithmic
  4486. {
  4487. if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range
  4488. {
  4489. QCPRange newRange;
  4490. newRange.lower = pow(mRange.lower/center, factor)*center;
  4491. newRange.upper = pow(mRange.upper/center, factor)*center;
  4492. if (QCPRange::validRange(newRange))
  4493. mRange = newRange.sanitizedForLogScale();
  4494. } else
  4495. qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center;
  4496. }
  4497. mCachedMarginValid = false;
  4498. emit rangeChanged(mRange);
  4499. emit rangeChanged(mRange, oldRange);
  4500. }
  4501. /*!
  4502. Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will
  4503. be done around the center of the current axis range.
  4504. For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs
  4505. plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the
  4506. axis rect has.
  4507. This is an operation that changes the range of this axis once, it doesn't fix the scale ratio
  4508. indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent
  4509. won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent
  4510. will follow.
  4511. */
  4512. void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio)
  4513. {
  4514. int otherPixelSize, ownPixelSize;
  4515. if (otherAxis->orientation() == Qt::Horizontal)
  4516. otherPixelSize = otherAxis->axisRect()->width();
  4517. else
  4518. otherPixelSize = otherAxis->axisRect()->height();
  4519. if (orientation() == Qt::Horizontal)
  4520. ownPixelSize = axisRect()->width();
  4521. else
  4522. ownPixelSize = axisRect()->height();
  4523. double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/(double)otherPixelSize;
  4524. setRange(range().center(), newRangeSize, Qt::AlignCenter);
  4525. }
  4526. /*!
  4527. Changes the axis range such that all plottables associated with this axis are fully visible in
  4528. that dimension.
  4529. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
  4530. */
  4531. void QCPAxis::rescale(bool onlyVisiblePlottables)
  4532. {
  4533. QList<QCPAbstractPlottable*> p = plottables();
  4534. QCPRange newRange;
  4535. bool haveRange = false;
  4536. for (int i=0; i<p.size(); ++i)
  4537. {
  4538. if (!p.at(i)->realVisibility() && onlyVisiblePlottables)
  4539. continue;
  4540. QCPRange plottableRange;
  4541. bool currentFoundRange;
  4542. QCPAbstractPlottable::SignDomain signDomain = QCPAbstractPlottable::sdBoth;
  4543. if (mScaleType == stLogarithmic)
  4544. signDomain = (mRange.upper < 0 ? QCPAbstractPlottable::sdNegative : QCPAbstractPlottable::sdPositive);
  4545. if (p.at(i)->keyAxis() == this)
  4546. plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain);
  4547. else
  4548. plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain);
  4549. if (currentFoundRange)
  4550. {
  4551. if (!haveRange)
  4552. newRange = plottableRange;
  4553. else
  4554. newRange.expand(plottableRange);
  4555. haveRange = true;
  4556. }
  4557. }
  4558. if (haveRange)
  4559. {
  4560. 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
  4561. {
  4562. 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
  4563. if (mScaleType == stLinear)
  4564. {
  4565. newRange.lower = center-mRange.size()/2.0;
  4566. newRange.upper = center+mRange.size()/2.0;
  4567. } else // mScaleType == stLogarithmic
  4568. {
  4569. newRange.lower = center/qSqrt(mRange.upper/mRange.lower);
  4570. newRange.upper = center*qSqrt(mRange.upper/mRange.lower);
  4571. }
  4572. }
  4573. setRange(newRange);
  4574. }
  4575. }
  4576. /*!
  4577. Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
  4578. */
  4579. double QCPAxis::pixelToCoord(double value) const
  4580. {
  4581. if (orientation() == Qt::Horizontal)
  4582. {
  4583. if (mScaleType == stLinear)
  4584. {
  4585. if (!mRangeReversed)
  4586. return (value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.lower;
  4587. else
  4588. return -(value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.upper;
  4589. } else // mScaleType == stLogarithmic
  4590. {
  4591. if (!mRangeReversed)
  4592. return pow(mRange.upper/mRange.lower, (value-mAxisRect->left())/(double)mAxisRect->width())*mRange.lower;
  4593. else
  4594. return pow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/(double)mAxisRect->width())*mRange.upper;
  4595. }
  4596. } else // orientation() == Qt::Vertical
  4597. {
  4598. if (mScaleType == stLinear)
  4599. {
  4600. if (!mRangeReversed)
  4601. return (mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.lower;
  4602. else
  4603. return -(mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.upper;
  4604. } else // mScaleType == stLogarithmic
  4605. {
  4606. if (!mRangeReversed)
  4607. return pow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/(double)mAxisRect->height())*mRange.lower;
  4608. else
  4609. return pow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/(double)mAxisRect->height())*mRange.upper;
  4610. }
  4611. }
  4612. }
  4613. /*!
  4614. Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
  4615. */
  4616. double QCPAxis::coordToPixel(double value) const
  4617. {
  4618. if (orientation() == Qt::Horizontal)
  4619. {
  4620. if (mScaleType == stLinear)
  4621. {
  4622. if (!mRangeReversed)
  4623. return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left();
  4624. else
  4625. return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left();
  4626. } else // mScaleType == stLogarithmic
  4627. {
  4628. if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range
  4629. return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200;
  4630. else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range
  4631. return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200;
  4632. else
  4633. {
  4634. if (!mRangeReversed)
  4635. return baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
  4636. else
  4637. return baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
  4638. }
  4639. }
  4640. } else // orientation() == Qt::Vertical
  4641. {
  4642. if (mScaleType == stLinear)
  4643. {
  4644. if (!mRangeReversed)
  4645. return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height();
  4646. else
  4647. return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height();
  4648. } else // mScaleType == stLogarithmic
  4649. {
  4650. if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range
  4651. return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200;
  4652. else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range
  4653. return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200;
  4654. else
  4655. {
  4656. if (!mRangeReversed)
  4657. return mAxisRect->bottom()-baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height();
  4658. else
  4659. return mAxisRect->bottom()-baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height();
  4660. }
  4661. }
  4662. }
  4663. }
  4664. /*!
  4665. Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
  4666. is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
  4667. function does not change the current selection state of the axis.
  4668. If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
  4669. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
  4670. */
  4671. QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const
  4672. {
  4673. if (!mVisible)
  4674. return spNone;
  4675. if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
  4676. return spAxis;
  4677. else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
  4678. return spTickLabels;
  4679. else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
  4680. return spAxisLabel;
  4681. else
  4682. return spNone;
  4683. }
  4684. /* inherits documentation from base class */
  4685. double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  4686. {
  4687. if (!mParentPlot) return -1;
  4688. SelectablePart part = getPartAt(pos);
  4689. if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
  4690. return -1;
  4691. if (details)
  4692. details->setValue(part);
  4693. return mParentPlot->selectionTolerance()*0.99;
  4694. }
  4695. /*!
  4696. Returns a list of all the plottables that have this axis as key or value axis.
  4697. If you are only interested in plottables of type QCPGraph, see \ref graphs.
  4698. \see graphs, items
  4699. */
  4700. QList<QCPAbstractPlottable*> QCPAxis::plottables() const
  4701. {
  4702. QList<QCPAbstractPlottable*> result;
  4703. if (!mParentPlot) return result;
  4704. for (int i=0; i<mParentPlot->mPlottables.size(); ++i)
  4705. {
  4706. if (mParentPlot->mPlottables.at(i)->keyAxis() == this ||mParentPlot->mPlottables.at(i)->valueAxis() == this)
  4707. result.append(mParentPlot->mPlottables.at(i));
  4708. }
  4709. return result;
  4710. }
  4711. /*!
  4712. Returns a list of all the graphs that have this axis as key or value axis.
  4713. \see plottables, items
  4714. */
  4715. QList<QCPGraph*> QCPAxis::graphs() const
  4716. {
  4717. QList<QCPGraph*> result;
  4718. if (!mParentPlot) return result;
  4719. for (int i=0; i<mParentPlot->mGraphs.size(); ++i)
  4720. {
  4721. if (mParentPlot->mGraphs.at(i)->keyAxis() == this || mParentPlot->mGraphs.at(i)->valueAxis() == this)
  4722. result.append(mParentPlot->mGraphs.at(i));
  4723. }
  4724. return result;
  4725. }
  4726. /*!
  4727. Returns a list of all the items that are associated with this axis. An item is considered
  4728. associated with an axis if at least one of its positions uses the axis as key or value axis.
  4729. \see plottables, graphs
  4730. */
  4731. QList<QCPAbstractItem*> QCPAxis::items() const
  4732. {
  4733. QList<QCPAbstractItem*> result;
  4734. if (!mParentPlot) return result;
  4735. for (int itemId=0; itemId<mParentPlot->mItems.size(); ++itemId)
  4736. {
  4737. QList<QCPItemPosition*> positions = mParentPlot->mItems.at(itemId)->positions();
  4738. for (int posId=0; posId<positions.size(); ++posId)
  4739. {
  4740. if (positions.at(posId)->keyAxis() == this || positions.at(posId)->valueAxis() == this)
  4741. {
  4742. result.append(mParentPlot->mItems.at(itemId));
  4743. break;
  4744. }
  4745. }
  4746. }
  4747. return result;
  4748. }
  4749. /*!
  4750. Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to
  4751. QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.)
  4752. */
  4753. QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side)
  4754. {
  4755. switch (side)
  4756. {
  4757. case QCP::msLeft: return atLeft;
  4758. case QCP::msRight: return atRight;
  4759. case QCP::msTop: return atTop;
  4760. case QCP::msBottom: return atBottom;
  4761. default: break;
  4762. }
  4763. qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << (int)side;
  4764. return atLeft;
  4765. }
  4766. /*!
  4767. Returns the axis type that describes the opposite axis of an axis with the specified \a type.
  4768. */
  4769. QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type)
  4770. {
  4771. switch (type)
  4772. {
  4773. case atLeft: return atRight; break;
  4774. case atRight: return atLeft; break;
  4775. case atBottom: return atTop; break;
  4776. case atTop: return atBottom; break;
  4777. default: qDebug() << Q_FUNC_INFO << "invalid axis type"; return atLeft; break;
  4778. }
  4779. }
  4780. /*! \internal
  4781. This function is called to prepare the tick vector, sub tick vector and tick label vector. If
  4782. \ref setAutoTicks is set to true, appropriate tick values are determined automatically via \ref
  4783. generateAutoTicks. If it's set to false, the signal ticksRequest is emitted, which can be used to
  4784. provide external tick positions. Then the sub tick vectors and tick label vectors are created.
  4785. */
  4786. void QCPAxis::setupTickVectors()
  4787. {
  4788. if (!mParentPlot) return;
  4789. if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
  4790. // fill tick vectors, either by auto generating or by notifying user to fill the vectors himself
  4791. if (mAutoTicks)
  4792. {
  4793. generateAutoTicks();
  4794. } else
  4795. {
  4796. emit ticksRequest();
  4797. }
  4798. visibleTickBounds(mLowestVisibleTick, mHighestVisibleTick);
  4799. if (mTickVector.isEmpty())
  4800. {
  4801. mSubTickVector.clear();
  4802. return;
  4803. }
  4804. // generate subticks between ticks:
  4805. mSubTickVector.resize((mTickVector.size()-1)*mSubTickCount);
  4806. if (mSubTickCount > 0)
  4807. {
  4808. double subTickStep = 0;
  4809. double subTickPosition = 0;
  4810. int subTickIndex = 0;
  4811. bool done = false;
  4812. int lowTick = mLowestVisibleTick > 0 ? mLowestVisibleTick-1 : mLowestVisibleTick;
  4813. int highTick = mHighestVisibleTick < mTickVector.size()-1 ? mHighestVisibleTick+1 : mHighestVisibleTick;
  4814. for (int i=lowTick+1; i<=highTick; ++i)
  4815. {
  4816. subTickStep = (mTickVector.at(i)-mTickVector.at(i-1))/(double)(mSubTickCount+1);
  4817. for (int k=1; k<=mSubTickCount; ++k)
  4818. {
  4819. subTickPosition = mTickVector.at(i-1) + k*subTickStep;
  4820. if (subTickPosition < mRange.lower)
  4821. continue;
  4822. if (subTickPosition > mRange.upper)
  4823. {
  4824. done = true;
  4825. break;
  4826. }
  4827. mSubTickVector[subTickIndex] = subTickPosition;
  4828. subTickIndex++;
  4829. }
  4830. if (done) break;
  4831. }
  4832. mSubTickVector.resize(subTickIndex);
  4833. }
  4834. // generate tick labels according to tick positions:
  4835. if (mAutoTickLabels)
  4836. {
  4837. int vecsize = mTickVector.size();
  4838. mTickVectorLabels.resize(vecsize);
  4839. if (mTickLabelType == ltNumber)
  4840. {
  4841. for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i)
  4842. mTickVectorLabels[i] = mParentPlot->locale().toString(mTickVector.at(i), mNumberFormatChar, mNumberPrecision);
  4843. } else if (mTickLabelType == ltDateTime)
  4844. {
  4845. for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i)
  4846. {
  4847. #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")
  4848. mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromTime_t(mTickVector.at(i)).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
  4849. #else
  4850. mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromMSecsSinceEpoch(mTickVector.at(i)*1000).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
  4851. #endif
  4852. }
  4853. }
  4854. } else // mAutoTickLabels == false
  4855. {
  4856. if (mAutoTicks) // ticks generated automatically, but not ticklabels, so emit ticksRequest here for labels
  4857. {
  4858. emit ticksRequest();
  4859. }
  4860. // make sure provided tick label vector has correct (minimal) length:
  4861. if (mTickVectorLabels.size() < mTickVector.size())
  4862. mTickVectorLabels.resize(mTickVector.size());
  4863. }
  4864. }
  4865. /*! \internal
  4866. If \ref setAutoTicks is set to true, this function is called by \ref setupTickVectors to
  4867. generate reasonable tick positions (and subtick count). The algorithm tries to create
  4868. approximately <tt>mAutoTickCount</tt> ticks (set via \ref setAutoTickCount).
  4869. If the scale is logarithmic, \ref setAutoTickCount is ignored, and one tick is generated at every
  4870. power of the current logarithm base, set via \ref setScaleLogBase.
  4871. */
  4872. void QCPAxis::generateAutoTicks()
  4873. {
  4874. if (mScaleType == stLinear)
  4875. {
  4876. if (mAutoTickStep)
  4877. {
  4878. // Generate tick positions according to linear scaling:
  4879. mTickStep = mRange.size()/(double)(mAutoTickCount+1e-10); // mAutoTickCount ticks on average, the small addition is to prevent jitter on exact integers
  4880. double magnitudeFactor = qPow(10.0, qFloor(qLn(mTickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc.
  4881. double tickStepMantissa = mTickStep/magnitudeFactor;
  4882. if (tickStepMantissa < 5)
  4883. {
  4884. // round digit after decimal point to 0.5
  4885. mTickStep = (int)(tickStepMantissa*2)/2.0*magnitudeFactor;
  4886. } else
  4887. {
  4888. // round to first digit in multiples of 2
  4889. mTickStep = (int)(tickStepMantissa/2.0)*2.0*magnitudeFactor;
  4890. }
  4891. }
  4892. if (mAutoSubTicks)
  4893. mSubTickCount = calculateAutoSubTickCount(mTickStep);
  4894. // Generate tick positions according to mTickStep:
  4895. qint64 firstStep = floor(mRange.lower/mTickStep);
  4896. qint64 lastStep = ceil(mRange.upper/mTickStep);
  4897. int tickcount = lastStep-firstStep+1;
  4898. if (tickcount < 0) tickcount = 0;
  4899. mTickVector.resize(tickcount);
  4900. for (int i=0; i<tickcount; ++i)
  4901. mTickVector[i] = (firstStep+i)*mTickStep;
  4902. } else // mScaleType == stLogarithmic
  4903. {
  4904. // Generate tick positions according to logbase scaling:
  4905. if (mRange.lower > 0 && mRange.upper > 0) // positive range
  4906. {
  4907. double lowerMag = basePow((int)floor(baseLog(mRange.lower)));
  4908. double currentMag = lowerMag;
  4909. mTickVector.clear();
  4910. mTickVector.append(currentMag);
  4911. while (currentMag < mRange.upper && currentMag > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
  4912. {
  4913. currentMag *= mScaleLogBase;
  4914. mTickVector.append(currentMag);
  4915. }
  4916. } else if (mRange.lower < 0 && mRange.upper < 0) // negative range
  4917. {
  4918. double lowerMag = -basePow((int)ceil(baseLog(-mRange.lower)));
  4919. double currentMag = lowerMag;
  4920. mTickVector.clear();
  4921. mTickVector.append(currentMag);
  4922. while (currentMag < mRange.upper && currentMag < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
  4923. {
  4924. currentMag /= mScaleLogBase;
  4925. mTickVector.append(currentMag);
  4926. }
  4927. } else // invalid range for logarithmic scale, because lower and upper have different sign
  4928. {
  4929. mTickVector.clear();
  4930. qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << mRange.lower << "-" << mRange.upper;
  4931. }
  4932. }
  4933. }
  4934. /*! \internal
  4935. Called by generateAutoTicks when \ref setAutoSubTicks is set to true. Depending on the \a
  4936. tickStep between two major ticks on the axis, a different number of sub ticks is appropriate. For
  4937. Example taking 4 sub ticks for a \a tickStep of 1 makes more sense than taking 5 sub ticks,
  4938. because this corresponds to a sub tick step of 0.2, instead of the less intuitive 0.16667. Note
  4939. that a subtick count of 4 means dividing the major tick step into 5 sections.
  4940. This is implemented by a hand made lookup for integer tick steps as well as fractional tick steps
  4941. with a fractional part of (approximately) 0.5. If a tick step is different (i.e. has no
  4942. fractional part close to 0.5), the currently set sub tick count (\ref setSubTickCount) is
  4943. returned.
  4944. */
  4945. int QCPAxis::calculateAutoSubTickCount(double tickStep) const
  4946. {
  4947. int result = mSubTickCount; // default to current setting, if no proper value can be found
  4948. // get mantissa of tickstep:
  4949. double magnitudeFactor = qPow(10.0, qFloor(qLn(tickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc.
  4950. double tickStepMantissa = tickStep/magnitudeFactor;
  4951. // separate integer and fractional part of mantissa:
  4952. double epsilon = 0.01;
  4953. double intPartf;
  4954. int intPart;
  4955. double fracPart = modf(tickStepMantissa, &intPartf);
  4956. intPart = intPartf;
  4957. // handle cases with (almost) integer mantissa:
  4958. if (fracPart < epsilon || 1.0-fracPart < epsilon)
  4959. {
  4960. if (1.0-fracPart < epsilon)
  4961. ++intPart;
  4962. switch (intPart)
  4963. {
  4964. case 1: result = 4; break; // 1.0 -> 0.2 substep
  4965. case 2: result = 3; break; // 2.0 -> 0.5 substep
  4966. case 3: result = 2; break; // 3.0 -> 1.0 substep
  4967. case 4: result = 3; break; // 4.0 -> 1.0 substep
  4968. case 5: result = 4; break; // 5.0 -> 1.0 substep
  4969. case 6: result = 2; break; // 6.0 -> 2.0 substep
  4970. case 7: result = 6; break; // 7.0 -> 1.0 substep
  4971. case 8: result = 3; break; // 8.0 -> 2.0 substep
  4972. case 9: result = 2; break; // 9.0 -> 3.0 substep
  4973. }
  4974. } else
  4975. {
  4976. // handle cases with significantly fractional mantissa:
  4977. if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa
  4978. {
  4979. switch (intPart)
  4980. {
  4981. case 1: result = 2; break; // 1.5 -> 0.5 substep
  4982. case 2: result = 4; break; // 2.5 -> 0.5 substep
  4983. case 3: result = 4; break; // 3.5 -> 0.7 substep
  4984. case 4: result = 2; break; // 4.5 -> 1.5 substep
  4985. case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with autoTickStep from here on)
  4986. case 6: result = 4; break; // 6.5 -> 1.3 substep
  4987. case 7: result = 2; break; // 7.5 -> 2.5 substep
  4988. case 8: result = 4; break; // 8.5 -> 1.7 substep
  4989. case 9: result = 4; break; // 9.5 -> 1.9 substep
  4990. }
  4991. }
  4992. // if mantissa fraction isnt 0.0 or 0.5, don't bother finding good sub tick marks, leave default
  4993. }
  4994. return result;
  4995. }
  4996. /* inherits documentation from base class */
  4997. void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  4998. {
  4999. Q_UNUSED(event)
  5000. SelectablePart part = details.value<SelectablePart>();
  5001. if (mSelectableParts.testFlag(part))
  5002. {
  5003. SelectableParts selBefore = mSelectedParts;
  5004. setSelectedParts(additive ? mSelectedParts^part : part);
  5005. if (selectionStateChanged)
  5006. *selectionStateChanged = mSelectedParts != selBefore;
  5007. }
  5008. }
  5009. /* inherits documentation from base class */
  5010. void QCPAxis::deselectEvent(bool *selectionStateChanged)
  5011. {
  5012. SelectableParts selBefore = mSelectedParts;
  5013. setSelectedParts(mSelectedParts & ~mSelectableParts);
  5014. if (selectionStateChanged)
  5015. *selectionStateChanged = mSelectedParts != selBefore;
  5016. }
  5017. /*! \internal
  5018. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  5019. before drawing axis lines.
  5020. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  5021. This function takes into account the local setting of the antialiasing flag as well as the
  5022. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  5023. QCustomPlot::setNotAntialiasedElements.
  5024. \see setAntialiased
  5025. */
  5026. void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const
  5027. {
  5028. applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
  5029. }
  5030. /*! \internal
  5031. Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance.
  5032. */
  5033. void QCPAxis::draw(QCPPainter *painter)
  5034. {
  5035. const int lowTick = mLowestVisibleTick;
  5036. const int highTick = mHighestVisibleTick;
  5037. QVector<double> subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  5038. QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  5039. QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
  5040. tickPositions.reserve(highTick-lowTick+1);
  5041. tickLabels.reserve(highTick-lowTick+1);
  5042. subTickPositions.reserve(mSubTickVector.size());
  5043. if (mTicks)
  5044. {
  5045. for (int i=lowTick; i<=highTick; ++i)
  5046. {
  5047. tickPositions.append(coordToPixel(mTickVector.at(i)));
  5048. if (mTickLabels)
  5049. tickLabels.append(mTickVectorLabels.at(i));
  5050. }
  5051. if (mSubTickCount > 0)
  5052. {
  5053. const int subTickCount = mSubTickVector.size();
  5054. for (int i=0; i<subTickCount; ++i) // no need to check bounds because subticks are always only created inside current mRange
  5055. subTickPositions.append(coordToPixel(mSubTickVector.at(i)));
  5056. }
  5057. }
  5058. // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to draw the axis.
  5059. // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
  5060. mAxisPainter->type = mAxisType;
  5061. mAxisPainter->basePen = getBasePen();
  5062. mAxisPainter->labelFont = getLabelFont();
  5063. mAxisPainter->labelColor = getLabelColor();
  5064. mAxisPainter->label = mLabel;
  5065. mAxisPainter->substituteExponent = mAutoTickLabels && mNumberBeautifulPowers && mTickLabelType == ltNumber;
  5066. mAxisPainter->tickPen = getTickPen();
  5067. mAxisPainter->subTickPen = getSubTickPen();
  5068. mAxisPainter->tickLabelFont = getTickLabelFont();
  5069. mAxisPainter->tickLabelColor = getTickLabelColor();
  5070. mAxisPainter->alignmentRect = mAxisRect->rect();
  5071. mAxisPainter->viewportRect = mParentPlot->viewport();
  5072. mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic;
  5073. mAxisPainter->reversedEndings = mRangeReversed;
  5074. mAxisPainter->tickPositions = tickPositions;
  5075. mAxisPainter->tickLabels = tickLabels;
  5076. mAxisPainter->subTickPositions = subTickPositions;
  5077. mAxisPainter->draw(painter);
  5078. }
  5079. /*! \internal
  5080. Returns via \a lowIndex and \a highIndex, which ticks in the current tick vector are visible in
  5081. the current range. The return values are indices of the tick vector, not the positions of the
  5082. ticks themselves.
  5083. The actual use of this function is when an external tick vector is provided, since it might
  5084. exceed far beyond the currently displayed range, and would cause unnecessary calculations e.g. of
  5085. subticks.
  5086. If all ticks are outside the axis range, an inverted range is returned, i.e. highIndex will be
  5087. smaller than lowIndex. There is one case, where this function returns indices that are not really
  5088. visible in the current axis range: When the tick spacing is larger than the axis range size and
  5089. one tick is below the axis range and the next tick is already above the axis range. Because in
  5090. such cases it is usually desirable to know the tick pair, to draw proper subticks.
  5091. */
  5092. void QCPAxis::visibleTickBounds(int &lowIndex, int &highIndex) const
  5093. {
  5094. bool lowFound = false;
  5095. bool highFound = false;
  5096. lowIndex = 0;
  5097. highIndex = -1;
  5098. for (int i=0; i < mTickVector.size(); ++i)
  5099. {
  5100. if (mTickVector.at(i) >= mRange.lower)
  5101. {
  5102. lowFound = true;
  5103. lowIndex = i;
  5104. break;
  5105. }
  5106. }
  5107. for (int i=mTickVector.size()-1; i >= 0; --i)
  5108. {
  5109. if (mTickVector.at(i) <= mRange.upper)
  5110. {
  5111. highFound = true;
  5112. highIndex = i;
  5113. break;
  5114. }
  5115. }
  5116. if (!lowFound && highFound)
  5117. lowIndex = highIndex+1;
  5118. else if (lowFound && !highFound)
  5119. highIndex = lowIndex-1;
  5120. }
  5121. /*! \internal
  5122. A log function with the base mScaleLogBase, used mostly for coordinate transforms in logarithmic
  5123. scales with arbitrary log base. Uses the buffered mScaleLogBaseLogInv for faster calculation.
  5124. This is set to <tt>1.0/qLn(mScaleLogBase)</tt> in \ref setScaleLogBase.
  5125. \see basePow, setScaleLogBase, setScaleType
  5126. */
  5127. double QCPAxis::baseLog(double value) const
  5128. {
  5129. return qLn(value)*mScaleLogBaseLogInv;
  5130. }
  5131. /*! \internal
  5132. A power function with the base mScaleLogBase, used mostly for coordinate transforms in
  5133. logarithmic scales with arbitrary log base.
  5134. \see baseLog, setScaleLogBase, setScaleType
  5135. */
  5136. double QCPAxis::basePow(double value) const
  5137. {
  5138. return qPow(mScaleLogBase, value);
  5139. }
  5140. /*! \internal
  5141. Returns the pen that is used to draw the axis base line. Depending on the selection state, this
  5142. is either mSelectedBasePen or mBasePen.
  5143. */
  5144. QPen QCPAxis::getBasePen() const
  5145. {
  5146. return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
  5147. }
  5148. /*! \internal
  5149. Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
  5150. is either mSelectedTickPen or mTickPen.
  5151. */
  5152. QPen QCPAxis::getTickPen() const
  5153. {
  5154. return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
  5155. }
  5156. /*! \internal
  5157. Returns the pen that is used to draw the subticks. Depending on the selection state, this
  5158. is either mSelectedSubTickPen or mSubTickPen.
  5159. */
  5160. QPen QCPAxis::getSubTickPen() const
  5161. {
  5162. return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
  5163. }
  5164. /*! \internal
  5165. Returns the font that is used to draw the tick labels. Depending on the selection state, this
  5166. is either mSelectedTickLabelFont or mTickLabelFont.
  5167. */
  5168. QFont QCPAxis::getTickLabelFont() const
  5169. {
  5170. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
  5171. }
  5172. /*! \internal
  5173. Returns the font that is used to draw the axis label. Depending on the selection state, this
  5174. is either mSelectedLabelFont or mLabelFont.
  5175. */
  5176. QFont QCPAxis::getLabelFont() const
  5177. {
  5178. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
  5179. }
  5180. /*! \internal
  5181. Returns the color that is used to draw the tick labels. Depending on the selection state, this
  5182. is either mSelectedTickLabelColor or mTickLabelColor.
  5183. */
  5184. QColor QCPAxis::getTickLabelColor() const
  5185. {
  5186. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
  5187. }
  5188. /*! \internal
  5189. Returns the color that is used to draw the axis label. Depending on the selection state, this
  5190. is either mSelectedLabelColor or mLabelColor.
  5191. */
  5192. QColor QCPAxis::getLabelColor() const
  5193. {
  5194. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
  5195. }
  5196. /*! \internal
  5197. Returns the appropriate outward margin for this axis. It is needed if \ref
  5198. QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref
  5199. atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom
  5200. margin and so forth. For the calculation, this function goes through similar steps as \ref draw,
  5201. so changing one function likely requires the modification of the other one as well.
  5202. The margin consists of the outward tick length, tick label padding, tick label size, label
  5203. padding, label size, and padding.
  5204. The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc.
  5205. unchanged are very fast.
  5206. */
  5207. int QCPAxis::calculateMargin()
  5208. {
  5209. if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis
  5210. return 0;
  5211. if (mCachedMarginValid)
  5212. return mCachedMargin;
  5213. // run through similar steps as QCPAxis::draw, and caluclate margin needed to fit axis and its labels
  5214. int margin = 0;
  5215. int lowTick, highTick;
  5216. visibleTickBounds(lowTick, highTick);
  5217. QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  5218. QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
  5219. tickPositions.reserve(highTick-lowTick+1);
  5220. tickLabels.reserve(highTick-lowTick+1);
  5221. if (mTicks)
  5222. {
  5223. for (int i=lowTick; i<=highTick; ++i)
  5224. {
  5225. tickPositions.append(coordToPixel(mTickVector.at(i)));
  5226. if (mTickLabels)
  5227. tickLabels.append(mTickVectorLabels.at(i));
  5228. }
  5229. }
  5230. // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size.
  5231. // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
  5232. mAxisPainter->type = mAxisType;
  5233. mAxisPainter->labelFont = getLabelFont();
  5234. mAxisPainter->label = mLabel;
  5235. mAxisPainter->tickLabelFont = mTickLabelFont;
  5236. mAxisPainter->alignmentRect = mAxisRect->rect();
  5237. mAxisPainter->viewportRect = mParentPlot->viewport();
  5238. mAxisPainter->tickPositions = tickPositions;
  5239. mAxisPainter->tickLabels = tickLabels;
  5240. margin += mAxisPainter->size();
  5241. margin += mPadding;
  5242. mCachedMargin = margin;
  5243. mCachedMarginValid = true;
  5244. return margin;
  5245. }
  5246. /* inherits documentation from base class */
  5247. QCP::Interaction QCPAxis::selectionCategory() const
  5248. {
  5249. return QCP::iSelectAxes;
  5250. }
  5251. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5252. //////////////////// QCPAxisPainterPrivate
  5253. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5254. /*! \class QCPAxisPainterPrivate
  5255. \internal
  5256. \brief (Private)
  5257. This is a private class and not part of the public QCustomPlot interface.
  5258. It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and
  5259. axis label. It also buffers the labels to reduce replot times. The parameters are configured by
  5260. directly accessing the public member variables.
  5261. */
  5262. /*!
  5263. Constructs a QCPAxisPainterPrivate instance. Make sure to not create a new instance on every
  5264. redraw, to utilize the caching mechanisms.
  5265. */
  5266. QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) :
  5267. type(QCPAxis::atLeft),
  5268. basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  5269. lowerEnding(QCPLineEnding::esNone),
  5270. upperEnding(QCPLineEnding::esNone),
  5271. labelPadding(0),
  5272. tickLabelPadding(0),
  5273. tickLabelRotation(0),
  5274. substituteExponent(true),
  5275. numberMultiplyCross(false),
  5276. tickLengthIn(5),
  5277. tickLengthOut(0),
  5278. subTickLengthIn(2),
  5279. subTickLengthOut(0),
  5280. tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  5281. subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  5282. offset(0),
  5283. abbreviateDecimalPowers(false),
  5284. reversedEndings(false),
  5285. mParentPlot(parentPlot),
  5286. mLabelCache(16) // cache at most 16 (tick) labels
  5287. {
  5288. }
  5289. QCPAxisPainterPrivate::~QCPAxisPainterPrivate()
  5290. {
  5291. }
  5292. /*! \internal
  5293. Draws the axis with the specified \a painter.
  5294. The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set
  5295. here, too.
  5296. */
  5297. void QCPAxisPainterPrivate::draw(QCPPainter *painter)
  5298. {
  5299. QByteArray newHash = generateLabelParameterHash();
  5300. if (newHash != mLabelParameterHash)
  5301. {
  5302. mLabelCache.clear();
  5303. mLabelParameterHash = newHash;
  5304. }
  5305. QPoint origin;
  5306. switch (type)
  5307. {
  5308. case QCPAxis::atLeft: origin = alignmentRect.bottomLeft() +QPoint(-offset, 0); break;
  5309. case QCPAxis::atRight: origin = alignmentRect.bottomRight()+QPoint(+offset, 0); break;
  5310. case QCPAxis::atTop: origin = alignmentRect.topLeft() +QPoint(0, -offset); break;
  5311. case QCPAxis::atBottom: origin = alignmentRect.bottomLeft() +QPoint(0, +offset); break;
  5312. }
  5313. double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes)
  5314. switch (type)
  5315. {
  5316. case QCPAxis::atTop: yCor = -1; break;
  5317. case QCPAxis::atRight: xCor = 1; break;
  5318. default: break;
  5319. }
  5320. int margin = 0;
  5321. // draw baseline:
  5322. QLineF baseLine;
  5323. painter->setPen(basePen);
  5324. if (QCPAxis::orientation(type) == Qt::Horizontal)
  5325. baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(alignmentRect.width()+xCor, yCor));
  5326. else
  5327. baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -alignmentRect.height()+yCor));
  5328. if (reversedEndings)
  5329. baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later
  5330. painter->drawLine(baseLine);
  5331. // draw ticks:
  5332. if (!tickPositions.isEmpty())
  5333. {
  5334. painter->setPen(tickPen);
  5335. int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis)
  5336. if (QCPAxis::orientation(type) == Qt::Horizontal)
  5337. {
  5338. for (int i=0; i<tickPositions.size(); ++i)
  5339. painter->drawLine(QLineF(tickPositions.at(i)+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPositions.at(i)+xCor, origin.y()+tickLengthIn*tickDir+yCor));
  5340. } else
  5341. {
  5342. for (int i=0; i<tickPositions.size(); ++i)
  5343. painter->drawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPositions.at(i)+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPositions.at(i)+yCor));
  5344. }
  5345. }
  5346. // draw subticks:
  5347. if (!subTickPositions.isEmpty())
  5348. {
  5349. painter->setPen(subTickPen);
  5350. // direction of ticks ("inward" is right for left axis and left for right axis)
  5351. int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1;
  5352. if (QCPAxis::orientation(type) == Qt::Horizontal)
  5353. {
  5354. for (int i=0; i<subTickPositions.size(); ++i)
  5355. painter->drawLine(QLineF(subTickPositions.at(i)+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPositions.at(i)+xCor, origin.y()+subTickLengthIn*tickDir+yCor));
  5356. } else
  5357. {
  5358. for (int i=0; i<subTickPositions.size(); ++i)
  5359. painter->drawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPositions.at(i)+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPositions.at(i)+yCor));
  5360. }
  5361. }
  5362. margin += qMax(0, qMax(tickLengthOut, subTickLengthOut));
  5363. // draw axis base endings:
  5364. bool antialiasingBackup = painter->antialiasing();
  5365. painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't
  5366. painter->setBrush(QBrush(basePen.color()));
  5367. QVector2D baseLineVector(baseLine.dx(), baseLine.dy());
  5368. if (lowerEnding.style() != QCPLineEnding::esNone)
  5369. lowerEnding.draw(painter, QVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector);
  5370. if (upperEnding.style() != QCPLineEnding::esNone)
  5371. upperEnding.draw(painter, QVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector);
  5372. painter->setAntialiasing(antialiasingBackup);
  5373. // tick labels:
  5374. QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label
  5375. if (!tickLabels.isEmpty())
  5376. {
  5377. margin += tickLabelPadding;
  5378. painter->setFont(tickLabelFont);
  5379. painter->setPen(QPen(tickLabelColor));
  5380. const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size());
  5381. for (int i=0; i<maxLabelIndex; ++i)
  5382. placeTickLabel(painter, tickPositions.at(i), margin, tickLabels.at(i), &tickLabelsSize);
  5383. if (QCPAxis::orientation(type) == Qt::Horizontal)
  5384. margin += tickLabelsSize.height();
  5385. else
  5386. margin += tickLabelsSize.width();
  5387. }
  5388. // axis label:
  5389. QRect labelBounds;
  5390. if (!label.isEmpty())
  5391. {
  5392. margin += labelPadding;
  5393. painter->setFont(labelFont);
  5394. painter->setPen(QPen(labelColor));
  5395. labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label);
  5396. if (type == QCPAxis::atLeft)
  5397. {
  5398. QTransform oldTransform = painter->transform();
  5399. painter->translate((origin.x()-margin-labelBounds.height()), origin.y());
  5400. painter->rotate(-90);
  5401. painter->drawText(0, 0, alignmentRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  5402. painter->setTransform(oldTransform);
  5403. }
  5404. else if (type == QCPAxis::atRight)
  5405. {
  5406. QTransform oldTransform = painter->transform();
  5407. painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-alignmentRect.height());
  5408. painter->rotate(90);
  5409. painter->drawText(0, 0, alignmentRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  5410. painter->setTransform(oldTransform);
  5411. }
  5412. else if (type == QCPAxis::atTop)
  5413. painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), alignmentRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  5414. else if (type == QCPAxis::atBottom)
  5415. painter->drawText(origin.x(), origin.y()+margin, alignmentRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  5416. }
  5417. // set selection boxes:
  5418. int selectionTolerance = 0;
  5419. if (mParentPlot)
  5420. selectionTolerance = mParentPlot->selectionTolerance();
  5421. else
  5422. qDebug() << Q_FUNC_INFO << "mParentPlot is null";
  5423. int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance);
  5424. int selAxisInSize = selectionTolerance;
  5425. int selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
  5426. int selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding;
  5427. int selLabelSize = labelBounds.height();
  5428. int selLabelOffset = selTickLabelOffset+selTickLabelSize+labelPadding;
  5429. if (type == QCPAxis::atLeft)
  5430. {
  5431. mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, alignmentRect.top(), origin.x()+selAxisInSize, alignmentRect.bottom());
  5432. mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, alignmentRect.top(), origin.x()-selTickLabelOffset, alignmentRect.bottom());
  5433. mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, alignmentRect.top(), origin.x()-selLabelOffset, alignmentRect.bottom());
  5434. } else if (type == QCPAxis::atRight)
  5435. {
  5436. mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, alignmentRect.top(), origin.x()+selAxisOutSize, alignmentRect.bottom());
  5437. mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, alignmentRect.top(), origin.x()+selTickLabelOffset, alignmentRect.bottom());
  5438. mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, alignmentRect.top(), origin.x()+selLabelOffset, alignmentRect.bottom());
  5439. } else if (type == QCPAxis::atTop)
  5440. {
  5441. mAxisSelectionBox.setCoords(alignmentRect.left(), origin.y()-selAxisOutSize, alignmentRect.right(), origin.y()+selAxisInSize);
  5442. mTickLabelsSelectionBox.setCoords(alignmentRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, alignmentRect.right(), origin.y()-selTickLabelOffset);
  5443. mLabelSelectionBox.setCoords(alignmentRect.left(), origin.y()-selLabelOffset-selLabelSize, alignmentRect.right(), origin.y()-selLabelOffset);
  5444. } else if (type == QCPAxis::atBottom)
  5445. {
  5446. mAxisSelectionBox.setCoords(alignmentRect.left(), origin.y()-selAxisInSize, alignmentRect.right(), origin.y()+selAxisOutSize);
  5447. mTickLabelsSelectionBox.setCoords(alignmentRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, alignmentRect.right(), origin.y()+selTickLabelOffset);
  5448. mLabelSelectionBox.setCoords(alignmentRect.left(), origin.y()+selLabelOffset+selLabelSize, alignmentRect.right(), origin.y()+selLabelOffset);
  5449. }
  5450. // draw hitboxes for debug purposes:
  5451. //painter->setBrush(Qt::NoBrush);
  5452. //painter->drawRects(QVector<QRect>() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox);
  5453. }
  5454. /*! \internal
  5455. Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone
  5456. direction) needed to fit the axis.
  5457. */
  5458. int QCPAxisPainterPrivate::size() const
  5459. {
  5460. int result = 0;
  5461. // get length of tick marks pointing outwards:
  5462. if (!tickPositions.isEmpty())
  5463. result += qMax(0, qMax(tickLengthOut, subTickLengthOut));
  5464. // calculate size of tick labels:
  5465. QSize tickLabelsSize(0, 0);
  5466. if (!tickLabels.isEmpty())
  5467. {
  5468. for (int i=0; i<tickLabels.size(); ++i)
  5469. getMaxTickLabelSize(tickLabelFont, tickLabels.at(i), &tickLabelsSize);
  5470. result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width();
  5471. result += tickLabelPadding;
  5472. }
  5473. // calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees):
  5474. if (!label.isEmpty())
  5475. {
  5476. QFontMetrics fontMetrics(labelFont);
  5477. QRect bounds;
  5478. bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label);
  5479. result += bounds.height() + labelPadding;
  5480. }
  5481. return result;
  5482. }
  5483. /*! \internal
  5484. Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This
  5485. method is called automatically in \ref draw, if any parameters have changed that invalidate the
  5486. cached labels, such as font, color, etc.
  5487. */
  5488. void QCPAxisPainterPrivate::clearCache()
  5489. {
  5490. mLabelCache.clear();
  5491. }
  5492. /*! \internal
  5493. Returns a hash that allows uniquely identifying whether the label parameters have changed such
  5494. that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the
  5495. return value of this method hasn't changed since the last redraw, the respective label parameters
  5496. haven't changed and cached labels may be used.
  5497. */
  5498. QByteArray QCPAxisPainterPrivate::generateLabelParameterHash() const
  5499. {
  5500. QByteArray result;
  5501. result.append(QByteArray::number(tickLabelRotation));
  5502. result.append(QByteArray::number((int)substituteExponent));
  5503. result.append(QByteArray::number((int)numberMultiplyCross));
  5504. result.append(tickLabelColor.name()+QByteArray::number(tickLabelColor.alpha(), 16));
  5505. result.append(tickLabelFont.toString());
  5506. return result;
  5507. }
  5508. /*! \internal
  5509. Draws a single tick label with the provided \a painter, utilizing the internal label cache to
  5510. significantly speed up drawing of labels that were drawn in previous calls. The tick label is
  5511. always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in
  5512. pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence
  5513. for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate),
  5514. at which the label should be drawn.
  5515. In order to later draw the axis label in a place that doesn't overlap with the tick labels, the
  5516. largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref
  5517. drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a
  5518. tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently
  5519. holds.
  5520. The label is drawn with the font and pen that are currently set on the \a painter. To draw
  5521. superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref
  5522. getTickLabelData).
  5523. */
  5524. void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize)
  5525. {
  5526. // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly!
  5527. if (text.isEmpty()) return;
  5528. QSize finalSize;
  5529. QPointF labelAnchor;
  5530. switch (type)
  5531. {
  5532. case QCPAxis::atLeft: labelAnchor = QPointF(alignmentRect.left()-distanceToAxis-offset, position); break;
  5533. case QCPAxis::atRight: labelAnchor = QPointF(alignmentRect.right()+distanceToAxis+offset, position); break;
  5534. case QCPAxis::atTop: labelAnchor = QPointF(position, alignmentRect.top()-distanceToAxis-offset); break;
  5535. case QCPAxis::atBottom: labelAnchor = QPointF(position, alignmentRect.bottom()+distanceToAxis+offset); break;
  5536. }
  5537. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled
  5538. {
  5539. if (!mLabelCache.contains(text)) // no cached label exists, create it
  5540. {
  5541. CachedLabel *newCachedLabel = new CachedLabel;
  5542. TickLabelData labelData = getTickLabelData(painter->font(), text);
  5543. QPointF drawOffset = getTickLabelDrawOffset(labelData);
  5544. newCachedLabel->offset = drawOffset+labelData.rotatedTotalBounds.topLeft();
  5545. newCachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
  5546. newCachedLabel->pixmap.fill(Qt::transparent);
  5547. QCPPainter cachePainter(&newCachedLabel->pixmap);
  5548. cachePainter.setPen(painter->pen());
  5549. drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData);
  5550. mLabelCache.insert(text, newCachedLabel, 1);
  5551. }
  5552. // draw cached label:
  5553. const CachedLabel *cachedLabel = mLabelCache.object(text);
  5554. // if label would be partly clipped by widget border on sides, don't draw it:
  5555. if (QCPAxis::orientation(type) == Qt::Horizontal)
  5556. {
  5557. if (labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width() > viewportRect.right() ||
  5558. labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left())
  5559. return;
  5560. } else
  5561. {
  5562. if (labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height() >viewportRect.bottom() ||
  5563. labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top())
  5564. return;
  5565. }
  5566. painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap);
  5567. finalSize = cachedLabel->pixmap.size();
  5568. } else // label caching disabled, draw text directly on surface:
  5569. {
  5570. TickLabelData labelData = getTickLabelData(painter->font(), text);
  5571. QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData);
  5572. // if label would be partly clipped by widget border on sides, don't draw it:
  5573. if (QCPAxis::orientation(type) == Qt::Horizontal)
  5574. {
  5575. if (finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() ||
  5576. finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left())
  5577. return;
  5578. } else
  5579. {
  5580. if (finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() ||
  5581. finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top())
  5582. return;
  5583. }
  5584. drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData);
  5585. finalSize = labelData.rotatedTotalBounds.size();
  5586. }
  5587. // expand passed tickLabelsSize if current tick label is larger:
  5588. if (finalSize.width() > tickLabelsSize->width())
  5589. tickLabelsSize->setWidth(finalSize.width());
  5590. if (finalSize.height() > tickLabelsSize->height())
  5591. tickLabelsSize->setHeight(finalSize.height());
  5592. }
  5593. /*! \internal
  5594. This is a \ref placeTickLabel helper function.
  5595. Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a
  5596. y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to
  5597. directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when
  5598. QCP::phCacheLabels plotting hint is not set.
  5599. */
  5600. void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const
  5601. {
  5602. // backup painter settings that we're about to change:
  5603. QTransform oldTransform = painter->transform();
  5604. QFont oldFont = painter->font();
  5605. // transform painter to position/rotation:
  5606. painter->translate(x, y);
  5607. if (!qFuzzyIsNull(tickLabelRotation))
  5608. painter->rotate(tickLabelRotation);
  5609. // draw text:
  5610. if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used
  5611. {
  5612. painter->setFont(labelData.baseFont);
  5613. painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart);
  5614. painter->setFont(labelData.expFont);
  5615. painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart);
  5616. } else
  5617. {
  5618. painter->setFont(labelData.baseFont);
  5619. painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart);
  5620. }
  5621. // reset painter settings to what it was before:
  5622. painter->setTransform(oldTransform);
  5623. painter->setFont(oldFont);
  5624. }
  5625. /*! \internal
  5626. This is a \ref placeTickLabel helper function.
  5627. Transforms the passed \a text and \a font to a tickLabelData structure that can then be further
  5628. processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and
  5629. exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes.
  5630. */
  5631. QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const
  5632. {
  5633. TickLabelData result;
  5634. // determine whether beautiful decimal powers should be used
  5635. bool useBeautifulPowers = false;
  5636. int ePos = -1;
  5637. if (substituteExponent)
  5638. {
  5639. ePos = text.indexOf('e');
  5640. if (ePos > -1)
  5641. useBeautifulPowers = true;
  5642. }
  5643. // calculate text bounding rects and do string preparation for beautiful decimal powers:
  5644. result.baseFont = font;
  5645. 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
  5646. 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
  5647. if (useBeautifulPowers)
  5648. {
  5649. // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent:
  5650. result.basePart = text.left(ePos);
  5651. // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base:
  5652. if (abbreviateDecimalPowers && result.basePart == "1")
  5653. result.basePart = "10";
  5654. else
  5655. result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + "10";
  5656. result.expPart = text.mid(ePos+1);
  5657. // clip "+" and leading zeros off expPart:
  5658. while (result.expPart.length() > 2 && result.expPart.at(1) == '0') // length > 2 so we leave one zero when numberFormatChar is 'e'
  5659. result.expPart.remove(1, 1);
  5660. if (!result.expPart.isEmpty() && result.expPart.at(0) == '+')
  5661. result.expPart.remove(0, 1);
  5662. // prepare smaller font for exponent:
  5663. result.expFont = font;
  5664. result.expFont.setPointSize(result.expFont.pointSize()*0.75);
  5665. // calculate bounding rects of base part, exponent part and total one:
  5666. result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart);
  5667. result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart);
  5668. 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
  5669. } else // useBeautifulPowers == false
  5670. {
  5671. result.basePart = text;
  5672. result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart);
  5673. }
  5674. 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
  5675. // calculate possibly different bounding rect after rotation:
  5676. result.rotatedTotalBounds = result.totalBounds;
  5677. if (!qFuzzyIsNull(tickLabelRotation))
  5678. {
  5679. QTransform transform;
  5680. transform.rotate(tickLabelRotation);
  5681. result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds);
  5682. }
  5683. return result;
  5684. }
  5685. /*! \internal
  5686. This is a \ref placeTickLabel helper function.
  5687. Calculates the offset at which the top left corner of the specified tick label shall be drawn.
  5688. The offset is relative to a point right next to the tick the label belongs to.
  5689. This function is thus responsible for e.g. centering tick labels under ticks and positioning them
  5690. appropriately when they are rotated.
  5691. */
  5692. QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const
  5693. {
  5694. /*
  5695. calculate label offset from base point at tick (non-trivial, for best visual appearance): short
  5696. explanation for bottom axis: The anchor, i.e. the point in the label that is placed
  5697. horizontally under the corresponding tick is always on the label side that is closer to the
  5698. axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height
  5699. is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text
  5700. will be centered under the tick (i.e. displaced horizontally by half its height). At the same
  5701. time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick
  5702. labels.
  5703. */
  5704. bool doRotation = !qFuzzyIsNull(tickLabelRotation);
  5705. bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes.
  5706. double radians = tickLabelRotation/180.0*M_PI;
  5707. int x=0, y=0;
  5708. if (type == QCPAxis::atLeft)
  5709. {
  5710. if (doRotation)
  5711. {
  5712. if (tickLabelRotation > 0)
  5713. {
  5714. x = -qCos(radians)*labelData.totalBounds.width();
  5715. y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0;
  5716. } else
  5717. {
  5718. x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height();
  5719. y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0;
  5720. }
  5721. } else
  5722. {
  5723. x = -labelData.totalBounds.width();
  5724. y = -labelData.totalBounds.height()/2.0;
  5725. }
  5726. } else if (type == QCPAxis::atRight)
  5727. {
  5728. if (doRotation)
  5729. {
  5730. if (tickLabelRotation > 0)
  5731. {
  5732. x = +qSin(radians)*labelData.totalBounds.height();
  5733. y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0;
  5734. } else
  5735. {
  5736. x = 0;
  5737. y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0;
  5738. }
  5739. } else
  5740. {
  5741. x = 0;
  5742. y = -labelData.totalBounds.height()/2.0;
  5743. }
  5744. } else if (type == QCPAxis::atTop)
  5745. {
  5746. if (doRotation)
  5747. {
  5748. if (tickLabelRotation > 0)
  5749. {
  5750. x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0;
  5751. y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height();
  5752. } else
  5753. {
  5754. x = -qSin(-radians)*labelData.totalBounds.height()/2.0;
  5755. y = -qCos(-radians)*labelData.totalBounds.height();
  5756. }
  5757. } else
  5758. {
  5759. x = -labelData.totalBounds.width()/2.0;
  5760. y = -labelData.totalBounds.height();
  5761. }
  5762. } else if (type == QCPAxis::atBottom)
  5763. {
  5764. if (doRotation)
  5765. {
  5766. if (tickLabelRotation > 0)
  5767. {
  5768. x = +qSin(radians)*labelData.totalBounds.height()/2.0;
  5769. y = 0;
  5770. } else
  5771. {
  5772. x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0;
  5773. y = +qSin(-radians)*labelData.totalBounds.width();
  5774. }
  5775. } else
  5776. {
  5777. x = -labelData.totalBounds.width()/2.0;
  5778. y = 0;
  5779. }
  5780. }
  5781. return QPointF(x, y);
  5782. }
  5783. /*! \internal
  5784. Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label
  5785. to be drawn, depending on number format etc. Since only the largest tick label is wanted for the
  5786. margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a
  5787. smaller width/height.
  5788. */
  5789. void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const
  5790. {
  5791. // note: this function must return the same tick label sizes as the placeTickLabel function.
  5792. QSize finalSize;
  5793. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label
  5794. {
  5795. const CachedLabel *cachedLabel = mLabelCache.object(text);
  5796. finalSize = cachedLabel->pixmap.size();
  5797. } else // label caching disabled or no label with this text cached:
  5798. {
  5799. TickLabelData labelData = getTickLabelData(font, text);
  5800. finalSize = labelData.rotatedTotalBounds.size();
  5801. }
  5802. // expand passed tickLabelsSize if current tick label is larger:
  5803. if (finalSize.width() > tickLabelsSize->width())
  5804. tickLabelsSize->setWidth(finalSize.width());
  5805. if (finalSize.height() > tickLabelsSize->height())
  5806. tickLabelsSize->setHeight(finalSize.height());
  5807. }
  5808. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5809. //////////////////// QCPAbstractPlottable
  5810. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5811. /*! \class QCPAbstractPlottable
  5812. \brief The abstract base class for all data representing objects in a plot.
  5813. It defines a very basic interface like name, pen, brush, visibility etc. Since this class is
  5814. abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to
  5815. create new ways of displaying data (see "Creating own plottables" below).
  5816. All further specifics are in the subclasses, for example:
  5817. \li A normal graph with possibly a line, scatter points and error bars is displayed by \ref QCPGraph
  5818. (typically created with \ref QCustomPlot::addGraph).
  5819. \li A parametric curve can be displayed with \ref QCPCurve.
  5820. \li A stackable bar chart can be achieved with \ref QCPBars.
  5821. \li A box of a statistical box plot is created with \ref QCPStatisticalBox.
  5822. \section plottables-subclassing Creating own plottables
  5823. To create an own plottable, you implement a subclass of QCPAbstractPlottable. These are the pure
  5824. virtual functions, you must implement:
  5825. \li \ref clearData
  5826. \li \ref selectTest
  5827. \li \ref draw
  5828. \li \ref drawLegendIcon
  5829. \li \ref getKeyRange
  5830. \li \ref getValueRange
  5831. See the documentation of those functions for what they need to do.
  5832. For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot
  5833. coordinates to pixel coordinates. This function is quite convenient, because it takes the
  5834. orientation of the key and value axes into account for you (x and y are swapped when the key axis
  5835. is vertical and the value axis horizontal). If you are worried about performance (i.e. you need
  5836. to translate many points in a loop like QCPGraph), you can directly use \ref
  5837. QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis
  5838. yourself.
  5839. Here are some important members you inherit from QCPAbstractPlottable:
  5840. <table>
  5841. <tr>
  5842. <td>QCustomPlot *\b mParentPlot</td>
  5843. <td>A pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.</td>
  5844. </tr><tr>
  5845. <td>QString \b mName</td>
  5846. <td>The name of the plottable.</td>
  5847. </tr><tr>
  5848. <td>QPen \b mPen</td>
  5849. <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>
  5850. </tr><tr>
  5851. <td>QPen \b mSelectedPen</td>
  5852. <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>
  5853. </tr><tr>
  5854. <td>QBrush \b mBrush</td>
  5855. <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>
  5856. </tr><tr>
  5857. <td>QBrush \b mSelectedBrush</td>
  5858. <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>
  5859. </tr><tr>
  5860. <td>QPointer<QCPAxis>\b mKeyAxis, \b mValueAxis</td>
  5861. <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.
  5862. 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>
  5863. </tr><tr>
  5864. <td>bool \b mSelected</td>
  5865. <td>indicates whether the plottable is selected or not.</td>
  5866. </tr>
  5867. </table>
  5868. */
  5869. /* start of documentation of pure virtual functions */
  5870. /*! \fn void QCPAbstractPlottable::clearData() = 0
  5871. Clears all data in the plottable.
  5872. */
  5873. /*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0
  5874. \internal
  5875. called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation
  5876. of this plottable inside \a rect, next to the plottable name.
  5877. */
  5878. /*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, SignDomain inSignDomain) const = 0
  5879. \internal
  5880. called by rescaleAxes functions to get the full data key bounds. For logarithmic plots, one can
  5881. set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the
  5882. returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain
  5883. to \ref sdNegative and all positive points will be ignored for range calculation. For no
  5884. restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output
  5885. parameter that indicates whether a range could be found or not. If this is false, you shouldn't
  5886. use the returned range (e.g. no points in data).
  5887. Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
  5888. this function may have size zero, which wouldn't count as a valid range.
  5889. \see rescaleAxes, getValueRange
  5890. */
  5891. /*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, SignDomain inSignDomain) const = 0
  5892. \internal
  5893. called by rescaleAxes functions to get the full data value bounds. For logarithmic plots, one can
  5894. set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the
  5895. returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain
  5896. to \ref sdNegative and all positive points will be ignored for range calculation. For no
  5897. restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output
  5898. parameter that indicates whether a range could be found or not. If this is false, you shouldn't
  5899. use the returned range (e.g. no points in data).
  5900. Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
  5901. this function may have size zero, which wouldn't count as a valid range.
  5902. \see rescaleAxes, getKeyRange
  5903. */
  5904. /* end of documentation of pure virtual functions */
  5905. /* start of documentation of signals */
  5906. /*! \fn void QCPAbstractPlottable::selectionChanged(bool selected)
  5907. This signal is emitted when the selection state of this plottable has changed, either by user
  5908. interaction or by a direct call to \ref setSelected.
  5909. */
  5910. /*! \fn void QCPAbstractPlottable::selectableChanged(bool selectable);
  5911. This signal is emitted when the selectability of this plottable has changed.
  5912. \see setSelectable
  5913. */
  5914. /* end of documentation of signals */
  5915. /*!
  5916. Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as
  5917. its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance
  5918. and have perpendicular orientations. If either of these restrictions is violated, a corresponding
  5919. message is printed to the debug output (qDebug), the construction is not aborted, though.
  5920. Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables,
  5921. it can't be directly instantiated.
  5922. You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead.
  5923. */
  5924. QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  5925. QCPLayerable(keyAxis->parentPlot(), "", keyAxis->axisRect()),
  5926. mName(""),
  5927. mAntialiasedFill(true),
  5928. mAntialiasedScatters(true),
  5929. mAntialiasedErrorBars(false),
  5930. mPen(Qt::black),
  5931. mSelectedPen(Qt::black),
  5932. mBrush(Qt::NoBrush),
  5933. mSelectedBrush(Qt::NoBrush),
  5934. mKeyAxis(keyAxis),
  5935. mValueAxis(valueAxis),
  5936. mSelectable(true),
  5937. mSelected(false)
  5938. {
  5939. if (keyAxis->parentPlot() != valueAxis->parentPlot())
  5940. qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
  5941. if (keyAxis->orientation() == valueAxis->orientation())
  5942. qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other.";
  5943. }
  5944. /*!
  5945. The name is the textual representation of this plottable as it is displayed in the legend
  5946. (\ref QCPLegend). It may contain any UTF-8 characters, including newlines.
  5947. */
  5948. void QCPAbstractPlottable::setName(const QString &name)
  5949. {
  5950. mName = name;
  5951. }
  5952. /*!
  5953. Sets whether fills of this plottable is drawn antialiased or not.
  5954. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  5955. QCustomPlot::setNotAntialiasedElements.
  5956. */
  5957. void QCPAbstractPlottable::setAntialiasedFill(bool enabled)
  5958. {
  5959. mAntialiasedFill = enabled;
  5960. }
  5961. /*!
  5962. Sets whether the scatter symbols of this plottable are drawn antialiased or not.
  5963. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  5964. QCustomPlot::setNotAntialiasedElements.
  5965. */
  5966. void QCPAbstractPlottable::setAntialiasedScatters(bool enabled)
  5967. {
  5968. mAntialiasedScatters = enabled;
  5969. }
  5970. /*!
  5971. Sets whether the error bars of this plottable are drawn antialiased or not.
  5972. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  5973. QCustomPlot::setNotAntialiasedElements.
  5974. */
  5975. void QCPAbstractPlottable::setAntialiasedErrorBars(bool enabled)
  5976. {
  5977. mAntialiasedErrorBars = enabled;
  5978. }
  5979. /*!
  5980. The pen is used to draw basic lines that make up the plottable representation in the
  5981. plot.
  5982. For example, the \ref QCPGraph subclass draws its graph lines and scatter points
  5983. with this pen.
  5984. \see setBrush
  5985. */
  5986. void QCPAbstractPlottable::setPen(const QPen &pen)
  5987. {
  5988. mPen = pen;
  5989. }
  5990. /*!
  5991. When the plottable is selected, this pen is used to draw basic lines instead of the normal
  5992. pen set via \ref setPen.
  5993. \see setSelected, setSelectable, setSelectedBrush, selectTest
  5994. */
  5995. void QCPAbstractPlottable::setSelectedPen(const QPen &pen)
  5996. {
  5997. mSelectedPen = pen;
  5998. }
  5999. /*!
  6000. The brush is used to draw basic fills of the plottable representation in the
  6001. plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
  6002. For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when
  6003. it's not set to Qt::NoBrush.
  6004. \see setPen
  6005. */
  6006. void QCPAbstractPlottable::setBrush(const QBrush &brush)
  6007. {
  6008. mBrush = brush;
  6009. }
  6010. /*!
  6011. When the plottable is selected, this brush is used to draw fills instead of the normal
  6012. brush set via \ref setBrush.
  6013. \see setSelected, setSelectable, setSelectedPen, selectTest
  6014. */
  6015. void QCPAbstractPlottable::setSelectedBrush(const QBrush &brush)
  6016. {
  6017. mSelectedBrush = brush;
  6018. }
  6019. /*!
  6020. The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
  6021. to the plottable's value axis. This function performs no checks to make sure this is the case.
  6022. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
  6023. y-axis (QCustomPlot::yAxis) as value axis.
  6024. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  6025. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  6026. \see setValueAxis
  6027. */
  6028. void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis)
  6029. {
  6030. mKeyAxis = axis;
  6031. }
  6032. /*!
  6033. The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is
  6034. orthogonal to the plottable's key axis. This function performs no checks to make sure this is the
  6035. case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and
  6036. the y-axis (QCustomPlot::yAxis) as value axis.
  6037. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  6038. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  6039. \see setKeyAxis
  6040. */
  6041. void QCPAbstractPlottable::setValueAxis(QCPAxis *axis)
  6042. {
  6043. mValueAxis = axis;
  6044. }
  6045. /*!
  6046. Sets whether the user can (de-)select this plottable by clicking on the QCustomPlot surface.
  6047. (When \ref QCustomPlot::setInteractions contains iSelectPlottables.)
  6048. However, even when \a selectable was set to false, it is possible to set the selection manually,
  6049. by calling \ref setSelected directly.
  6050. \see setSelected
  6051. */
  6052. void QCPAbstractPlottable::setSelectable(bool selectable)
  6053. {
  6054. if (mSelectable != selectable)
  6055. {
  6056. mSelectable = selectable;
  6057. emit selectableChanged(mSelectable);
  6058. }
  6059. }
  6060. /*!
  6061. Sets whether this plottable is selected or not. When selected, it uses a different pen and brush
  6062. to draw its lines and fills, see \ref setSelectedPen and \ref setSelectedBrush.
  6063. The entire selection mechanism for plottables is handled automatically when \ref
  6064. QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
  6065. you wish to change the selection state manually.
  6066. This function can change the selection state even when \ref setSelectable was set to false.
  6067. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  6068. \see setSelectable, selectTest
  6069. */
  6070. void QCPAbstractPlottable::setSelected(bool selected)
  6071. {
  6072. if (mSelected != selected)
  6073. {
  6074. mSelected = selected;
  6075. emit selectionChanged(mSelected);
  6076. }
  6077. }
  6078. /*!
  6079. Rescales the key and value axes associated with this plottable to contain all displayed data, so
  6080. the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make
  6081. sure not to rescale to an illegal range i.e. a range containing different signs and/or zero.
  6082. Instead it will stay in the current sign domain and ignore all parts of the plottable that lie
  6083. outside of that domain.
  6084. \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show
  6085. multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has
  6086. \a onlyEnlarge set to false (the default), and all subsequent set to true.
  6087. \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale
  6088. */
  6089. void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const
  6090. {
  6091. rescaleKeyAxis(onlyEnlarge);
  6092. rescaleValueAxis(onlyEnlarge);
  6093. }
  6094. /*!
  6095. Rescales the key axis of the plottable so the whole plottable is visible.
  6096. See \ref rescaleAxes for detailed behaviour.
  6097. */
  6098. void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const
  6099. {
  6100. QCPAxis *keyAxis = mKeyAxis.data();
  6101. if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
  6102. SignDomain signDomain = sdBoth;
  6103. if (keyAxis->scaleType() == QCPAxis::stLogarithmic)
  6104. signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive);
  6105. bool foundRange;
  6106. QCPRange newRange = getKeyRange(foundRange, signDomain);
  6107. if (foundRange)
  6108. {
  6109. if (onlyEnlarge)
  6110. newRange.expand(keyAxis->range());
  6111. 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
  6112. {
  6113. 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
  6114. if (keyAxis->scaleType() == QCPAxis::stLinear)
  6115. {
  6116. newRange.lower = center-keyAxis->range().size()/2.0;
  6117. newRange.upper = center+keyAxis->range().size()/2.0;
  6118. } else // scaleType() == stLogarithmic
  6119. {
  6120. newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower);
  6121. newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower);
  6122. }
  6123. }
  6124. keyAxis->setRange(newRange);
  6125. }
  6126. }
  6127. /*!
  6128. Rescales the value axis of the plottable so the whole plottable is visible.
  6129. Returns true if the axis was actually scaled. This might not be the case if this plottable has an
  6130. invalid range, e.g. because it has no data points.
  6131. See \ref rescaleAxes for detailed behaviour.
  6132. */
  6133. void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge) const
  6134. {
  6135. QCPAxis *valueAxis = mValueAxis.data();
  6136. if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; }
  6137. SignDomain signDomain = sdBoth;
  6138. if (valueAxis->scaleType() == QCPAxis::stLogarithmic)
  6139. signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive);
  6140. bool foundRange;
  6141. QCPRange newRange = getValueRange(foundRange, signDomain);
  6142. if (foundRange)
  6143. {
  6144. if (onlyEnlarge)
  6145. newRange.expand(valueAxis->range());
  6146. 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
  6147. {
  6148. 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
  6149. if (valueAxis->scaleType() == QCPAxis::stLinear)
  6150. {
  6151. newRange.lower = center-valueAxis->range().size()/2.0;
  6152. newRange.upper = center+valueAxis->range().size()/2.0;
  6153. } else // scaleType() == stLogarithmic
  6154. {
  6155. newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  6156. newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  6157. }
  6158. }
  6159. valueAxis->setRange(newRange);
  6160. }
  6161. }
  6162. /*!
  6163. Adds this plottable to the legend of the parent QCustomPlot (QCustomPlot::legend).
  6164. Normally, a QCPPlottableLegendItem is created and inserted into the legend. If the plottable
  6165. needs a more specialized representation in the legend, this function will take this into account
  6166. and instead create the specialized subclass of QCPAbstractLegendItem.
  6167. Returns true on success, i.e. when the legend exists and a legend item associated with this plottable isn't already in
  6168. the legend.
  6169. \see removeFromLegend, QCPLegend::addItem
  6170. */
  6171. bool QCPAbstractPlottable::addToLegend()
  6172. {
  6173. if (!mParentPlot || !mParentPlot->legend)
  6174. return false;
  6175. if (!mParentPlot->legend->hasItemWithPlottable(this))
  6176. {
  6177. mParentPlot->legend->addItem(new QCPPlottableLegendItem(mParentPlot->legend, this));
  6178. return true;
  6179. } else
  6180. return false;
  6181. }
  6182. /*!
  6183. Removes the plottable from the legend of the parent QCustomPlot. This means the
  6184. QCPAbstractLegendItem (usually a QCPPlottableLegendItem) that is associated with this plottable
  6185. is removed.
  6186. Returns true on success, i.e. if the legend exists and a legend item associated with this
  6187. plottable was found and removed.
  6188. \see addToLegend, QCPLegend::removeItem
  6189. */
  6190. bool QCPAbstractPlottable::removeFromLegend() const
  6191. {
  6192. if (!mParentPlot->legend)
  6193. return false;
  6194. if (QCPPlottableLegendItem *lip = mParentPlot->legend->itemWithPlottable(this))
  6195. return mParentPlot->legend->removeItem(lip);
  6196. else
  6197. return false;
  6198. }
  6199. /* inherits documentation from base class */
  6200. QRect QCPAbstractPlottable::clipRect() const
  6201. {
  6202. if (mKeyAxis && mValueAxis)
  6203. return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect();
  6204. else
  6205. return QRect();
  6206. }
  6207. /* inherits documentation from base class */
  6208. QCP::Interaction QCPAbstractPlottable::selectionCategory() const
  6209. {
  6210. return QCP::iSelectPlottables;
  6211. }
  6212. /*! \internal
  6213. Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface,
  6214. taking the orientations of the axes associated with this plottable into account (e.g. whether key
  6215. represents x or y).
  6216. \a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y.
  6217. \see pixelsToCoords, QCPAxis::coordToPixel
  6218. */
  6219. void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const
  6220. {
  6221. QCPAxis *keyAxis = mKeyAxis.data();
  6222. QCPAxis *valueAxis = mValueAxis.data();
  6223. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  6224. if (keyAxis->orientation() == Qt::Horizontal)
  6225. {
  6226. x = keyAxis->coordToPixel(key);
  6227. y = valueAxis->coordToPixel(value);
  6228. } else
  6229. {
  6230. y = keyAxis->coordToPixel(key);
  6231. x = valueAxis->coordToPixel(value);
  6232. }
  6233. }
  6234. /*! \internal
  6235. \overload
  6236. Returns the input as pixel coordinates in a QPointF.
  6237. */
  6238. const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const
  6239. {
  6240. QCPAxis *keyAxis = mKeyAxis.data();
  6241. QCPAxis *valueAxis = mValueAxis.data();
  6242. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
  6243. if (keyAxis->orientation() == Qt::Horizontal)
  6244. return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value));
  6245. else
  6246. return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key));
  6247. }
  6248. /*! \internal
  6249. Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates,
  6250. taking the orientations of the axes associated with this plottable into account (e.g. whether key
  6251. represents x or y).
  6252. \a x and \a y are transformed to the plot coodinates and are written to \a key and \a value.
  6253. \see coordsToPixels, QCPAxis::coordToPixel
  6254. */
  6255. void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const
  6256. {
  6257. QCPAxis *keyAxis = mKeyAxis.data();
  6258. QCPAxis *valueAxis = mValueAxis.data();
  6259. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  6260. if (keyAxis->orientation() == Qt::Horizontal)
  6261. {
  6262. key = keyAxis->pixelToCoord(x);
  6263. value = valueAxis->pixelToCoord(y);
  6264. } else
  6265. {
  6266. key = keyAxis->pixelToCoord(y);
  6267. value = valueAxis->pixelToCoord(x);
  6268. }
  6269. }
  6270. /*! \internal
  6271. \overload
  6272. Returns the pixel input \a pixelPos as plot coordinates \a key and \a value.
  6273. */
  6274. void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
  6275. {
  6276. pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value);
  6277. }
  6278. /*! \internal
  6279. Returns the pen that should be used for drawing lines of the plottable. Returns mPen when the
  6280. graph is not selected and mSelectedPen when it is.
  6281. */
  6282. QPen QCPAbstractPlottable::mainPen() const
  6283. {
  6284. return mSelected ? mSelectedPen : mPen;
  6285. }
  6286. /*! \internal
  6287. Returns the brush that should be used for drawing fills of the plottable. Returns mBrush when the
  6288. graph is not selected and mSelectedBrush when it is.
  6289. */
  6290. QBrush QCPAbstractPlottable::mainBrush() const
  6291. {
  6292. return mSelected ? mSelectedBrush : mBrush;
  6293. }
  6294. /*! \internal
  6295. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  6296. before drawing plottable lines.
  6297. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  6298. This function takes into account the local setting of the antialiasing flag as well as the
  6299. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  6300. QCustomPlot::setNotAntialiasedElements.
  6301. \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint
  6302. */
  6303. void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const
  6304. {
  6305. applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables);
  6306. }
  6307. /*! \internal
  6308. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  6309. before drawing plottable fills.
  6310. This function takes into account the local setting of the antialiasing flag as well as the
  6311. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  6312. QCustomPlot::setNotAntialiasedElements.
  6313. \see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint
  6314. */
  6315. void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const
  6316. {
  6317. applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills);
  6318. }
  6319. /*! \internal
  6320. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  6321. before drawing plottable scatter points.
  6322. This function takes into account the local setting of the antialiasing flag as well as the
  6323. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  6324. QCustomPlot::setNotAntialiasedElements.
  6325. \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint, applyErrorBarsAntialiasingHint
  6326. */
  6327. void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const
  6328. {
  6329. applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
  6330. }
  6331. /*! \internal
  6332. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  6333. before drawing plottable error bars.
  6334. This function takes into account the local setting of the antialiasing flag as well as the
  6335. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  6336. QCustomPlot::setNotAntialiasedElements.
  6337. \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyDefaultAntialiasingHint
  6338. */
  6339. void QCPAbstractPlottable::applyErrorBarsAntialiasingHint(QCPPainter *painter) const
  6340. {
  6341. applyAntialiasingHint(painter, mAntialiasedErrorBars, QCP::aeErrorBars);
  6342. }
  6343. /*! \internal
  6344. Finds the shortest squared distance of \a point to the line segment defined by \a start and \a
  6345. end.
  6346. This function may be used to help with the implementation of the \ref selectTest function for
  6347. specific plottables.
  6348. \note This function is identical to QCPAbstractItem::distSqrToLine
  6349. */
  6350. double QCPAbstractPlottable::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const
  6351. {
  6352. QVector2D a(start);
  6353. QVector2D b(end);
  6354. QVector2D p(point);
  6355. QVector2D v(b-a);
  6356. double vLengthSqr = v.lengthSquared();
  6357. if (!qFuzzyIsNull(vLengthSqr))
  6358. {
  6359. double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr;
  6360. if (mu < 0)
  6361. return (a-p).lengthSquared();
  6362. else if (mu > 1)
  6363. return (b-p).lengthSquared();
  6364. else
  6365. return ((a + mu*v)-p).lengthSquared();
  6366. } else
  6367. return (a-p).lengthSquared();
  6368. }
  6369. /* inherits documentation from base class */
  6370. void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  6371. {
  6372. Q_UNUSED(event)
  6373. Q_UNUSED(details)
  6374. if (mSelectable)
  6375. {
  6376. bool selBefore = mSelected;
  6377. setSelected(additive ? !mSelected : true);
  6378. if (selectionStateChanged)
  6379. *selectionStateChanged = mSelected != selBefore;
  6380. }
  6381. }
  6382. /* inherits documentation from base class */
  6383. void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged)
  6384. {
  6385. if (mSelectable)
  6386. {
  6387. bool selBefore = mSelected;
  6388. setSelected(false);
  6389. if (selectionStateChanged)
  6390. *selectionStateChanged = mSelected != selBefore;
  6391. }
  6392. }
  6393. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6394. //////////////////// QCPItemAnchor
  6395. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6396. /*! \class QCPItemAnchor
  6397. \brief An anchor of an item to which positions can be attached to.
  6398. An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't
  6399. control anything on its item, but provides a way to tie other items via their positions to the
  6400. anchor.
  6401. For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight.
  6402. Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can
  6403. attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by
  6404. calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the
  6405. QCPItemRect. This way the start of the line will now always follow the respective anchor location
  6406. on the rect item.
  6407. Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an
  6408. anchor to other positions.
  6409. To learn how to provide anchors in your own item subclasses, see the subclassing section of the
  6410. QCPAbstractItem documentation.
  6411. */
  6412. /* start documentation of inline functions */
  6413. /*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition()
  6414. Returns 0 if this instance is merely a QCPItemAnchor, and a valid pointer of type QCPItemPosition* if
  6415. it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor).
  6416. This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids
  6417. dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with
  6418. gcc compiler).
  6419. */
  6420. /* end documentation of inline functions */
  6421. /*!
  6422. Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if
  6423. you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as
  6424. explained in the subclassing section of the QCPAbstractItem documentation.
  6425. */
  6426. QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId) :
  6427. mName(name),
  6428. mParentPlot(parentPlot),
  6429. mParentItem(parentItem),
  6430. mAnchorId(anchorId)
  6431. {
  6432. }
  6433. QCPItemAnchor::~QCPItemAnchor()
  6434. {
  6435. // unregister as parent at children:
  6436. QList<QCPItemPosition*> currentChildren(mChildren.toList());
  6437. for (int i=0; i<currentChildren.size(); ++i)
  6438. currentChildren.at(i)->setParentAnchor(0); // this acts back on this anchor and child removes itself from mChildren
  6439. }
  6440. /*!
  6441. Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface.
  6442. The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the
  6443. parent item, QCPItemAnchor is just an intermediary.
  6444. */
  6445. QPointF QCPItemAnchor::pixelPoint() const
  6446. {
  6447. if (mParentItem)
  6448. {
  6449. if (mAnchorId > -1)
  6450. {
  6451. return mParentItem->anchorPixelPoint(mAnchorId);
  6452. } else
  6453. {
  6454. qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId;
  6455. return QPointF();
  6456. }
  6457. } else
  6458. {
  6459. qDebug() << Q_FUNC_INFO << "no parent item set";
  6460. return QPointF();
  6461. }
  6462. }
  6463. /*! \internal
  6464. Adds \a pos to the child list of this anchor. This is necessary to notify the children prior to
  6465. destruction of the anchor.
  6466. Note that this function does not change the parent setting in \a pos.
  6467. */
  6468. void QCPItemAnchor::addChild(QCPItemPosition *pos)
  6469. {
  6470. if (!mChildren.contains(pos))
  6471. mChildren.insert(pos);
  6472. else
  6473. qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
  6474. }
  6475. /*! \internal
  6476. Removes \a pos from the child list of this anchor.
  6477. Note that this function does not change the parent setting in \a pos.
  6478. */
  6479. void QCPItemAnchor::removeChild(QCPItemPosition *pos)
  6480. {
  6481. if (!mChildren.remove(pos))
  6482. qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
  6483. }
  6484. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6485. //////////////////// QCPItemPosition
  6486. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6487. /*! \class QCPItemPosition
  6488. \brief Manages the position of an item.
  6489. Every item has at least one public QCPItemPosition member pointer which provides ways to position the
  6490. item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two:
  6491. \a topLeft and \a bottomRight.
  6492. QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type defines
  6493. how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel coordinates, as
  6494. plot coordinates of certain axes, etc.
  6495. Further, QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. (Note that every
  6496. QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent anchor for other
  6497. positions.) This way you can tie multiple items together. If the QCPItemPosition has a parent, the
  6498. coordinates set with \ref setCoords are considered to be absolute values in the reference frame of the
  6499. parent anchor, where (0, 0) means directly ontop of the parent anchor. For example, You could attach
  6500. the \a start position of a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting
  6501. point of the line always be centered under the text label, no matter where the text is moved to, or is
  6502. itself tied to.
  6503. To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPoint. This
  6504. works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref
  6505. setPixelPoint transforms the coordinates appropriately, to make the position appear at the specified
  6506. pixel values.
  6507. */
  6508. /*!
  6509. Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if
  6510. you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as
  6511. explained in the subclassing section of the QCPAbstractItem documentation.
  6512. */
  6513. QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name) :
  6514. QCPItemAnchor(parentPlot, parentItem, name),
  6515. mPositionType(ptAbsolute),
  6516. mKey(0),
  6517. mValue(0),
  6518. mParentAnchor(0)
  6519. {
  6520. }
  6521. QCPItemPosition::~QCPItemPosition()
  6522. {
  6523. // unregister as parent at children:
  6524. // Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then
  6525. // the setParentAnchor(0) call the correct QCPItemPosition::pixelPoint function instead of QCPItemAnchor::pixelPoint
  6526. QList<QCPItemPosition*> currentChildren(mChildren.toList());
  6527. for (int i=0; i<currentChildren.size(); ++i)
  6528. currentChildren.at(i)->setParentAnchor(0); // this acts back on this anchor and child removes itself from mChildren
  6529. // unregister as child in parent:
  6530. if (mParentAnchor)
  6531. mParentAnchor->removeChild(this);
  6532. }
  6533. /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
  6534. QCPAxisRect *QCPItemPosition::axisRect() const
  6535. {
  6536. return mAxisRect.data();
  6537. }
  6538. /*!
  6539. Sets the type of the position. The type defines how the coordinates passed to \ref setCoords
  6540. should be handled and how the QCPItemPosition should behave in the plot.
  6541. The possible values for \a type can be separated in two main categories:
  6542. \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords
  6543. and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes.
  6544. By default, the QCustomPlot's x- and yAxis are used.
  6545. \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This
  6546. corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref
  6547. ptAxisRectRatio. They differ only in the way the absolute position is described, see the
  6548. documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify
  6549. the axis rect with \ref setAxisRect. By default this is set to the main axis rect.
  6550. Note that the position type \ref ptPlotCoords is only available (and sensible) when the position
  6551. has no parent anchor (\ref setParentAnchor).
  6552. If the type is changed, the apparent pixel position on the plot is preserved. This means
  6553. the coordinates as retrieved with coords() and set with \ref setCoords may change in the process.
  6554. */
  6555. void QCPItemPosition::setType(QCPItemPosition::PositionType type)
  6556. {
  6557. if (mPositionType != type)
  6558. {
  6559. // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
  6560. // were deleted), don't try to recover the pixelPoint() because it would output a qDebug warning.
  6561. bool recoverPixelPosition = true;
  6562. if ((mPositionType == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
  6563. recoverPixelPosition = false;
  6564. if ((mPositionType == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
  6565. recoverPixelPosition = false;
  6566. QPointF pixelP;
  6567. if (recoverPixelPosition)
  6568. pixelP = pixelPoint();
  6569. mPositionType = type;
  6570. if (recoverPixelPosition)
  6571. setPixelPoint(pixelP);
  6572. }
  6573. }
  6574. /*!
  6575. Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now
  6576. follow any position changes of the anchor. The local coordinate system of positions with a parent
  6577. anchor always is absolute with (0, 0) being exactly on top of the parent anchor. (Hence the type
  6578. shouldn't be \ref ptPlotCoords for positions with parent anchors.)
  6579. if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved
  6580. during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position
  6581. will be exactly on top of the parent anchor.
  6582. To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to 0.
  6583. If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is
  6584. set to \ref ptAbsolute, to keep the position in a valid state.
  6585. */
  6586. bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
  6587. {
  6588. // make sure self is not assigned as parent:
  6589. if (parentAnchor == this)
  6590. {
  6591. qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
  6592. return false;
  6593. }
  6594. // make sure no recursive parent-child-relationships are created:
  6595. QCPItemAnchor *currentParent = parentAnchor;
  6596. while (currentParent)
  6597. {
  6598. if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
  6599. {
  6600. // is a QCPItemPosition, might have further parent, so keep iterating
  6601. if (currentParentPos == this)
  6602. {
  6603. qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
  6604. return false;
  6605. }
  6606. currentParent = currentParentPos->mParentAnchor;
  6607. } else
  6608. {
  6609. // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
  6610. // same, to prevent a position being child of an anchor which itself depends on the position,
  6611. // because they're both on the same item:
  6612. if (currentParent->mParentItem == mParentItem)
  6613. {
  6614. qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
  6615. return false;
  6616. }
  6617. break;
  6618. }
  6619. }
  6620. // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
  6621. if (!mParentAnchor && mPositionType == ptPlotCoords)
  6622. setType(ptAbsolute);
  6623. // save pixel position:
  6624. QPointF pixelP;
  6625. if (keepPixelPosition)
  6626. pixelP = pixelPoint();
  6627. // unregister at current parent anchor:
  6628. if (mParentAnchor)
  6629. mParentAnchor->removeChild(this);
  6630. // register at new parent anchor:
  6631. if (parentAnchor)
  6632. parentAnchor->addChild(this);
  6633. mParentAnchor = parentAnchor;
  6634. // restore pixel position under new parent:
  6635. if (keepPixelPosition)
  6636. setPixelPoint(pixelP);
  6637. else
  6638. setCoords(0, 0);
  6639. return true;
  6640. }
  6641. /*!
  6642. Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type
  6643. (\ref setType).
  6644. For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position
  6645. on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the
  6646. QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the
  6647. plot coordinate system defined by the axes set by \ref setAxes. By default those are the
  6648. QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available
  6649. coordinate types and their meaning.
  6650. \see setPixelPoint
  6651. */
  6652. void QCPItemPosition::setCoords(double key, double value)
  6653. {
  6654. mKey = key;
  6655. mValue = value;
  6656. }
  6657. /*! \overload
  6658. Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the
  6659. meaning of \a value of the \ref setCoords(double key, double value) method.
  6660. */
  6661. void QCPItemPosition::setCoords(const QPointF &pos)
  6662. {
  6663. setCoords(pos.x(), pos.y());
  6664. }
  6665. /*!
  6666. Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It
  6667. includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor).
  6668. \see setPixelPoint
  6669. */
  6670. QPointF QCPItemPosition::pixelPoint() const
  6671. {
  6672. switch (mPositionType)
  6673. {
  6674. case ptAbsolute:
  6675. {
  6676. if (mParentAnchor)
  6677. return QPointF(mKey, mValue) + mParentAnchor->pixelPoint();
  6678. else
  6679. return QPointF(mKey, mValue);
  6680. }
  6681. case ptViewportRatio:
  6682. {
  6683. if (mParentAnchor)
  6684. {
  6685. return QPointF(mKey*mParentPlot->viewport().width(),
  6686. mValue*mParentPlot->viewport().height()) + mParentAnchor->pixelPoint();
  6687. } else
  6688. {
  6689. return QPointF(mKey*mParentPlot->viewport().width(),
  6690. mValue*mParentPlot->viewport().height()) + mParentPlot->viewport().topLeft();
  6691. }
  6692. }
  6693. case ptAxisRectRatio:
  6694. {
  6695. if (mAxisRect)
  6696. {
  6697. if (mParentAnchor)
  6698. {
  6699. return QPointF(mKey*mAxisRect.data()->width(),
  6700. mValue*mAxisRect.data()->height()) + mParentAnchor->pixelPoint();
  6701. } else
  6702. {
  6703. return QPointF(mKey*mAxisRect.data()->width(),
  6704. mValue*mAxisRect.data()->height()) + mAxisRect.data()->topLeft();
  6705. }
  6706. } else
  6707. {
  6708. qDebug() << Q_FUNC_INFO << "No axis rect defined";
  6709. return QPointF(mKey, mValue);
  6710. }
  6711. }
  6712. case ptPlotCoords:
  6713. {
  6714. double x, y;
  6715. if (mKeyAxis && mValueAxis)
  6716. {
  6717. // both key and value axis are given, translate key/value to x/y coordinates:
  6718. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  6719. {
  6720. x = mKeyAxis.data()->coordToPixel(mKey);
  6721. y = mValueAxis.data()->coordToPixel(mValue);
  6722. } else
  6723. {
  6724. y = mKeyAxis.data()->coordToPixel(mKey);
  6725. x = mValueAxis.data()->coordToPixel(mValue);
  6726. }
  6727. } else if (mKeyAxis)
  6728. {
  6729. // only key axis is given, depending on orientation only transform x or y to key coordinate, other stays pixel:
  6730. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  6731. {
  6732. x = mKeyAxis.data()->coordToPixel(mKey);
  6733. y = mValue;
  6734. } else
  6735. {
  6736. y = mKeyAxis.data()->coordToPixel(mKey);
  6737. x = mValue;
  6738. }
  6739. } else if (mValueAxis)
  6740. {
  6741. // only value axis is given, depending on orientation only transform x or y to value coordinate, other stays pixel:
  6742. if (mValueAxis.data()->orientation() == Qt::Horizontal)
  6743. {
  6744. x = mValueAxis.data()->coordToPixel(mValue);
  6745. y = mKey;
  6746. } else
  6747. {
  6748. y = mValueAxis.data()->coordToPixel(mValue);
  6749. x = mKey;
  6750. }
  6751. } else
  6752. {
  6753. // no axis given, basically the same as if mPositionType were ptAbsolute
  6754. qDebug() << Q_FUNC_INFO << "No axes defined";
  6755. x = mKey;
  6756. y = mValue;
  6757. }
  6758. return QPointF(x, y);
  6759. }
  6760. }
  6761. return QPointF();
  6762. }
  6763. /*!
  6764. When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the
  6765. coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and
  6766. yAxis of the QCustomPlot.
  6767. */
  6768. void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis)
  6769. {
  6770. mKeyAxis = keyAxis;
  6771. mValueAxis = valueAxis;
  6772. }
  6773. /*!
  6774. When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the
  6775. coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of
  6776. the QCustomPlot.
  6777. */
  6778. void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect)
  6779. {
  6780. mAxisRect = axisRect;
  6781. }
  6782. /*!
  6783. Sets the apparent pixel position. This works no matter what type (\ref setType) this
  6784. QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed
  6785. appropriately, to make the position finally appear at the specified pixel values.
  6786. Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is
  6787. identical to that of \ref setCoords.
  6788. \see pixelPoint, setCoords
  6789. */
  6790. void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint)
  6791. {
  6792. switch (mPositionType)
  6793. {
  6794. case ptAbsolute:
  6795. {
  6796. if (mParentAnchor)
  6797. setCoords(pixelPoint-mParentAnchor->pixelPoint());
  6798. else
  6799. setCoords(pixelPoint);
  6800. break;
  6801. }
  6802. case ptViewportRatio:
  6803. {
  6804. if (mParentAnchor)
  6805. {
  6806. QPointF p(pixelPoint-mParentAnchor->pixelPoint());
  6807. p.rx() /= (double)mParentPlot->viewport().width();
  6808. p.ry() /= (double)mParentPlot->viewport().height();
  6809. setCoords(p);
  6810. } else
  6811. {
  6812. QPointF p(pixelPoint-mParentPlot->viewport().topLeft());
  6813. p.rx() /= (double)mParentPlot->viewport().width();
  6814. p.ry() /= (double)mParentPlot->viewport().height();
  6815. setCoords(p);
  6816. }
  6817. break;
  6818. }
  6819. case ptAxisRectRatio:
  6820. {
  6821. if (mAxisRect)
  6822. {
  6823. if (mParentAnchor)
  6824. {
  6825. QPointF p(pixelPoint-mParentAnchor->pixelPoint());
  6826. p.rx() /= (double)mAxisRect.data()->width();
  6827. p.ry() /= (double)mAxisRect.data()->height();
  6828. setCoords(p);
  6829. } else
  6830. {
  6831. QPointF p(pixelPoint-mAxisRect.data()->topLeft());
  6832. p.rx() /= (double)mAxisRect.data()->width();
  6833. p.ry() /= (double)mAxisRect.data()->height();
  6834. setCoords(p);
  6835. }
  6836. } else
  6837. {
  6838. qDebug() << Q_FUNC_INFO << "No axis rect defined";
  6839. setCoords(pixelPoint);
  6840. }
  6841. break;
  6842. }
  6843. case ptPlotCoords:
  6844. {
  6845. double newKey, newValue;
  6846. if (mKeyAxis && mValueAxis)
  6847. {
  6848. // both key and value axis are given, translate point to key/value coordinates:
  6849. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  6850. {
  6851. newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.x());
  6852. newValue = mValueAxis.data()->pixelToCoord(pixelPoint.y());
  6853. } else
  6854. {
  6855. newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.y());
  6856. newValue = mValueAxis.data()->pixelToCoord(pixelPoint.x());
  6857. }
  6858. } else if (mKeyAxis)
  6859. {
  6860. // only key axis is given, depending on orientation only transform x or y to key coordinate, other stays pixel:
  6861. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  6862. {
  6863. newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.x());
  6864. newValue = pixelPoint.y();
  6865. } else
  6866. {
  6867. newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.y());
  6868. newValue = pixelPoint.x();
  6869. }
  6870. } else if (mValueAxis)
  6871. {
  6872. // only value axis is given, depending on orientation only transform x or y to value coordinate, other stays pixel:
  6873. if (mValueAxis.data()->orientation() == Qt::Horizontal)
  6874. {
  6875. newKey = pixelPoint.y();
  6876. newValue = mValueAxis.data()->pixelToCoord(pixelPoint.x());
  6877. } else
  6878. {
  6879. newKey = pixelPoint.x();
  6880. newValue = mValueAxis.data()->pixelToCoord(pixelPoint.y());
  6881. }
  6882. } else
  6883. {
  6884. // no axis given, basically the same as if mPositionType were ptAbsolute
  6885. qDebug() << Q_FUNC_INFO << "No axes defined";
  6886. newKey = pixelPoint.x();
  6887. newValue = pixelPoint.y();
  6888. }
  6889. setCoords(newKey, newValue);
  6890. break;
  6891. }
  6892. }
  6893. }
  6894. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6895. //////////////////// QCPAbstractItem
  6896. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6897. /*! \class QCPAbstractItem
  6898. \brief The abstract base class for all items in a plot.
  6899. In QCustomPlot, items are supplemental graphical elements that are neither plottables
  6900. (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus
  6901. plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each
  6902. specific item has at least one QCPItemPosition member which controls the positioning. Some items
  6903. are defined by more than one coordinate and thus have two or more QCPItemPosition members (For
  6904. example, QCPItemRect has \a topLeft and \a bottomRight).
  6905. This abstract base class defines a very basic interface like visibility and clipping. Since this
  6906. class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass
  6907. yourself to create new items.
  6908. The built-in items are:
  6909. <table>
  6910. <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>
  6911. <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>
  6912. <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>
  6913. <tr><td>QCPItemRect</td><td>A rectangle</td></tr>
  6914. <tr><td>QCPItemEllipse</td><td>An ellipse</td></tr>
  6915. <tr><td>QCPItemPixmap</td><td>An arbitrary pixmap</td></tr>
  6916. <tr><td>QCPItemText</td><td>A text label</td></tr>
  6917. <tr><td>QCPItemBracket</td><td>A bracket which may be used to reference/highlight certain parts in the plot.</td></tr>
  6918. <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>
  6919. </table>
  6920. Items are by default clipped to the main axis rect. To make an item visible outside that axis
  6921. rect, disable clipping via \ref setClipToAxisRect.
  6922. \section items-using Using items
  6923. First you instantiate the item you want to use and add it to the plot:
  6924. \code
  6925. QCPItemLine *line = new QCPItemLine(customPlot);
  6926. customPlot->addItem(line);
  6927. \endcode
  6928. by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just
  6929. set the plot coordinates where the line should start/end:
  6930. \code
  6931. line->start->setCoords(-0.1, 0.8);
  6932. line->end->setCoords(1.1, 0.2);
  6933. \endcode
  6934. If we don't want the line to be positioned in plot coordinates but a different coordinate system,
  6935. e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like this:
  6936. \code
  6937. line->start->setType(QCPItemPosition::ptAbsolute);
  6938. line->end->setType(QCPItemPosition::ptAbsolute);
  6939. \endcode
  6940. Then we can set the coordinates, this time in pixels:
  6941. \code
  6942. line->start->setCoords(100, 200);
  6943. line->end->setCoords(450, 320);
  6944. \endcode
  6945. \section items-subclassing Creating own items
  6946. To create an own item, you implement a subclass of QCPAbstractItem. These are the pure
  6947. virtual functions, you must implement:
  6948. \li \ref selectTest
  6949. \li \ref draw
  6950. See the documentation of those functions for what they need to do.
  6951. \subsection items-positioning Allowing the item to be positioned
  6952. As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall
  6953. have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add
  6954. a public member of type QCPItemPosition like so:
  6955. \code QCPItemPosition * const myPosition;\endcode
  6956. the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition
  6957. instance it points to, can be modified, of course).
  6958. The initialization of this pointer is made easy with the \ref createPosition function. Just assign
  6959. the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition
  6960. takes a string which is the name of the position, typically this is identical to the variable name.
  6961. For example, the constructor of QCPItemExample could look like this:
  6962. \code
  6963. QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) :
  6964. QCPAbstractItem(parentPlot),
  6965. myPosition(createPosition("myPosition"))
  6966. {
  6967. // other constructor code
  6968. }
  6969. \endcode
  6970. \subsection items-drawing The draw function
  6971. To give your item a visual representation, reimplement the \ref draw function and use the passed
  6972. QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the
  6973. position member(s) via \ref QCPItemPosition::pixelPoint.
  6974. To optimize performance you should calculate a bounding rect first (don't forget to take the pen
  6975. width into account), check whether it intersects the \ref clipRect, and only draw the item at all
  6976. if this is the case.
  6977. \subsection items-selection The selectTest function
  6978. Your implementation of the \ref selectTest function may use the helpers \ref distSqrToLine and
  6979. \ref rectSelectTest. With these, the implementation of the selection test becomes significantly
  6980. simpler for most items. See the documentation of \ref selectTest for what the function parameters
  6981. mean and what the function should return.
  6982. \subsection anchors Providing anchors
  6983. Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public
  6984. member, e.g.
  6985. \code QCPItemAnchor * const bottom;\endcode
  6986. and create it in the constructor with the \ref createAnchor function, assigning it a name and an
  6987. anchor id (an integer enumerating all anchors on the item, you may create an own enum for this).
  6988. Since anchors can be placed anywhere, relative to the item's position(s), your item needs to
  6989. provide the position of every anchor with the reimplementation of the \ref anchorPixelPoint(int
  6990. anchorId) function.
  6991. In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel
  6992. position when anything attached to the anchor needs to know the coordinates.
  6993. */
  6994. /* start of documentation of inline functions */
  6995. /*! \fn QList<QCPItemPosition*> QCPAbstractItem::positions() const
  6996. Returns all positions of the item in a list.
  6997. \see anchors, position
  6998. */
  6999. /*! \fn QList<QCPItemAnchor*> QCPAbstractItem::anchors() const
  7000. Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always
  7001. also an anchor, the list will also contain the positions of this item.
  7002. \see positions, anchor
  7003. */
  7004. /* end of documentation of inline functions */
  7005. /* start documentation of pure virtual functions */
  7006. /*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0
  7007. \internal
  7008. Draws this item with the provided \a painter.
  7009. The cliprect of the provided painter is set to the rect returned by \ref clipRect before this
  7010. function is called. The clipRect depends on the clipping settings defined by \ref
  7011. setClipToAxisRect and \ref setClipAxisRect.
  7012. */
  7013. /* end documentation of pure virtual functions */
  7014. /* start documentation of signals */
  7015. /*! \fn void QCPAbstractItem::selectionChanged(bool selected)
  7016. This signal is emitted when the selection state of this item has changed, either by user interaction
  7017. or by a direct call to \ref setSelected.
  7018. */
  7019. /* end documentation of signals */
  7020. /*!
  7021. Base class constructor which initializes base class members.
  7022. */
  7023. QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) :
  7024. QCPLayerable(parentPlot),
  7025. mClipToAxisRect(false),
  7026. mSelectable(true),
  7027. mSelected(false)
  7028. {
  7029. QList<QCPAxisRect*> rects = parentPlot->axisRects();
  7030. if (rects.size() > 0)
  7031. {
  7032. setClipToAxisRect(true);
  7033. setClipAxisRect(rects.first());
  7034. }
  7035. }
  7036. QCPAbstractItem::~QCPAbstractItem()
  7037. {
  7038. // don't delete mPositions because every position is also an anchor and thus in mAnchors
  7039. qDeleteAll(mAnchors);
  7040. }
  7041. /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
  7042. QCPAxisRect *QCPAbstractItem::clipAxisRect() const
  7043. {
  7044. return mClipAxisRect.data();
  7045. }
  7046. /*!
  7047. Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the
  7048. entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect.
  7049. \see setClipAxisRect
  7050. */
  7051. void QCPAbstractItem::setClipToAxisRect(bool clip)
  7052. {
  7053. mClipToAxisRect = clip;
  7054. if (mClipToAxisRect)
  7055. setParentLayerable(mClipAxisRect.data());
  7056. }
  7057. /*!
  7058. Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref
  7059. setClipToAxisRect is set to true.
  7060. \see setClipToAxisRect
  7061. */
  7062. void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect)
  7063. {
  7064. mClipAxisRect = rect;
  7065. if (mClipToAxisRect)
  7066. setParentLayerable(mClipAxisRect.data());
  7067. }
  7068. /*!
  7069. Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface.
  7070. (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.)
  7071. However, even when \a selectable was set to false, it is possible to set the selection manually,
  7072. by calling \ref setSelected.
  7073. \see QCustomPlot::setInteractions, setSelected
  7074. */
  7075. void QCPAbstractItem::setSelectable(bool selectable)
  7076. {
  7077. if (mSelectable != selectable)
  7078. {
  7079. mSelectable = selectable;
  7080. emit selectableChanged(mSelectable);
  7081. }
  7082. }
  7083. /*!
  7084. Sets whether this item is selected or not. When selected, it might use a different visual
  7085. appearance (e.g. pen and brush), this depends on the specific item though.
  7086. The entire selection mechanism for items is handled automatically when \ref
  7087. QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this
  7088. function when you wish to change the selection state manually.
  7089. This function can change the selection state even when \ref setSelectable was set to false.
  7090. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  7091. \see setSelectable, selectTest
  7092. */
  7093. void QCPAbstractItem::setSelected(bool selected)
  7094. {
  7095. if (mSelected != selected)
  7096. {
  7097. mSelected = selected;
  7098. emit selectionChanged(mSelected);
  7099. }
  7100. }
  7101. /*!
  7102. Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by
  7103. that name, returns 0.
  7104. This function provides an alternative way to access item positions. Normally, you access
  7105. positions direcly by their member pointers (which typically have the same variable name as \a
  7106. name).
  7107. \see positions, anchor
  7108. */
  7109. QCPItemPosition *QCPAbstractItem::position(const QString &name) const
  7110. {
  7111. for (int i=0; i<mPositions.size(); ++i)
  7112. {
  7113. if (mPositions.at(i)->name() == name)
  7114. return mPositions.at(i);
  7115. }
  7116. qDebug() << Q_FUNC_INFO << "position with name not found:" << name;
  7117. return 0;
  7118. }
  7119. /*!
  7120. Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by
  7121. that name, returns 0.
  7122. This function provides an alternative way to access item anchors. Normally, you access
  7123. anchors direcly by their member pointers (which typically have the same variable name as \a
  7124. name).
  7125. \see anchors, position
  7126. */
  7127. QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const
  7128. {
  7129. for (int i=0; i<mAnchors.size(); ++i)
  7130. {
  7131. if (mAnchors.at(i)->name() == name)
  7132. return mAnchors.at(i);
  7133. }
  7134. qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name;
  7135. return 0;
  7136. }
  7137. /*!
  7138. Returns whether this item has an anchor with the specified \a name.
  7139. Note that you can check for positions with this function, too. This is because every position is
  7140. also an anchor (QCPItemPosition inherits from QCPItemAnchor).
  7141. \see anchor, position
  7142. */
  7143. bool QCPAbstractItem::hasAnchor(const QString &name) const
  7144. {
  7145. for (int i=0; i<mAnchors.size(); ++i)
  7146. {
  7147. if (mAnchors.at(i)->name() == name)
  7148. return true;
  7149. }
  7150. return false;
  7151. }
  7152. /*! \internal
  7153. Returns the rect the visual representation of this item is clipped to. This depends on the
  7154. current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect.
  7155. If the item is not clipped to an axis rect, the \ref QCustomPlot::viewport rect is returned.
  7156. \see draw
  7157. */
  7158. QRect QCPAbstractItem::clipRect() const
  7159. {
  7160. if (mClipToAxisRect && mClipAxisRect)
  7161. return mClipAxisRect.data()->rect();
  7162. else
  7163. return mParentPlot->viewport();
  7164. }
  7165. /*! \internal
  7166. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  7167. before drawing item lines.
  7168. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  7169. This function takes into account the local setting of the antialiasing flag as well as the
  7170. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  7171. QCustomPlot::setNotAntialiasedElements.
  7172. \see setAntialiased
  7173. */
  7174. void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
  7175. {
  7176. applyAntialiasingHint(painter, mAntialiased, QCP::aeItems);
  7177. }
  7178. /*! \internal
  7179. Finds the shortest squared distance of \a point to the line segment defined by \a start and \a
  7180. end.
  7181. This function may be used to help with the implementation of the \ref selectTest function for
  7182. specific items.
  7183. \note This function is identical to QCPAbstractPlottable::distSqrToLine
  7184. \see rectSelectTest
  7185. */
  7186. double QCPAbstractItem::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const
  7187. {
  7188. QVector2D a(start);
  7189. QVector2D b(end);
  7190. QVector2D p(point);
  7191. QVector2D v(b-a);
  7192. double vLengthSqr = v.lengthSquared();
  7193. if (!qFuzzyIsNull(vLengthSqr))
  7194. {
  7195. double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr;
  7196. if (mu < 0)
  7197. return (a-p).lengthSquared();
  7198. else if (mu > 1)
  7199. return (b-p).lengthSquared();
  7200. else
  7201. return ((a + mu*v)-p).lengthSquared();
  7202. } else
  7203. return (a-p).lengthSquared();
  7204. }
  7205. /*! \internal
  7206. A convenience function which returns the selectTest value for a specified \a rect and a specified
  7207. click position \a pos. \a filledRect defines whether a click inside the rect should also be
  7208. considered a hit or whether only the rect border is sensitive to hits.
  7209. This function may be used to help with the implementation of the \ref selectTest function for
  7210. specific items.
  7211. For example, if your item consists of four rects, call this function four times, once for each
  7212. rect, in your \ref selectTest reimplementation. Finally, return the minimum of all four returned
  7213. values which were greater or equal to zero. (Because this function may return -1.0 when \a pos
  7214. doesn't hit \a rect at all). If all calls returned -1.0, return -1.0, too, because your item
  7215. wasn't hit.
  7216. \see distSqrToLine
  7217. */
  7218. double QCPAbstractItem::rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const
  7219. {
  7220. double result = -1;
  7221. // distance to border:
  7222. QList<QLineF> lines;
  7223. lines << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight())
  7224. << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight());
  7225. double minDistSqr = std::numeric_limits<double>::max();
  7226. for (int i=0; i<lines.size(); ++i)
  7227. {
  7228. double distSqr = distSqrToLine(lines.at(i).p1(), lines.at(i).p2(), pos);
  7229. if (distSqr < minDistSqr)
  7230. minDistSqr = distSqr;
  7231. }
  7232. result = qSqrt(minDistSqr);
  7233. // filled rect, allow click inside to count as hit:
  7234. if (filledRect && result > mParentPlot->selectionTolerance()*0.99)
  7235. {
  7236. if (rect.contains(pos))
  7237. result = mParentPlot->selectionTolerance()*0.99;
  7238. }
  7239. return result;
  7240. }
  7241. /*! \internal
  7242. Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in
  7243. item subclasses if they want to provide anchors (QCPItemAnchor).
  7244. For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor
  7245. ids and returns the respective pixel points of the specified anchor.
  7246. \see createAnchor
  7247. */
  7248. QPointF QCPAbstractItem::anchorPixelPoint(int anchorId) const
  7249. {
  7250. qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId;
  7251. return QPointF();
  7252. }
  7253. /*! \internal
  7254. Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified
  7255. \a name must be a unique string that is usually identical to the variable name of the position
  7256. member (This is needed to provide the name-based \ref position access to positions).
  7257. Don't delete positions created by this function manually, as the item will take care of it.
  7258. Use this function in the constructor (initialization list) of the specific item subclass to
  7259. create each position member. Don't create QCPItemPositions with \b new yourself, because they
  7260. won't be registered with the item properly.
  7261. \see createAnchor
  7262. */
  7263. QCPItemPosition *QCPAbstractItem::createPosition(const QString &name)
  7264. {
  7265. if (hasAnchor(name))
  7266. qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
  7267. QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name);
  7268. mPositions.append(newPosition);
  7269. mAnchors.append(newPosition); // every position is also an anchor
  7270. newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis);
  7271. newPosition->setType(QCPItemPosition::ptPlotCoords);
  7272. if (mParentPlot->axisRect())
  7273. newPosition->setAxisRect(mParentPlot->axisRect());
  7274. newPosition->setCoords(0, 0);
  7275. return newPosition;
  7276. }
  7277. /*! \internal
  7278. Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified
  7279. \a name must be a unique string that is usually identical to the variable name of the anchor
  7280. member (This is needed to provide the name based \ref anchor access to anchors).
  7281. The \a anchorId must be a number identifying the created anchor. It is recommended to create an
  7282. enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor
  7283. to identify itself when it calls QCPAbstractItem::anchorPixelPoint. That function then returns
  7284. the correct pixel coordinates for the passed anchor id.
  7285. Don't delete anchors created by this function manually, as the item will take care of it.
  7286. Use this function in the constructor (initialization list) of the specific item subclass to
  7287. create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they
  7288. won't be registered with the item properly.
  7289. \see createPosition
  7290. */
  7291. QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId)
  7292. {
  7293. if (hasAnchor(name))
  7294. qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
  7295. QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId);
  7296. mAnchors.append(newAnchor);
  7297. return newAnchor;
  7298. }
  7299. /* inherits documentation from base class */
  7300. void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  7301. {
  7302. Q_UNUSED(event)
  7303. Q_UNUSED(details)
  7304. if (mSelectable)
  7305. {
  7306. bool selBefore = mSelected;
  7307. setSelected(additive ? !mSelected : true);
  7308. if (selectionStateChanged)
  7309. *selectionStateChanged = mSelected != selBefore;
  7310. }
  7311. }
  7312. /* inherits documentation from base class */
  7313. void QCPAbstractItem::deselectEvent(bool *selectionStateChanged)
  7314. {
  7315. if (mSelectable)
  7316. {
  7317. bool selBefore = mSelected;
  7318. setSelected(false);
  7319. if (selectionStateChanged)
  7320. *selectionStateChanged = mSelected != selBefore;
  7321. }
  7322. }
  7323. /* inherits documentation from base class */
  7324. QCP::Interaction QCPAbstractItem::selectionCategory() const
  7325. {
  7326. return QCP::iSelectItems;
  7327. }
  7328. /*! \file */
  7329. /*! \mainpage %QCustomPlot 1.2.1 Documentation
  7330. \image html qcp-doc-logo.png
  7331. Below is a brief overview of and guide to the classes and their relations. If you are new to
  7332. QCustomPlot and just want to start using it, it's recommended to look at the tutorials and
  7333. examples at
  7334. http://www.qcustomplot.com/
  7335. This documentation is especially helpful as a reference, when you're familiar with the basic
  7336. concept of how to use %QCustomPlot and you wish to learn more about specific functionality.
  7337. See the \ref classoverview "class overview" for diagrams explaining the relationships between
  7338. the most important classes of the QCustomPlot library.
  7339. The central widget which displays the plottables and axes on its surface is QCustomPlot. Every
  7340. QCustomPlot contains four axes by default. They can be accessed via the members \ref
  7341. QCustomPlot::xAxis "xAxis", \ref QCustomPlot::yAxis "yAxis", \ref QCustomPlot::xAxis2 "xAxis2"
  7342. and \ref QCustomPlot::yAxis2 "yAxis2", and are of type QCPAxis. QCustomPlot supports an arbitrary
  7343. number of axes and axis rects, see the documentation of QCPAxisRect for details.
  7344. \section mainpage-plottables Plottables
  7345. \a Plottables are classes that display any kind of data inside the QCustomPlot. They all derive
  7346. from QCPAbstractPlottable. For example, the QCPGraph class is a plottable that displays a graph
  7347. inside the plot with different line styles, scatter styles, filling etc.
  7348. Since plotting graphs is such a dominant use case, QCustomPlot has a special interface for working
  7349. with QCPGraph plottables, that makes it very easy to handle them:\n
  7350. You create a new graph with QCustomPlot::addGraph and access them with QCustomPlot::graph.
  7351. For all other plottables, you need to use the normal plottable interface:\n
  7352. First, you create an instance of the plottable you want, e.g.
  7353. \code
  7354. QCPCurve *newCurve = new QCPCurve(customPlot->xAxis, customPlot->yAxis);\endcode
  7355. add it to the customPlot:
  7356. \code
  7357. customPlot->addPlottable(newCurve);\endcode
  7358. and then modify the properties of the newly created plottable via the <tt>newCurve</tt> pointer.
  7359. Plottables (including graphs) can be retrieved via QCustomPlot::plottable. Since the return type
  7360. of that function is the abstract base class of all plottables, QCPAbstractPlottable, you will
  7361. probably want to qobject_cast the returned pointer to the respective plottable subclass. (As
  7362. usual, if the cast returns zero, the plottable wasn't of that specific subclass.)
  7363. All further interfacing with plottables (e.g how to set data) is specific to the plottable type.
  7364. See the documentations of the subclasses: QCPGraph, QCPCurve, QCPBars, QCPStatisticalBox,
  7365. QCPColorMap.
  7366. \section mainpage-axes Controlling the Axes
  7367. As mentioned, QCustomPlot has four axes by default: \a xAxis (bottom), \a yAxis (left), \a xAxis2
  7368. (top), \a yAxis2 (right).
  7369. Their range is handled by the simple QCPRange class. You can set the range with the
  7370. QCPAxis::setRange function. By default, the axes represent a linear scale. To set a logarithmic
  7371. scale, set \ref QCPAxis::setScaleType to \ref QCPAxis::stLogarithmic. The logarithm base can be set freely
  7372. with \ref QCPAxis::setScaleLogBase.
  7373. By default, an axis automatically creates and labels ticks in a sensible manner. See the
  7374. following functions for tick manipulation:\n QCPAxis::setTicks, QCPAxis::setAutoTicks,
  7375. QCPAxis::setAutoTickCount, QCPAxis::setAutoTickStep, QCPAxis::setTickLabels,
  7376. QCPAxis::setTickLabelType, QCPAxis::setTickLabelRotation, QCPAxis::setTickStep,
  7377. QCPAxis::setTickLength,...
  7378. Each axis can be given an axis label (e.g. "Voltage (mV)") with QCPAxis::setLabel.
  7379. The distance of an axis backbone to the respective viewport border is called its margin.
  7380. Normally, the margins are calculated automatically. To change this, set
  7381. \ref QCPAxisRect::setAutoMargins to exclude the respective margin sides, set the margins manually with
  7382. \ref QCPAxisRect::setMargins. The main axis rect can be reached with \ref QCustomPlot::axisRect().
  7383. \section mainpage-legend Plot Legend
  7384. Every QCustomPlot has one QCPLegend (as \ref QCustomPlot::legend) by default. A legend is a small
  7385. layout element inside the plot which lists the plottables with an icon of the plottable
  7386. line/symbol and a name (QCPAbstractPlottable::setName). Plottables can be added and removed from
  7387. the main legend via \ref QCPAbstractPlottable::addToLegend and \ref
  7388. QCPAbstractPlottable::removeFromLegend. By default, adding a plottable to QCustomPlot
  7389. automatically adds it to the legend, too. This behaviour can be modified with the
  7390. QCustomPlot::setAutoAddPlottableToLegend property.
  7391. The QCPLegend provides an interface to access, add and remove legend items directly, too. See
  7392. QCPLegend::item, QCPLegend::itemWithPlottable, QCPLegend::addItem, QCPLegend::removeItem for
  7393. example.
  7394. Multiple legends are supported via the \link thelayoutsystem layout system\endlink (as a
  7395. QCPLegend simply is a normal layout element).
  7396. \section mainpage-userinteraction User Interactions
  7397. QCustomPlot supports dragging axis ranges with the mouse (\ref
  7398. QCPAxisRect::setRangeDrag), zooming axis ranges with the mouse wheel (\ref
  7399. QCPAxisRect::setRangeZoom) and a complete selection mechanism.
  7400. The availability of these interactions is controlled with \ref QCustomPlot::setInteractions. For
  7401. details about the interaction system, see the documentation there.
  7402. Further, QCustomPlot always emits corresponding signals, when objects are clicked or
  7403. doubleClicked. See \ref QCustomPlot::plottableClick, \ref QCustomPlot::plottableDoubleClick
  7404. and \ref QCustomPlot::axisClick for example.
  7405. \section mainpage-items Items
  7406. Apart from plottables there is another category of plot objects that are important: Items. The
  7407. base class of all items is QCPAbstractItem. An item sets itself apart from plottables in that
  7408. it's not necessarily bound to any axes. This means it may also be positioned in absolute pixel
  7409. coordinates or placed at a relative position on an axis rect. Further, it usually doesn't
  7410. represent data directly, but acts as decoration, emphasis, description etc.
  7411. Multiple items can be arranged in a parent-child-hierarchy allowing for dynamical behaviour. For
  7412. example, you could place the head of an arrow at a fixed plot coordinate, so it always points to
  7413. some important area in the plot. The tail of the arrow can be anchored to a text item which
  7414. always resides in the top center of the axis rect, independent of where the user drags the axis
  7415. ranges. This way the arrow stretches and turns so it always points from the label to the
  7416. specified plot coordinate, without any further code necessary.
  7417. For a more detailed introduction, see the QCPAbstractItem documentation, and from there the
  7418. documentations of the individual built-in items, to find out how to use them.
  7419. \section mainpage-layoutelements Layout elements and layouts
  7420. QCustomPlot uses an internal layout system to provide dynamic sizing and positioning of objects like
  7421. the axis rect(s), legends and the plot title. They are all based on \ref QCPLayoutElement and are arranged by
  7422. placing them inside a \ref QCPLayout.
  7423. Details on this topic are given on the dedicated page about \link thelayoutsystem the layout system\endlink.
  7424. \section mainpage-performancetweaks Performance Tweaks
  7425. Although QCustomPlot is quite fast, some features like translucent fills, antialiasing and thick
  7426. lines can cause a significant slow down. If you notice this in your application, here are some
  7427. thoughts on how to increase performance. By far the most time is spent in the drawing functions,
  7428. specifically the drawing of graphs. For maximum performance, consider the following (most
  7429. recommended/effective measures first):
  7430. \li use Qt 4.8.0 and up. Performance has doubled or tripled with respect to Qt 4.7.4. However
  7431. QPainter was broken and drawing pixel precise things, e.g. scatters, isn't possible with Qt >=
  7432. 4.8.0. So it's a performance vs. plot quality tradeoff when switching to Qt 4.8.
  7433. \li To increase responsiveness during dragging, consider setting \ref QCustomPlot::setNoAntialiasingOnDrag to true.
  7434. \li On X11 (GNU/Linux), avoid the slow native drawing system, use raster by supplying
  7435. "-graphicssystem raster" as command line argument or calling QApplication::setGraphicsSystem("raster")
  7436. before creating the QApplication object. (Only available for Qt versions before 5.0)
  7437. \li On all operating systems, use OpenGL hardware acceleration by supplying "-graphicssystem
  7438. opengl" as command line argument or calling QApplication::setGraphicsSystem("opengl") (Only
  7439. available for Qt versions before 5.0). If OpenGL is available, this will slightly decrease the
  7440. quality of antialiasing, but extremely increase performance especially with alpha
  7441. (semi-transparent) fills, much antialiasing and a large QCustomPlot drawing surface. Note
  7442. however, that the maximum frame rate might be constrained by the vertical sync frequency of your
  7443. monitor (VSync can be disabled in the graphics card driver configuration). So for simple plots
  7444. (where the potential framerate is far above 60 frames per second), OpenGL acceleration might
  7445. achieve numerically lower frame rates than the other graphics systems, because they are not
  7446. capped at the VSync frequency.
  7447. \li Avoid any kind of alpha (transparency), especially in fills
  7448. \li Avoid lines with a pen width greater than one
  7449. \li Avoid any kind of antialiasing, especially in graph lines (see \ref QCustomPlot::setNotAntialiasedElements)
  7450. \li Avoid repeatedly setting the complete data set with \ref QCPGraph::setData. Use \ref QCPGraph::addData instead, if most
  7451. data points stay unchanged, e.g. in a running measurement.
  7452. \li Set the \a copy parameter of the setData functions to false, so only pointers get
  7453. transferred. (Relevant only if preparing data maps with a large number of points, i.e. over 10000)
  7454. \section mainpage-flags Preprocessor Define Flags
  7455. QCustomPlot understands some preprocessor defines that are useful for debugging and compilation:
  7456. <dl>
  7457. <dt>\c QCUSTOMPLOT_COMPILE_LIBRARY
  7458. <dd>Define this flag when you compile QCustomPlot as a shared library (.so/.dll)
  7459. <dt>\c QCUSTOMPLOT_USE_LIBRARY
  7460. <dd>Define this flag before including the header, when using QCustomPlot as a shared library
  7461. <dt>\c QCUSTOMPLOT_CHECK_DATA
  7462. <dd>If this flag is defined, the QCustomPlot plottables will perform data validity checks on every redraw.
  7463. This means they will give qDebug output when you plot \e inf or \e nan values, they will not
  7464. fix your data.
  7465. </dl>
  7466. */
  7467. /*! \page classoverview Class Overview
  7468. The following diagrams may help to gain a deeper understanding of the relationships between classes that make up
  7469. the QCustomPlot library. The diagrams are not exhaustive, so only the classes deemed most relevant are shown.
  7470. \section classoverview-relations Class Relationship Diagram
  7471. \image html RelationOverview.png "Overview of most important classes and their relations"
  7472. \section classoverview-inheritance Class Inheritance Tree
  7473. \image html InheritanceOverview.png "Inheritance tree of most important classes"
  7474. */
  7475. ////////////////////////////////////////////////////////////////////////////////////////////////////
  7476. //////////////////// QCustomPlot
  7477. ////////////////////////////////////////////////////////////////////////////////////////////////////
  7478. /*! \class QCustomPlot
  7479. \brief The central class of the library. This is the QWidget which displays the plot and
  7480. interacts with the user.
  7481. For tutorials on how to use QCustomPlot, see the website\n
  7482. http://www.qcustomplot.com/
  7483. */
  7484. /* start of documentation of inline functions */
  7485. /*! \fn QRect QCustomPlot::viewport() const
  7486. Returns the viewport rect of this QCustomPlot instance. The viewport is the area the plot is
  7487. drawn in, all mechanisms, e.g. margin caluclation take the viewport to be the outer border of the
  7488. plot. The viewport normally is the rect() of the QCustomPlot widget, i.e. a rect with top left
  7489. (0, 0) and size of the QCustomPlot widget.
  7490. Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically
  7491. an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger
  7492. and contains also the axes themselves, their tick numbers, their labels, the plot title etc.
  7493. Only when saving to a file (see \ref savePng, savePdf etc.) the viewport is temporarily modified
  7494. to allow saving plots with sizes independent of the current widget size.
  7495. */
  7496. /*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const
  7497. Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just
  7498. one cell with the main QCPAxisRect inside.
  7499. */
  7500. /* end of documentation of inline functions */
  7501. /* start of documentation of signals */
  7502. /*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event)
  7503. This signal is emitted when the QCustomPlot receives a mouse double click event.
  7504. */
  7505. /*! \fn void QCustomPlot::mousePress(QMouseEvent *event)
  7506. This signal is emitted when the QCustomPlot receives a mouse press event.
  7507. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
  7508. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
  7509. QCPAxisRect::setRangeDragAxes.
  7510. */
  7511. /*! \fn void QCustomPlot::mouseMove(QMouseEvent *event)
  7512. This signal is emitted when the QCustomPlot receives a mouse move event.
  7513. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
  7514. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
  7515. QCPAxisRect::setRangeDragAxes.
  7516. \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here,
  7517. because the dragging starting point was saved the moment the mouse was pressed. Thus it only has
  7518. a meaning for the range drag axes that were set at that moment. If you want to change the drag
  7519. axes, consider doing this in the \ref mousePress signal instead.
  7520. */
  7521. /*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event)
  7522. This signal is emitted when the QCustomPlot receives a mouse release event.
  7523. It is emitted before QCustomPlot handles any other mechanisms like object selection. So a
  7524. slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or
  7525. \ref QCPAbstractPlottable::setSelectable.
  7526. */
  7527. /*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event)
  7528. This signal is emitted when the QCustomPlot receives a mouse wheel event.
  7529. It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot
  7530. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref
  7531. QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor.
  7532. */
  7533. /*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event)
  7534. This signal is emitted when a plottable is clicked.
  7535. \a event is the mouse event that caused the click and \a plottable is the plottable that received
  7536. the click.
  7537. \see plottableDoubleClick
  7538. */
  7539. /*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event)
  7540. This signal is emitted when a plottable is double clicked.
  7541. \a event is the mouse event that caused the click and \a plottable is the plottable that received
  7542. the click.
  7543. \see plottableClick
  7544. */
  7545. /*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event)
  7546. This signal is emitted when an item is clicked.
  7547. \a event is the mouse event that caused the click and \a item is the item that received the
  7548. click.
  7549. \see itemDoubleClick
  7550. */
  7551. /*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event)
  7552. This signal is emitted when an item is double clicked.
  7553. \a event is the mouse event that caused the click and \a item is the item that received the
  7554. click.
  7555. \see itemClick
  7556. */
  7557. /*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
  7558. This signal is emitted when an axis is clicked.
  7559. \a event is the mouse event that caused the click, \a axis is the axis that received the click and
  7560. \a part indicates the part of the axis that was clicked.
  7561. \see axisDoubleClick
  7562. */
  7563. /*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
  7564. This signal is emitted when an axis is double clicked.
  7565. \a event is the mouse event that caused the click, \a axis is the axis that received the click and
  7566. \a part indicates the part of the axis that was clicked.
  7567. \see axisClick
  7568. */
  7569. /*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
  7570. This signal is emitted when a legend (item) is clicked.
  7571. \a event is the mouse event that caused the click, \a legend is the legend that received the
  7572. click and \a item is the legend item that received the click. If only the legend and no item is
  7573. clicked, \a item is 0. This happens for a click inside the legend padding or the space between
  7574. two items.
  7575. \see legendDoubleClick
  7576. */
  7577. /*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
  7578. This signal is emitted when a legend (item) is double clicked.
  7579. \a event is the mouse event that caused the click, \a legend is the legend that received the
  7580. click and \a item is the legend item that received the click. If only the legend and no item is
  7581. clicked, \a item is 0. This happens for a click inside the legend padding or the space between
  7582. two items.
  7583. \see legendClick
  7584. */
  7585. /*! \fn void QCustomPlot:: titleClick(QMouseEvent *event, QCPPlotTitle *title)
  7586. This signal is emitted when a plot title is clicked.
  7587. \a event is the mouse event that caused the click and \a title is the plot title that received
  7588. the click.
  7589. \see titleDoubleClick
  7590. */
  7591. /*! \fn void QCustomPlot::titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title)
  7592. This signal is emitted when a plot title is double clicked.
  7593. \a event is the mouse event that caused the click and \a title is the plot title that received
  7594. the click.
  7595. \see titleClick
  7596. */
  7597. /*! \fn void QCustomPlot::selectionChangedByUser()
  7598. This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by
  7599. clicking. It is not emitted when the selection state of an object has changed programmatically by
  7600. a direct call to setSelected() on an object or by calling \ref deselectAll.
  7601. In addition to this signal, selectable objects also provide individual signals, for example
  7602. QCPAxis::selectionChanged or QCPAbstractPlottable::selectionChanged. Note that those signals are
  7603. emitted even if the selection state is changed programmatically.
  7604. See the documentation of \ref setInteractions for details about the selection mechanism.
  7605. \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends
  7606. */
  7607. /*! \fn void QCustomPlot::beforeReplot()
  7608. This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref
  7609. replot).
  7610. It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
  7611. replot synchronously, it won't cause an infinite recursion.
  7612. \see replot, afterReplot
  7613. */
  7614. /*! \fn void QCustomPlot::afterReplot()
  7615. This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref
  7616. replot).
  7617. It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
  7618. replot synchronously, it won't cause an infinite recursion.
  7619. \see replot, beforeReplot
  7620. */
  7621. /* end of documentation of signals */
  7622. /* start of documentation of public members */
  7623. /*! \var QCPAxis *QCustomPlot::xAxis
  7624. A pointer to the primary x Axis (bottom) of the main axis rect of the plot.
  7625. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  7626. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  7627. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  7628. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  7629. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  7630. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  7631. axis rect), the corresponding pointers become 0.
  7632. */
  7633. /*! \var QCPAxis *QCustomPlot::yAxis
  7634. A pointer to the primary y Axis (left) of the main axis rect of the plot.
  7635. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  7636. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  7637. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  7638. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  7639. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  7640. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  7641. axis rect), the corresponding pointers become 0.
  7642. */
  7643. /*! \var QCPAxis *QCustomPlot::xAxis2
  7644. A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are
  7645. invisible by default. Use QCPAxis::setVisible to change this (or use \ref
  7646. QCPAxisRect::setupFullAxesBox).
  7647. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  7648. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  7649. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  7650. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  7651. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  7652. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  7653. axis rect), the corresponding pointers become 0.
  7654. */
  7655. /*! \var QCPAxis *QCustomPlot::yAxis2
  7656. A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are
  7657. invisible by default. Use QCPAxis::setVisible to change this (or use \ref
  7658. QCPAxisRect::setupFullAxesBox).
  7659. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  7660. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  7661. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  7662. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  7663. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  7664. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  7665. axis rect), the corresponding pointers become 0.
  7666. */
  7667. /*! \var QCPLegend *QCustomPlot::legend
  7668. A pointer to the default legend of the main axis rect. The legend is invisible by default. Use
  7669. QCPLegend::setVisible to change this.
  7670. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  7671. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  7672. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  7673. layout system\endlink to add multiple legends to the plot, use the layout system interface to
  7674. access the new legend. For example, legends can be placed inside an axis rect's \ref
  7675. QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If
  7676. the default legend is removed due to manipulation of the layout system (e.g. by removing the main
  7677. axis rect), the corresponding pointer becomes 0.
  7678. */
  7679. /* end of documentation of public members */
  7680. /*!
  7681. Constructs a QCustomPlot and sets reasonable default values.
  7682. */
  7683. QCustomPlot::QCustomPlot(QWidget *parent) :
  7684. QWidget(parent),
  7685. xAxis(0),
  7686. yAxis(0),
  7687. xAxis2(0),
  7688. yAxis2(0),
  7689. legend(0),
  7690. mPlotLayout(0),
  7691. mAutoAddPlottableToLegend(true),
  7692. mAntialiasedElements(QCP::aeNone),
  7693. mNotAntialiasedElements(QCP::aeNone),
  7694. mInteractions(0),
  7695. mSelectionTolerance(8),
  7696. mNoAntialiasingOnDrag(false),
  7697. mBackgroundBrush(Qt::white, Qt::SolidPattern),
  7698. mBackgroundScaled(true),
  7699. mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
  7700. mCurrentLayer(0),
  7701. mPlottingHints(QCP::phCacheLabels|QCP::phForceRepaint),
  7702. mMultiSelectModifier(Qt::ControlModifier),
  7703. mPaintBuffer(size()),
  7704. mMouseEventElement(0),
  7705. mReplotting(false)
  7706. {
  7707. setAttribute(Qt::WA_NoMousePropagation);
  7708. setAttribute(Qt::WA_OpaquePaintEvent);
  7709. setMouseTracking(true);
  7710. QLocale currentLocale = locale();
  7711. currentLocale.setNumberOptions(QLocale::OmitGroupSeparator);
  7712. setLocale(currentLocale);
  7713. // create initial layers:
  7714. mLayers.append(new QCPLayer(this, "background"));
  7715. mLayers.append(new QCPLayer(this, "grid"));
  7716. mLayers.append(new QCPLayer(this, "main"));
  7717. mLayers.append(new QCPLayer(this, "axes"));
  7718. mLayers.append(new QCPLayer(this, "legend"));
  7719. updateLayerIndices();
  7720. setCurrentLayer("main");
  7721. // create initial layout, axis rect and legend:
  7722. mPlotLayout = new QCPLayoutGrid;
  7723. mPlotLayout->initializeParentPlot(this);
  7724. mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry
  7725. mPlotLayout->setLayer("main");
  7726. QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true);
  7727. mPlotLayout->addElement(0, 0, defaultAxisRect);
  7728. xAxis = defaultAxisRect->axis(QCPAxis::atBottom);
  7729. yAxis = defaultAxisRect->axis(QCPAxis::atLeft);
  7730. xAxis2 = defaultAxisRect->axis(QCPAxis::atTop);
  7731. yAxis2 = defaultAxisRect->axis(QCPAxis::atRight);
  7732. legend = new QCPLegend;
  7733. legend->setVisible(false);
  7734. defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop);
  7735. defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12));
  7736. defaultAxisRect->setLayer("background");
  7737. xAxis->setLayer("axes");
  7738. yAxis->setLayer("axes");
  7739. xAxis2->setLayer("axes");
  7740. yAxis2->setLayer("axes");
  7741. xAxis->grid()->setLayer("grid");
  7742. yAxis->grid()->setLayer("grid");
  7743. xAxis2->grid()->setLayer("grid");
  7744. yAxis2->grid()->setLayer("grid");
  7745. legend->setLayer("legend");
  7746. setViewport(rect()); // needs to be called after mPlotLayout has been created
  7747. replot();
  7748. }
  7749. QCustomPlot::~QCustomPlot()
  7750. {
  7751. clearPlottables();
  7752. clearItems();
  7753. if (mPlotLayout)
  7754. {
  7755. delete mPlotLayout;
  7756. mPlotLayout = 0;
  7757. }
  7758. mCurrentLayer = 0;
  7759. qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed
  7760. mLayers.clear();
  7761. }
  7762. /*!
  7763. Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement.
  7764. This overrides the antialiasing settings for whole element groups, normally controlled with the
  7765. \a setAntialiasing function on the individual elements. If an element is neither specified in
  7766. \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
  7767. each individual element instance is used.
  7768. For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be
  7769. drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
  7770. to.
  7771. if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is
  7772. removed from there.
  7773. \see setNotAntialiasedElements
  7774. */
  7775. void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements)
  7776. {
  7777. mAntialiasedElements = antialiasedElements;
  7778. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  7779. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  7780. mNotAntialiasedElements |= ~mAntialiasedElements;
  7781. }
  7782. /*!
  7783. Sets whether the specified \a antialiasedElement is forcibly drawn antialiased.
  7784. See \ref setAntialiasedElements for details.
  7785. \see setNotAntialiasedElement
  7786. */
  7787. void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled)
  7788. {
  7789. if (!enabled && mAntialiasedElements.testFlag(antialiasedElement))
  7790. mAntialiasedElements &= ~antialiasedElement;
  7791. else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement))
  7792. mAntialiasedElements |= antialiasedElement;
  7793. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  7794. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  7795. mNotAntialiasedElements |= ~mAntialiasedElements;
  7796. }
  7797. /*!
  7798. Sets which elements are forcibly drawn not antialiased as an \a or combination of
  7799. QCP::AntialiasedElement.
  7800. This overrides the antialiasing settings for whole element groups, normally controlled with the
  7801. \a setAntialiasing function on the individual elements. If an element is neither specified in
  7802. \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
  7803. each individual element instance is used.
  7804. For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be
  7805. drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
  7806. to.
  7807. if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is
  7808. removed from there.
  7809. \see setAntialiasedElements
  7810. */
  7811. void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements &notAntialiasedElements)
  7812. {
  7813. mNotAntialiasedElements = notAntialiasedElements;
  7814. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  7815. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  7816. mAntialiasedElements |= ~mNotAntialiasedElements;
  7817. }
  7818. /*!
  7819. Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased.
  7820. See \ref setNotAntialiasedElements for details.
  7821. \see setAntialiasedElement
  7822. */
  7823. void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled)
  7824. {
  7825. if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement))
  7826. mNotAntialiasedElements &= ~notAntialiasedElement;
  7827. else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement))
  7828. mNotAntialiasedElements |= notAntialiasedElement;
  7829. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  7830. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  7831. mAntialiasedElements |= ~mNotAntialiasedElements;
  7832. }
  7833. /*!
  7834. If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the
  7835. plottable to the legend (QCustomPlot::legend).
  7836. \see addPlottable, addGraph, QCPLegend::addItem
  7837. */
  7838. void QCustomPlot::setAutoAddPlottableToLegend(bool on)
  7839. {
  7840. mAutoAddPlottableToLegend = on;
  7841. }
  7842. /*!
  7843. Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction
  7844. enums. There are the following types of interactions:
  7845. <b>Axis range manipulation</b> is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the
  7846. respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel.
  7847. For details how to control which axes the user may drag/zoom and in what orientations, see \ref
  7848. QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes,
  7849. \ref QCPAxisRect::setRangeZoomAxes.
  7850. <b>Plottable selection</b> is controlled by \ref QCP::iSelectPlottables. If \ref QCP::iSelectPlottables is
  7851. set, the user may select plottables (graphs, curves, bars,...) by clicking on them or in their
  7852. vicinity (\ref setSelectionTolerance). Whether the user can actually select a plottable can
  7853. further be restricted with the \ref QCPAbstractPlottable::setSelectable function on the specific
  7854. plottable. To find out whether a specific plottable is selected, call
  7855. QCPAbstractPlottable::selected(). To retrieve a list of all currently selected plottables, call
  7856. \ref selectedPlottables. If you're only interested in QCPGraphs, you may use the convenience
  7857. function \ref selectedGraphs.
  7858. <b>Item selection</b> is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user
  7859. may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find
  7860. out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of
  7861. all currently selected items, call \ref selectedItems.
  7862. <b>Axis selection</b> is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user
  7863. may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick
  7864. labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for
  7865. each axis. To retrieve a list of all axes that currently contain selected parts, call \ref
  7866. selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts().
  7867. <b>Legend selection</b> is controlled with \ref QCP::iSelectLegend. If this is set, the user may
  7868. select the legend itself or individual items by clicking on them. What parts exactly are
  7869. selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the
  7870. legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To
  7871. find out which child items are selected, call \ref QCPLegend::selectedItems.
  7872. <b>All other selectable elements</b> The selection of all other selectable objects (e.g.
  7873. QCPPlotTitle, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the
  7874. user may select those objects by clicking on them. To find out which are currently selected, you
  7875. need to check their selected state explicitly.
  7876. If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is
  7877. emitted. Each selectable object additionally emits an individual selectionChanged signal whenever
  7878. their selection state has changed, i.e. not only by user interaction.
  7879. To allow multiple objects to be selected by holding the selection modifier (\ref
  7880. setMultiSelectModifier), set the flag \ref QCP::iMultiSelect.
  7881. \note In addition to the selection mechanism presented here, QCustomPlot always emits
  7882. corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and
  7883. \ref plottableDoubleClick for example.
  7884. \see setInteraction, setSelectionTolerance
  7885. */
  7886. void QCustomPlot::setInteractions(const QCP::Interactions &interactions)
  7887. {
  7888. mInteractions = interactions;
  7889. }
  7890. /*!
  7891. Sets the single \a interaction of this QCustomPlot to \a enabled.
  7892. For details about the interaction system, see \ref setInteractions.
  7893. \see setInteractions
  7894. */
  7895. void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled)
  7896. {
  7897. if (!enabled && mInteractions.testFlag(interaction))
  7898. mInteractions &= ~interaction;
  7899. else if (enabled && !mInteractions.testFlag(interaction))
  7900. mInteractions |= interaction;
  7901. }
  7902. /*!
  7903. Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or
  7904. not.
  7905. If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a
  7906. potential selection when the minimum distance between the click position and the graph line is
  7907. smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks
  7908. directly inside the area and ignore this selection tolerance. In other words, it only has meaning
  7909. for parts of objects that are too thin to exactly hit with a click and thus need such a
  7910. tolerance.
  7911. \see setInteractions, QCPLayerable::selectTest
  7912. */
  7913. void QCustomPlot::setSelectionTolerance(int pixels)
  7914. {
  7915. mSelectionTolerance = pixels;
  7916. }
  7917. /*!
  7918. Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes
  7919. ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves
  7920. performance during dragging. Thus it creates a more responsive user experience. As soon as the
  7921. user stops dragging, the last replot is done with normal antialiasing, to restore high image
  7922. quality.
  7923. \see setAntialiasedElements, setNotAntialiasedElements
  7924. */
  7925. void QCustomPlot::setNoAntialiasingOnDrag(bool enabled)
  7926. {
  7927. mNoAntialiasingOnDrag = enabled;
  7928. }
  7929. /*!
  7930. Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint.
  7931. \see setPlottingHint
  7932. */
  7933. void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints)
  7934. {
  7935. mPlottingHints = hints;
  7936. }
  7937. /*!
  7938. Sets the specified plotting \a hint to \a enabled.
  7939. \see setPlottingHints
  7940. */
  7941. void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled)
  7942. {
  7943. QCP::PlottingHints newHints = mPlottingHints;
  7944. if (!enabled)
  7945. newHints &= ~hint;
  7946. else
  7947. newHints |= hint;
  7948. if (newHints != mPlottingHints)
  7949. setPlottingHints(newHints);
  7950. }
  7951. /*!
  7952. Sets the keyboard modifier that will be recognized as multi-select-modifier.
  7953. If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple objects
  7954. by clicking on them one after the other while holding down \a modifier.
  7955. By default the multi-select-modifier is set to Qt::ControlModifier.
  7956. \see setInteractions
  7957. */
  7958. void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier)
  7959. {
  7960. mMultiSelectModifier = modifier;
  7961. }
  7962. /*!
  7963. Sets the viewport of this QCustomPlot. The Viewport is the area that the top level layout
  7964. (QCustomPlot::plotLayout()) uses as its rect. Normally, the viewport is the entire widget rect.
  7965. This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref
  7966. savePdf, etc. by temporarily changing the viewport size.
  7967. */
  7968. void QCustomPlot::setViewport(const QRect &rect)
  7969. {
  7970. mViewport = rect;
  7971. if (mPlotLayout)
  7972. mPlotLayout->setOuterRect(mViewport);
  7973. }
  7974. /*!
  7975. Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn
  7976. below all other objects in the plot.
  7977. For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be
  7978. enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is
  7979. preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  7980. consider using the overloaded version of this function.
  7981. If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will
  7982. first be filled with that brush, before drawing the background pixmap. This can be useful for
  7983. background pixmaps with translucent areas.
  7984. \see setBackgroundScaled, setBackgroundScaledMode
  7985. */
  7986. void QCustomPlot::setBackground(const QPixmap &pm)
  7987. {
  7988. mBackgroundPixmap = pm;
  7989. mScaledBackgroundPixmap = QPixmap();
  7990. }
  7991. /*!
  7992. Sets the background brush of the viewport (see \ref setViewport).
  7993. Before drawing everything else, the background is filled with \a brush. If a background pixmap
  7994. was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport
  7995. before the background pixmap is drawn. This can be useful for background pixmaps with translucent
  7996. areas.
  7997. Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be
  7998. useful for exporting to image formats which support transparency, e.g. \ref savePng.
  7999. \see setBackgroundScaled, setBackgroundScaledMode
  8000. */
  8001. void QCustomPlot::setBackground(const QBrush &brush)
  8002. {
  8003. mBackgroundBrush = brush;
  8004. }
  8005. /*! \overload
  8006. Allows setting the background pixmap of the viewport, whether it shall be scaled and how it
  8007. shall be scaled in one call.
  8008. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  8009. */
  8010. void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
  8011. {
  8012. mBackgroundPixmap = pm;
  8013. mScaledBackgroundPixmap = QPixmap();
  8014. mBackgroundScaled = scaled;
  8015. mBackgroundScaledMode = mode;
  8016. }
  8017. /*!
  8018. Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is
  8019. set to true, control whether and how the aspect ratio of the original pixmap is preserved with
  8020. \ref setBackgroundScaledMode.
  8021. Note that the scaled version of the original pixmap is buffered, so there is no performance
  8022. penalty on replots. (Except when the viewport dimensions are changed continuously.)
  8023. \see setBackground, setBackgroundScaledMode
  8024. */
  8025. void QCustomPlot::setBackgroundScaled(bool scaled)
  8026. {
  8027. mBackgroundScaled = scaled;
  8028. }
  8029. /*!
  8030. If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this
  8031. function to define whether and how the aspect ratio of the original pixmap is preserved.
  8032. \see setBackground, setBackgroundScaled
  8033. */
  8034. void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  8035. {
  8036. mBackgroundScaledMode = mode;
  8037. }
  8038. /*!
  8039. Returns the plottable with \a index. If the index is invalid, returns 0.
  8040. There is an overloaded version of this function with no parameter which returns the last added
  8041. plottable, see QCustomPlot::plottable()
  8042. \see plottableCount, addPlottable
  8043. */
  8044. QCPAbstractPlottable *QCustomPlot::plottable(int index)
  8045. {
  8046. if (index >= 0 && index < mPlottables.size())
  8047. {
  8048. return mPlottables.at(index);
  8049. } else
  8050. {
  8051. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  8052. return 0;
  8053. }
  8054. }
  8055. /*! \overload
  8056. Returns the last plottable that was added with \ref addPlottable. If there are no plottables in
  8057. the plot, returns 0.
  8058. \see plottableCount, addPlottable
  8059. */
  8060. QCPAbstractPlottable *QCustomPlot::plottable()
  8061. {
  8062. if (!mPlottables.isEmpty())
  8063. {
  8064. return mPlottables.last();
  8065. } else
  8066. return 0;
  8067. }
  8068. /*!
  8069. Adds the specified plottable to the plot and, if \ref setAutoAddPlottableToLegend is enabled, to
  8070. the legend (QCustomPlot::legend). QCustomPlot takes ownership of the plottable.
  8071. Returns true on success, i.e. when \a plottable isn't already in the plot and the parent plot of
  8072. \a plottable is this QCustomPlot (the latter is controlled by what axes were passed in the
  8073. plottable's constructor).
  8074. \see plottable, plottableCount, removePlottable, clearPlottables
  8075. */
  8076. bool QCustomPlot::addPlottable(QCPAbstractPlottable *plottable)
  8077. {
  8078. if (mPlottables.contains(plottable))
  8079. {
  8080. qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast<quintptr>(plottable);
  8081. return false;
  8082. }
  8083. if (plottable->parentPlot() != this)
  8084. {
  8085. qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(plottable);
  8086. return false;
  8087. }
  8088. mPlottables.append(plottable);
  8089. // possibly add plottable to legend:
  8090. if (mAutoAddPlottableToLegend)
  8091. plottable->addToLegend();
  8092. // special handling for QCPGraphs to maintain the simple graph interface:
  8093. if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable))
  8094. mGraphs.append(graph);
  8095. if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
  8096. plottable->setLayer(currentLayer());
  8097. return true;
  8098. }
  8099. /*!
  8100. Removes the specified plottable from the plot and, if necessary, from the legend (QCustomPlot::legend).
  8101. Returns true on success.
  8102. \see addPlottable, clearPlottables
  8103. */
  8104. bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable)
  8105. {
  8106. if (!mPlottables.contains(plottable))
  8107. {
  8108. qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast<quintptr>(plottable);
  8109. return false;
  8110. }
  8111. // remove plottable from legend:
  8112. plottable->removeFromLegend();
  8113. // special handling for QCPGraphs to maintain the simple graph interface:
  8114. if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable))
  8115. mGraphs.removeOne(graph);
  8116. // remove plottable:
  8117. delete plottable;
  8118. mPlottables.removeOne(plottable);
  8119. return true;
  8120. }
  8121. /*! \overload
  8122. Removes the plottable by its \a index.
  8123. */
  8124. bool QCustomPlot::removePlottable(int index)
  8125. {
  8126. if (index >= 0 && index < mPlottables.size())
  8127. return removePlottable(mPlottables[index]);
  8128. else
  8129. {
  8130. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  8131. return false;
  8132. }
  8133. }
  8134. /*!
  8135. Removes all plottables from the plot (and the QCustomPlot::legend, if necessary).
  8136. Returns the number of plottables removed.
  8137. \see removePlottable
  8138. */
  8139. int QCustomPlot::clearPlottables()
  8140. {
  8141. int c = mPlottables.size();
  8142. for (int i=c-1; i >= 0; --i)
  8143. removePlottable(mPlottables[i]);
  8144. return c;
  8145. }
  8146. /*!
  8147. Returns the number of currently existing plottables in the plot
  8148. \see plottable, addPlottable
  8149. */
  8150. int QCustomPlot::plottableCount() const
  8151. {
  8152. return mPlottables.size();
  8153. }
  8154. /*!
  8155. Returns a list of the selected plottables. If no plottables are currently selected, the list is empty.
  8156. There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs.
  8157. \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected
  8158. */
  8159. QList<QCPAbstractPlottable*> QCustomPlot::selectedPlottables() const
  8160. {
  8161. QList<QCPAbstractPlottable*> result;
  8162. foreach (QCPAbstractPlottable *plottable, mPlottables)
  8163. {
  8164. if (plottable->selected())
  8165. result.append(plottable);
  8166. }
  8167. return result;
  8168. }
  8169. /*!
  8170. Returns the plottable at the pixel position \a pos. Plottables that only consist of single lines
  8171. (like graphs) have a tolerance band around them, see \ref setSelectionTolerance. If multiple
  8172. plottables come into consideration, the one closest to \a pos is returned.
  8173. If \a onlySelectable is true, only plottables that are selectable
  8174. (QCPAbstractPlottable::setSelectable) are considered.
  8175. If there is no plottable at \a pos, the return value is 0.
  8176. \see itemAt, layoutElementAt
  8177. */
  8178. QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable) const
  8179. {
  8180. QCPAbstractPlottable *resultPlottable = 0;
  8181. double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value
  8182. foreach (QCPAbstractPlottable *plottable, mPlottables)
  8183. {
  8184. 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
  8185. continue;
  8186. 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
  8187. {
  8188. double currentDistance = plottable->selectTest(pos, false);
  8189. if (currentDistance >= 0 && currentDistance < resultDistance)
  8190. {
  8191. resultPlottable = plottable;
  8192. resultDistance = currentDistance;
  8193. }
  8194. }
  8195. }
  8196. return resultPlottable;
  8197. }
  8198. /*!
  8199. Returns whether this QCustomPlot instance contains the \a plottable.
  8200. \see addPlottable
  8201. */
  8202. bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const
  8203. {
  8204. return mPlottables.contains(plottable);
  8205. }
  8206. /*!
  8207. Returns the graph with \a index. If the index is invalid, returns 0.
  8208. There is an overloaded version of this function with no parameter which returns the last created
  8209. graph, see QCustomPlot::graph()
  8210. \see graphCount, addGraph
  8211. */
  8212. QCPGraph *QCustomPlot::graph(int index) const
  8213. {
  8214. if (index >= 0 && index < mGraphs.size())
  8215. {
  8216. return mGraphs.at(index);
  8217. } else
  8218. {
  8219. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  8220. return 0;
  8221. }
  8222. }
  8223. /*! \overload
  8224. Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot,
  8225. returns 0.
  8226. \see graphCount, addGraph
  8227. */
  8228. QCPGraph *QCustomPlot::graph() const
  8229. {
  8230. if (!mGraphs.isEmpty())
  8231. {
  8232. return mGraphs.last();
  8233. } else
  8234. return 0;
  8235. }
  8236. /*!
  8237. Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the
  8238. bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a
  8239. keyAxis and \a valueAxis must reside in this QCustomPlot.
  8240. \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically
  8241. "y") for the graph.
  8242. Returns a pointer to the newly created graph, or 0 if adding the graph failed.
  8243. \see graph, graphCount, removeGraph, clearGraphs
  8244. */
  8245. QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis)
  8246. {
  8247. if (!keyAxis) keyAxis = xAxis;
  8248. if (!valueAxis) valueAxis = yAxis;
  8249. if (!keyAxis || !valueAxis)
  8250. {
  8251. qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)";
  8252. return 0;
  8253. }
  8254. if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this)
  8255. {
  8256. qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent";
  8257. return 0;
  8258. }
  8259. QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis);
  8260. if (addPlottable(newGraph))
  8261. {
  8262. newGraph->setName("Graph "+QString::number(mGraphs.size()));
  8263. return newGraph;
  8264. } else
  8265. {
  8266. delete newGraph;
  8267. return 0;
  8268. }
  8269. }
  8270. /*!
  8271. Removes the specified \a graph from the plot and, if necessary, from the QCustomPlot::legend. If
  8272. any other graphs in the plot have a channel fill set towards the removed graph, the channel fill
  8273. property of those graphs is reset to zero (no channel fill).
  8274. Returns true on success.
  8275. \see clearGraphs
  8276. */
  8277. bool QCustomPlot::removeGraph(QCPGraph *graph)
  8278. {
  8279. return removePlottable(graph);
  8280. }
  8281. /*! \overload
  8282. Removes the graph by its \a index.
  8283. */
  8284. bool QCustomPlot::removeGraph(int index)
  8285. {
  8286. if (index >= 0 && index < mGraphs.size())
  8287. return removeGraph(mGraphs[index]);
  8288. else
  8289. return false;
  8290. }
  8291. /*!
  8292. Removes all graphs from the plot (and the QCustomPlot::legend, if necessary).
  8293. Returns the number of graphs removed.
  8294. \see removeGraph
  8295. */
  8296. int QCustomPlot::clearGraphs()
  8297. {
  8298. int c = mGraphs.size();
  8299. for (int i=c-1; i >= 0; --i)
  8300. removeGraph(mGraphs[i]);
  8301. return c;
  8302. }
  8303. /*!
  8304. Returns the number of currently existing graphs in the plot
  8305. \see graph, addGraph
  8306. */
  8307. int QCustomPlot::graphCount() const
  8308. {
  8309. return mGraphs.size();
  8310. }
  8311. /*!
  8312. Returns a list of the selected graphs. If no graphs are currently selected, the list is empty.
  8313. If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars,
  8314. etc., use \ref selectedPlottables.
  8315. \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected
  8316. */
  8317. QList<QCPGraph*> QCustomPlot::selectedGraphs() const
  8318. {
  8319. QList<QCPGraph*> result;
  8320. foreach (QCPGraph *graph, mGraphs)
  8321. {
  8322. if (graph->selected())
  8323. result.append(graph);
  8324. }
  8325. return result;
  8326. }
  8327. /*!
  8328. Returns the item with \a index. If the index is invalid, returns 0.
  8329. There is an overloaded version of this function with no parameter which returns the last added
  8330. item, see QCustomPlot::item()
  8331. \see itemCount, addItem
  8332. */
  8333. QCPAbstractItem *QCustomPlot::item(int index) const
  8334. {
  8335. if (index >= 0 && index < mItems.size())
  8336. {
  8337. return mItems.at(index);
  8338. } else
  8339. {
  8340. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  8341. return 0;
  8342. }
  8343. }
  8344. /*! \overload
  8345. Returns the last item, that was added with \ref addItem. If there are no items in the plot,
  8346. returns 0.
  8347. \see itemCount, addItem
  8348. */
  8349. QCPAbstractItem *QCustomPlot::item() const
  8350. {
  8351. if (!mItems.isEmpty())
  8352. {
  8353. return mItems.last();
  8354. } else
  8355. return 0;
  8356. }
  8357. /*!
  8358. Adds the specified item to the plot. QCustomPlot takes ownership of the item.
  8359. Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a
  8360. item is this QCustomPlot.
  8361. \see item, itemCount, removeItem, clearItems
  8362. */
  8363. bool QCustomPlot::addItem(QCPAbstractItem *item)
  8364. {
  8365. if (!mItems.contains(item) && item->parentPlot() == this)
  8366. {
  8367. mItems.append(item);
  8368. return true;
  8369. } else
  8370. {
  8371. qDebug() << Q_FUNC_INFO << "item either already in list or not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(item);
  8372. return false;
  8373. }
  8374. }
  8375. /*!
  8376. Removes the specified item from the plot.
  8377. Returns true on success.
  8378. \see addItem, clearItems
  8379. */
  8380. bool QCustomPlot::removeItem(QCPAbstractItem *item)
  8381. {
  8382. if (mItems.contains(item))
  8383. {
  8384. delete item;
  8385. mItems.removeOne(item);
  8386. return true;
  8387. } else
  8388. {
  8389. qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast<quintptr>(item);
  8390. return false;
  8391. }
  8392. }
  8393. /*! \overload
  8394. Removes the item by its \a index.
  8395. */
  8396. bool QCustomPlot::removeItem(int index)
  8397. {
  8398. if (index >= 0 && index < mItems.size())
  8399. return removeItem(mItems[index]);
  8400. else
  8401. {
  8402. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  8403. return false;
  8404. }
  8405. }
  8406. /*!
  8407. Removes all items from the plot.
  8408. Returns the number of items removed.
  8409. \see removeItem
  8410. */
  8411. int QCustomPlot::clearItems()
  8412. {
  8413. int c = mItems.size();
  8414. for (int i=c-1; i >= 0; --i)
  8415. removeItem(mItems[i]);
  8416. return c;
  8417. }
  8418. /*!
  8419. Returns the number of currently existing items in the plot
  8420. \see item, addItem
  8421. */
  8422. int QCustomPlot::itemCount() const
  8423. {
  8424. return mItems.size();
  8425. }
  8426. /*!
  8427. Returns a list of the selected items. If no items are currently selected, the list is empty.
  8428. \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected
  8429. */
  8430. QList<QCPAbstractItem*> QCustomPlot::selectedItems() const
  8431. {
  8432. QList<QCPAbstractItem*> result;
  8433. foreach (QCPAbstractItem *item, mItems)
  8434. {
  8435. if (item->selected())
  8436. result.append(item);
  8437. }
  8438. return result;
  8439. }
  8440. /*!
  8441. Returns the item at the pixel position \a pos. Items that only consist of single lines (e.g. \ref
  8442. QCPItemLine or \ref QCPItemCurve) have a tolerance band around them, see \ref
  8443. setSelectionTolerance. If multiple items come into consideration, the one closest to \a pos is
  8444. returned.
  8445. If \a onlySelectable is true, only items that are selectable (QCPAbstractItem::setSelectable) are
  8446. considered.
  8447. If there is no item at \a pos, the return value is 0.
  8448. \see plottableAt, layoutElementAt
  8449. */
  8450. QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const
  8451. {
  8452. QCPAbstractItem *resultItem = 0;
  8453. double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value
  8454. foreach (QCPAbstractItem *item, mItems)
  8455. {
  8456. 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
  8457. continue;
  8458. if (!item->clipToAxisRect() || item->clipRect().contains(pos.toPoint())) // only consider clicks inside axis cliprect of the item if actually clipped to it
  8459. {
  8460. double currentDistance = item->selectTest(pos, false);
  8461. if (currentDistance >= 0 && currentDistance < resultDistance)
  8462. {
  8463. resultItem = item;
  8464. resultDistance = currentDistance;
  8465. }
  8466. }
  8467. }
  8468. return resultItem;
  8469. }
  8470. /*!
  8471. Returns whether this QCustomPlot contains the \a item.
  8472. \see addItem
  8473. */
  8474. bool QCustomPlot::hasItem(QCPAbstractItem *item) const
  8475. {
  8476. return mItems.contains(item);
  8477. }
  8478. /*!
  8479. Returns the layer with the specified \a name. If there is no layer with the specified name, 0 is
  8480. returned.
  8481. Layer names are case-sensitive.
  8482. \see addLayer, moveLayer, removeLayer
  8483. */
  8484. QCPLayer *QCustomPlot::layer(const QString &name) const
  8485. {
  8486. foreach (QCPLayer *layer, mLayers)
  8487. {
  8488. if (layer->name() == name)
  8489. return layer;
  8490. }
  8491. return 0;
  8492. }
  8493. /*! \overload
  8494. Returns the layer by \a index. If the index is invalid, 0 is returned.
  8495. \see addLayer, moveLayer, removeLayer
  8496. */
  8497. QCPLayer *QCustomPlot::layer(int index) const
  8498. {
  8499. if (index >= 0 && index < mLayers.size())
  8500. {
  8501. return mLayers.at(index);
  8502. } else
  8503. {
  8504. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  8505. return 0;
  8506. }
  8507. }
  8508. /*!
  8509. Returns the layer that is set as current layer (see \ref setCurrentLayer).
  8510. */
  8511. QCPLayer *QCustomPlot::currentLayer() const
  8512. {
  8513. return mCurrentLayer;
  8514. }
  8515. /*!
  8516. Sets the layer with the specified \a name to be the current layer. All layerables (\ref
  8517. QCPLayerable), e.g. plottables and items, are created on the current layer.
  8518. Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot.
  8519. Layer names are case-sensitive.
  8520. \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer
  8521. */
  8522. bool QCustomPlot::setCurrentLayer(const QString &name)
  8523. {
  8524. if (QCPLayer *newCurrentLayer = layer(name))
  8525. {
  8526. return setCurrentLayer(newCurrentLayer);
  8527. } else
  8528. {
  8529. qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name;
  8530. return false;
  8531. }
  8532. }
  8533. /*! \overload
  8534. Sets the provided \a layer to be the current layer.
  8535. Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot.
  8536. \see addLayer, moveLayer, removeLayer
  8537. */
  8538. bool QCustomPlot::setCurrentLayer(QCPLayer *layer)
  8539. {
  8540. if (!mLayers.contains(layer))
  8541. {
  8542. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  8543. return false;
  8544. }
  8545. mCurrentLayer = layer;
  8546. return true;
  8547. }
  8548. /*!
  8549. Returns the number of currently existing layers in the plot
  8550. \see layer, addLayer
  8551. */
  8552. int QCustomPlot::layerCount() const
  8553. {
  8554. return mLayers.size();
  8555. }
  8556. /*!
  8557. Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which
  8558. must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer.
  8559. Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a
  8560. valid layer inside this QCustomPlot.
  8561. If \a otherLayer is 0, the highest layer in the QCustomPlot will be used.
  8562. For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer.
  8563. \see layer, moveLayer, removeLayer
  8564. */
  8565. bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
  8566. {
  8567. if (!otherLayer)
  8568. otherLayer = mLayers.last();
  8569. if (!mLayers.contains(otherLayer))
  8570. {
  8571. qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
  8572. return false;
  8573. }
  8574. if (layer(name))
  8575. {
  8576. qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name;
  8577. return false;
  8578. }
  8579. QCPLayer *newLayer = new QCPLayer(this, name);
  8580. mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer);
  8581. updateLayerIndices();
  8582. return true;
  8583. }
  8584. /*!
  8585. Removes the specified \a layer and returns true on success.
  8586. All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below
  8587. \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both
  8588. cases, the total rendering order of all layerables in the QCustomPlot is preserved.
  8589. If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom
  8590. layer) becomes the new current layer.
  8591. It is not possible to remove the last layer of the plot.
  8592. \see layer, addLayer, moveLayer
  8593. */
  8594. bool QCustomPlot::removeLayer(QCPLayer *layer)
  8595. {
  8596. if (!mLayers.contains(layer))
  8597. {
  8598. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  8599. return false;
  8600. }
  8601. if (mLayers.size() < 2)
  8602. {
  8603. qDebug() << Q_FUNC_INFO << "can't remove last layer";
  8604. return false;
  8605. }
  8606. // append all children of this layer to layer below (if this is lowest layer, prepend to layer above)
  8607. int removedIndex = layer->index();
  8608. bool isFirstLayer = removedIndex==0;
  8609. QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1);
  8610. QList<QCPLayerable*> children = layer->children();
  8611. if (isFirstLayer) // prepend in reverse order (so order relative to each other stays the same)
  8612. {
  8613. for (int i=children.size()-1; i>=0; --i)
  8614. children.at(i)->moveToLayer(targetLayer, true);
  8615. } else // append normally
  8616. {
  8617. for (int i=0; i<children.size(); ++i)
  8618. children.at(i)->moveToLayer(targetLayer, false);
  8619. }
  8620. // if removed layer is current layer, change current layer to layer below/above:
  8621. if (layer == mCurrentLayer)
  8622. setCurrentLayer(targetLayer);
  8623. // remove layer:
  8624. delete layer;
  8625. mLayers.removeOne(layer);
  8626. updateLayerIndices();
  8627. return true;
  8628. }
  8629. /*!
  8630. Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or
  8631. below is controlled with \a insertMode.
  8632. Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the
  8633. QCustomPlot.
  8634. \see layer, addLayer, moveLayer
  8635. */
  8636. bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
  8637. {
  8638. if (!mLayers.contains(layer))
  8639. {
  8640. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  8641. return false;
  8642. }
  8643. if (!mLayers.contains(otherLayer))
  8644. {
  8645. qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
  8646. return false;
  8647. }
  8648. mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0));
  8649. updateLayerIndices();
  8650. return true;
  8651. }
  8652. /*!
  8653. Returns the number of axis rects in the plot.
  8654. All axis rects can be accessed via QCustomPlot::axisRect().
  8655. Initially, only one axis rect exists in the plot.
  8656. \see axisRect, axisRects
  8657. */
  8658. int QCustomPlot::axisRectCount() const
  8659. {
  8660. return axisRects().size();
  8661. }
  8662. /*!
  8663. Returns the axis rect with \a index.
  8664. Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were
  8665. added, all of them may be accessed with this function in a linear fashion (even when they are
  8666. nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout).
  8667. \see axisRectCount, axisRects
  8668. */
  8669. QCPAxisRect *QCustomPlot::axisRect(int index) const
  8670. {
  8671. const QList<QCPAxisRect*> rectList = axisRects();
  8672. if (index >= 0 && index < rectList.size())
  8673. {
  8674. return rectList.at(index);
  8675. } else
  8676. {
  8677. qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index;
  8678. return 0;
  8679. }
  8680. }
  8681. /*!
  8682. Returns all axis rects in the plot.
  8683. \see axisRectCount, axisRect
  8684. */
  8685. QList<QCPAxisRect*> QCustomPlot::axisRects() const
  8686. {
  8687. QList<QCPAxisRect*> result;
  8688. QStack<QCPLayoutElement*> elementStack;
  8689. if (mPlotLayout)
  8690. elementStack.push(mPlotLayout);
  8691. while (!elementStack.isEmpty())
  8692. {
  8693. foreach (QCPLayoutElement *element, elementStack.pop()->elements(false))
  8694. {
  8695. if (element)
  8696. {
  8697. elementStack.push(element);
  8698. if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(element))
  8699. result.append(ar);
  8700. }
  8701. }
  8702. }
  8703. return result;
  8704. }
  8705. /*!
  8706. Returns the layout element at pixel position \a pos. If there is no element at that position,
  8707. returns 0.
  8708. Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on
  8709. any of its parent elements is set to false, it will not be considered.
  8710. \see itemAt, plottableAt
  8711. */
  8712. QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const
  8713. {
  8714. QCPLayoutElement *currentElement = mPlotLayout;
  8715. bool searchSubElements = true;
  8716. while (searchSubElements && currentElement)
  8717. {
  8718. searchSubElements = false;
  8719. foreach (QCPLayoutElement *subElement, currentElement->elements(false))
  8720. {
  8721. if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
  8722. {
  8723. currentElement = subElement;
  8724. searchSubElements = true;
  8725. break;
  8726. }
  8727. }
  8728. }
  8729. return currentElement;
  8730. }
  8731. /*!
  8732. Returns the axes that currently have selected parts, i.e. whose selection state is not \ref
  8733. QCPAxis::spNone.
  8734. \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts,
  8735. QCPAxis::setSelectableParts
  8736. */
  8737. QList<QCPAxis*> QCustomPlot::selectedAxes() const
  8738. {
  8739. QList<QCPAxis*> result, allAxes;
  8740. foreach (QCPAxisRect *rect, axisRects())
  8741. allAxes << rect->axes();
  8742. foreach (QCPAxis *axis, allAxes)
  8743. {
  8744. if (axis->selectedParts() != QCPAxis::spNone)
  8745. result.append(axis);
  8746. }
  8747. return result;
  8748. }
  8749. /*!
  8750. Returns the legends that currently have selected parts, i.e. whose selection state is not \ref
  8751. QCPLegend::spNone.
  8752. \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts,
  8753. QCPLegend::setSelectableParts, QCPLegend::selectedItems
  8754. */
  8755. QList<QCPLegend*> QCustomPlot::selectedLegends() const
  8756. {
  8757. QList<QCPLegend*> result;
  8758. QStack<QCPLayoutElement*> elementStack;
  8759. if (mPlotLayout)
  8760. elementStack.push(mPlotLayout);
  8761. while (!elementStack.isEmpty())
  8762. {
  8763. foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false))
  8764. {
  8765. if (subElement)
  8766. {
  8767. elementStack.push(subElement);
  8768. if (QCPLegend *leg = qobject_cast<QCPLegend*>(subElement))
  8769. {
  8770. if (leg->selectedParts() != QCPLegend::spNone)
  8771. result.append(leg);
  8772. }
  8773. }
  8774. }
  8775. }
  8776. return result;
  8777. }
  8778. /*!
  8779. Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot.
  8780. Since calling this function is not a user interaction, this does not emit the \ref
  8781. selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the
  8782. objects were previously selected.
  8783. \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends
  8784. */
  8785. void QCustomPlot::deselectAll()
  8786. {
  8787. foreach (QCPLayer *layer, mLayers)
  8788. {
  8789. foreach (QCPLayerable *layerable, layer->children())
  8790. layerable->deselectEvent(0);
  8791. }
  8792. }
  8793. /*!
  8794. Causes a complete replot into the internal buffer. Finally, update() is called, to redraw the
  8795. buffer on the QCustomPlot widget surface. This is the method that must be called to make changes,
  8796. for example on the axis ranges or data points of graphs, visible.
  8797. Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the
  8798. QCustomPlot widget and user interactions (object selection and range dragging/zooming).
  8799. Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref
  8800. afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two
  8801. signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite
  8802. recursion.
  8803. */
  8804. void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority)
  8805. {
  8806. if (mReplotting) // incase signals loop back to replot slot
  8807. return;
  8808. mReplotting = true;
  8809. emit beforeReplot();
  8810. mPaintBuffer.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent);
  8811. QCPPainter painter;
  8812. painter.begin(&mPaintBuffer);
  8813. if (painter.isActive())
  8814. {
  8815. painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem
  8816. if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush)
  8817. painter.fillRect(mViewport, mBackgroundBrush);
  8818. draw(&painter);
  8819. painter.end();
  8820. if ((refreshPriority == rpHint && mPlottingHints.testFlag(QCP::phForceRepaint)) || refreshPriority==rpImmediate)
  8821. repaint();
  8822. else
  8823. update();
  8824. } else // might happen if QCustomPlot has width or height zero
  8825. qDebug() << Q_FUNC_INFO << "Couldn't activate painter on buffer";
  8826. emit afterReplot();
  8827. mReplotting = false;
  8828. }
  8829. /*!
  8830. Rescales the axes such that all plottables (like graphs) in the plot are fully visible.
  8831. if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true
  8832. (QCPLayerable::setVisible), will be used to rescale the axes.
  8833. \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale
  8834. */
  8835. void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables)
  8836. {
  8837. QList<QCPAxis*> allAxes;
  8838. foreach (QCPAxisRect *rect, axisRects())
  8839. allAxes << rect->axes();
  8840. foreach (QCPAxis *axis, allAxes)
  8841. axis->rescale(onlyVisiblePlottables);
  8842. }
  8843. /*!
  8844. Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale
  8845. of texts and lines will be derived from the specified \a width and \a height. This means, the
  8846. output will look like the normal on-screen output of a QCustomPlot widget with the corresponding
  8847. pixel width and height. If either \a width or \a height is zero, the exported image will have the
  8848. same dimensions as the QCustomPlot widget currently has.
  8849. \a noCosmeticPen disables the use of cosmetic pens when drawing to the PDF file. Cosmetic pens
  8850. are pens with numerical width 0, which are always drawn as a one pixel wide line, no matter what
  8851. zoom factor is set in the PDF-Viewer. For more information about cosmetic pens, see the QPainter
  8852. and QPen documentation.
  8853. The objects of the plot will appear in the current selection state. If you don't want any
  8854. selected objects to be painted in their selected look, deselect everything with \ref deselectAll
  8855. before calling this function.
  8856. Returns true on success.
  8857. \warning
  8858. \li If you plan on editing the exported PDF file with a vector graphics editor like
  8859. Inkscape, it is advised to set \a noCosmeticPen to true to avoid losing those cosmetic lines
  8860. (which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks).
  8861. \li If calling this function inside the constructor of the parent of the QCustomPlot widget
  8862. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  8863. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  8864. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  8865. aren't defined yet inside the constructor, so you would get an image that has strange
  8866. widths/heights.
  8867. \a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting
  8868. PDF file.
  8869. \note On Android systems, this method does nothing and issues an according qDebug warning
  8870. message. This is also the case if for other reasons the define flag QT_NO_PRINTER is set.
  8871. \see savePng, saveBmp, saveJpg, saveRastered
  8872. */
  8873. bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width, int height, const QString &pdfCreator, const QString &pdfTitle)
  8874. {
  8875. bool success = false;
  8876. #ifdef QT_NO_PRINTER
  8877. Q_UNUSED(fileName)
  8878. Q_UNUSED(noCosmeticPen)
  8879. Q_UNUSED(width)
  8880. Q_UNUSED(height)
  8881. qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created.";
  8882. #else
  8883. int newWidth, newHeight;
  8884. if (width == 0 || height == 0)
  8885. {
  8886. newWidth = this->width();
  8887. newHeight = this->height();
  8888. } else
  8889. {
  8890. newWidth = width;
  8891. newHeight = height;
  8892. }
  8893. QPrinter printer(QPrinter::ScreenResolution);
  8894. printer.setOutputFileName(fileName);
  8895. printer.setOutputFormat(QPrinter::PdfFormat);
  8896. printer.setFullPage(true);
  8897. printer.setColorMode(QPrinter::Color);
  8898. printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator);
  8899. printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle);
  8900. QRect oldViewport = viewport();
  8901. setViewport(QRect(0, 0, newWidth, newHeight));
  8902. printer.setPaperSize(viewport().size(), QPrinter::DevicePixel);
  8903. QCPPainter printpainter;
  8904. if (printpainter.begin(&printer))
  8905. {
  8906. printpainter.setMode(QCPPainter::pmVectorized);
  8907. printpainter.setMode(QCPPainter::pmNoCaching);
  8908. printpainter.setMode(QCPPainter::pmNonCosmetic, noCosmeticPen);
  8909. printpainter.setWindow(mViewport);
  8910. if (mBackgroundBrush.style() != Qt::NoBrush &&
  8911. mBackgroundBrush.color() != Qt::white &&
  8912. mBackgroundBrush.color() != Qt::transparent &&
  8913. mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent
  8914. printpainter.fillRect(viewport(), mBackgroundBrush);
  8915. draw(&printpainter);
  8916. printpainter.end();
  8917. success = true;
  8918. }
  8919. setViewport(oldViewport);
  8920. #endif // QT_NO_PRINTER
  8921. return success;
  8922. }
  8923. /*!
  8924. Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width
  8925. and \a height in pixels. If either \a width or \a height is zero, the exported image will have
  8926. the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not
  8927. scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter.
  8928. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  8929. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  8930. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  8931. 200*200 pixel resolution.
  8932. If you use a high scaling factor, it is recommended to enable antialiasing for all elements via
  8933. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  8934. QCustomPlot to place objects with sub-pixel accuracy.
  8935. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  8936. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  8937. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  8938. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  8939. aren't defined yet inside the constructor, so you would get an image that has strange
  8940. widths/heights.
  8941. The objects of the plot will appear in the current selection state. If you don't want any selected
  8942. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  8943. this function.
  8944. If you want the PNG to have a transparent background, call \ref setBackground(const QBrush
  8945. &brush) with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving.
  8946. PNG compression can be controlled with the \a quality parameter which must be between 0 and 100 or
  8947. -1 to use the default setting.
  8948. Returns true on success. If this function fails, most likely the PNG format isn't supported by
  8949. the system, see Qt docs about QImageWriter::supportedImageFormats().
  8950. \see savePdf, saveBmp, saveJpg, saveRastered
  8951. */
  8952. bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality)
  8953. {
  8954. return saveRastered(fileName, width, height, scale, "PNG", quality);
  8955. }
  8956. /*!
  8957. Saves a JPG image file to \a fileName on disc. The output plot will have the dimensions \a width
  8958. and \a height in pixels. If either \a width or \a height is zero, the exported image will have
  8959. the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not
  8960. scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter.
  8961. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  8962. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  8963. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  8964. 200*200 pixel resolution.
  8965. If you use a high scaling factor, it is recommended to enable antialiasing for all elements via
  8966. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  8967. QCustomPlot to place objects with sub-pixel accuracy.
  8968. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  8969. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  8970. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  8971. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  8972. aren't defined yet inside the constructor, so you would get an image that has strange
  8973. widths/heights.
  8974. The objects of the plot will appear in the current selection state. If you don't want any selected
  8975. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  8976. this function.
  8977. JPG compression can be controlled with the \a quality parameter which must be between 0 and 100 or
  8978. -1 to use the default setting.
  8979. Returns true on success. If this function fails, most likely the JPG format isn't supported by
  8980. the system, see Qt docs about QImageWriter::supportedImageFormats().
  8981. \see savePdf, savePng, saveBmp, saveRastered
  8982. */
  8983. bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality)
  8984. {
  8985. return saveRastered(fileName, width, height, scale, "JPG", quality);
  8986. }
  8987. /*!
  8988. Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width
  8989. and \a height in pixels. If either \a width or \a height is zero, the exported image will have
  8990. the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not
  8991. scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter.
  8992. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  8993. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  8994. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  8995. 200*200 pixel resolution.
  8996. If you use a high scaling factor, it is recommended to enable antialiasing for all elements via
  8997. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  8998. QCustomPlot to place objects with sub-pixel accuracy.
  8999. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  9000. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  9001. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  9002. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  9003. aren't defined yet inside the constructor, so you would get an image that has strange
  9004. widths/heights.
  9005. The objects of the plot will appear in the current selection state. If you don't want any selected
  9006. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  9007. this function.
  9008. Returns true on success. If this function fails, most likely the BMP format isn't supported by
  9009. the system, see Qt docs about QImageWriter::supportedImageFormats().
  9010. \see savePdf, savePng, saveJpg, saveRastered
  9011. */
  9012. bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale)
  9013. {
  9014. return saveRastered(fileName, width, height, scale, "BMP");
  9015. }
  9016. /*! \internal
  9017. Returns a minimum size hint that corresponds to the minimum size of the top level layout
  9018. (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum
  9019. size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot.
  9020. This is especially important, when placed in a QLayout where other components try to take in as
  9021. much space as possible (e.g. QMdiArea).
  9022. */
  9023. QSize QCustomPlot::minimumSizeHint() const
  9024. {
  9025. return mPlotLayout->minimumSizeHint();
  9026. }
  9027. /*! \internal
  9028. Returns a size hint that is the same as \ref minimumSizeHint.
  9029. */
  9030. QSize QCustomPlot::sizeHint() const
  9031. {
  9032. return mPlotLayout->minimumSizeHint();
  9033. }
  9034. /*! \internal
  9035. Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but
  9036. draws the internal buffer on the widget surface.
  9037. */
  9038. void QCustomPlot::paintEvent(QPaintEvent *event)
  9039. {
  9040. Q_UNUSED(event);
  9041. QPainter painter(this);
  9042. painter.drawPixmap(0, 0, mPaintBuffer);
  9043. }
  9044. /*! \internal
  9045. Event handler for a resize of the QCustomPlot widget. Causes the internal buffer to be resized to
  9046. the new size. The viewport (which becomes the outer rect of mPlotLayout) is resized
  9047. appropriately. Finally a \ref replot is performed.
  9048. */
  9049. void QCustomPlot::resizeEvent(QResizeEvent *event)
  9050. {
  9051. // resize and repaint the buffer:
  9052. mPaintBuffer = QPixmap(event->size());
  9053. setViewport(rect());
  9054. replot(rpQueued); // queued update is important here, to prevent painting issues in some contexts
  9055. }
  9056. /*! \internal
  9057. Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then emits
  9058. the specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref
  9059. axisDoubleClick, etc.). Finally determines the affected layout element and forwards the event to
  9060. it.
  9061. \see mousePressEvent, mouseReleaseEvent
  9062. */
  9063. void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event)
  9064. {
  9065. emit mouseDoubleClick(event);
  9066. QVariant details;
  9067. QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details);
  9068. // emit specialized object double click signals:
  9069. if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(clickedLayerable))
  9070. emit plottableDoubleClick(ap, event);
  9071. else if (QCPAxis *ax = qobject_cast<QCPAxis*>(clickedLayerable))
  9072. emit axisDoubleClick(ax, details.value<QCPAxis::SelectablePart>(), event);
  9073. else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(clickedLayerable))
  9074. emit itemDoubleClick(ai, event);
  9075. else if (QCPLegend *lg = qobject_cast<QCPLegend*>(clickedLayerable))
  9076. emit legendDoubleClick(lg, 0, event);
  9077. else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(clickedLayerable))
  9078. emit legendDoubleClick(li->parentLegend(), li, event);
  9079. else if (QCPPlotTitle *pt = qobject_cast<QCPPlotTitle*>(clickedLayerable))
  9080. emit titleDoubleClick(event, pt);
  9081. // call double click event of affected layout element:
  9082. if (QCPLayoutElement *el = layoutElementAt(event->pos()))
  9083. el->mouseDoubleClickEvent(event);
  9084. // call release event of affected layout element (as in mouseReleaseEvent, since the mouseDoubleClick replaces the second release event in double click case):
  9085. if (mMouseEventElement)
  9086. {
  9087. mMouseEventElement->mouseReleaseEvent(event);
  9088. mMouseEventElement = 0;
  9089. }
  9090. //QWidget::mouseDoubleClickEvent(event); don't call base class implementation because it would just cause a mousePress/ReleaseEvent, which we don't want.
  9091. }
  9092. /*! \internal
  9093. Event handler for when a mouse button is pressed. Emits the mousePress signal. Then determines
  9094. the affected layout element and forwards the event to it.
  9095. \see mouseMoveEvent, mouseReleaseEvent
  9096. */
  9097. void QCustomPlot::mousePressEvent(QMouseEvent *event)
  9098. {
  9099. emit mousePress(event);
  9100. mMousePressPos = event->pos(); // need this to determine in releaseEvent whether it was a click (no position change between press and release)
  9101. // call event of affected layout element:
  9102. mMouseEventElement = layoutElementAt(event->pos());
  9103. if (mMouseEventElement)
  9104. mMouseEventElement->mousePressEvent(event);
  9105. QWidget::mousePressEvent(event);
  9106. }
  9107. /*! \internal
  9108. Event handler for when the cursor is moved. Emits the \ref mouseMove signal.
  9109. If a layout element has mouse capture focus (a mousePressEvent happened on top of the layout
  9110. element before), the mouseMoveEvent is forwarded to that element.
  9111. \see mousePressEvent, mouseReleaseEvent
  9112. */
  9113. void QCustomPlot::mouseMoveEvent(QMouseEvent *event)
  9114. {
  9115. emit mouseMove(event);
  9116. // call event of affected layout element:
  9117. if (mMouseEventElement)
  9118. mMouseEventElement->mouseMoveEvent(event);
  9119. QWidget::mouseMoveEvent(event);
  9120. }
  9121. /*! \internal
  9122. Event handler for when a mouse button is released. Emits the \ref mouseRelease signal.
  9123. If the mouse was moved less than a certain threshold in any direction since the \ref
  9124. mousePressEvent, it is considered a click which causes the selection mechanism (if activated via
  9125. \ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse
  9126. click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.)
  9127. If a layout element has mouse capture focus (a \ref mousePressEvent happened on top of the layout
  9128. element before), the \ref mouseReleaseEvent is forwarded to that element.
  9129. \see mousePressEvent, mouseMoveEvent
  9130. */
  9131. void QCustomPlot::mouseReleaseEvent(QMouseEvent *event)
  9132. {
  9133. emit mouseRelease(event);
  9134. bool doReplot = false;
  9135. if ((mMousePressPos-event->pos()).manhattanLength() < 5) // determine whether it was a click operation
  9136. {
  9137. if (event->button() == Qt::LeftButton)
  9138. {
  9139. // handle selection mechanism:
  9140. QVariant details;
  9141. QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details);
  9142. bool selectionStateChanged = false;
  9143. bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier);
  9144. // deselect all other layerables if not additive selection:
  9145. if (!additive)
  9146. {
  9147. foreach (QCPLayer *layer, mLayers)
  9148. {
  9149. foreach (QCPLayerable *layerable, layer->children())
  9150. {
  9151. if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory()))
  9152. {
  9153. bool selChanged = false;
  9154. layerable->deselectEvent(&selChanged);
  9155. selectionStateChanged |= selChanged;
  9156. }
  9157. }
  9158. }
  9159. }
  9160. if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory()))
  9161. {
  9162. // a layerable was actually clicked, call its selectEvent:
  9163. bool selChanged = false;
  9164. clickedLayerable->selectEvent(event, additive, details, &selChanged);
  9165. selectionStateChanged |= selChanged;
  9166. }
  9167. doReplot = true;
  9168. if (selectionStateChanged)
  9169. emit selectionChangedByUser();
  9170. }
  9171. // emit specialized object click signals:
  9172. QVariant details;
  9173. 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
  9174. if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(clickedLayerable))
  9175. emit plottableClick(ap, event);
  9176. else if (QCPAxis *ax = qobject_cast<QCPAxis*>(clickedLayerable))
  9177. emit axisClick(ax, details.value<QCPAxis::SelectablePart>(), event);
  9178. else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(clickedLayerable))
  9179. emit itemClick(ai, event);
  9180. else if (QCPLegend *lg = qobject_cast<QCPLegend*>(clickedLayerable))
  9181. emit legendClick(lg, 0, event);
  9182. else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(clickedLayerable))
  9183. emit legendClick(li->parentLegend(), li, event);
  9184. else if (QCPPlotTitle *pt = qobject_cast<QCPPlotTitle*>(clickedLayerable))
  9185. emit titleClick(event, pt);
  9186. }
  9187. // call event of affected layout element:
  9188. if (mMouseEventElement)
  9189. {
  9190. mMouseEventElement->mouseReleaseEvent(event);
  9191. mMouseEventElement = 0;
  9192. }
  9193. if (doReplot || noAntialiasingOnDrag())
  9194. replot();
  9195. QWidget::mouseReleaseEvent(event);
  9196. }
  9197. /*! \internal
  9198. Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then
  9199. determines the affected layout element and forwards the event to it.
  9200. */
  9201. void QCustomPlot::wheelEvent(QWheelEvent *event)
  9202. {
  9203. emit mouseWheel(event);
  9204. // call event of affected layout element:
  9205. if (QCPLayoutElement *el = layoutElementAt(event->pos()))
  9206. el->wheelEvent(event);
  9207. QWidget::wheelEvent(event);
  9208. }
  9209. /*! \internal
  9210. This is the main draw function. It draws the entire plot, including background pixmap, with the
  9211. specified \a painter. Note that it does not fill the background with the background brush (as the
  9212. user may specify with \ref setBackground(const QBrush &brush)), this is up to the respective
  9213. functions calling this method (e.g. \ref replot, \ref toPixmap and \ref toPainter).
  9214. */
  9215. void QCustomPlot::draw(QCPPainter *painter)
  9216. {
  9217. // run through layout phases:
  9218. mPlotLayout->update(QCPLayoutElement::upPreparation);
  9219. mPlotLayout->update(QCPLayoutElement::upMargins);
  9220. mPlotLayout->update(QCPLayoutElement::upLayout);
  9221. // draw viewport background pixmap:
  9222. drawBackground(painter);
  9223. // draw all layered objects (grid, axes, plottables, items, legend,...):
  9224. foreach (QCPLayer *layer, mLayers)
  9225. {
  9226. foreach (QCPLayerable *child, layer->children())
  9227. {
  9228. if (child->realVisibility())
  9229. {
  9230. painter->save();
  9231. painter->setClipRect(child->clipRect().translated(0, -1));
  9232. child->applyDefaultAntialiasingHint(painter);
  9233. child->draw(painter);
  9234. painter->restore();
  9235. }
  9236. }
  9237. }
  9238. /* Debug code to draw all layout element rects
  9239. foreach (QCPLayoutElement* el, findChildren<QCPLayoutElement*>())
  9240. {
  9241. painter->setBrush(Qt::NoBrush);
  9242. painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine));
  9243. painter->drawRect(el->rect());
  9244. painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine));
  9245. painter->drawRect(el->outerRect());
  9246. }
  9247. */
  9248. }
  9249. /*! \internal
  9250. Draws the viewport background pixmap of the plot.
  9251. If a pixmap was provided via \ref setBackground, this function buffers the scaled version
  9252. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  9253. the viewport with the provided \a painter. The scaled version is buffered in
  9254. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  9255. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  9256. dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
  9257. set.
  9258. Note that this function does not draw a fill with the background brush (\ref setBackground(const
  9259. QBrush &brush)) beneath the pixmap.
  9260. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  9261. */
  9262. void QCustomPlot::drawBackground(QCPPainter *painter)
  9263. {
  9264. // Note: background color is handled in individual replot/save functions
  9265. // draw background pixmap (on top of fill, if brush specified):
  9266. if (!mBackgroundPixmap.isNull())
  9267. {
  9268. if (mBackgroundScaled)
  9269. {
  9270. // check whether mScaledBackground needs to be updated:
  9271. QSize scaledSize(mBackgroundPixmap.size());
  9272. scaledSize.scale(mViewport.size(), mBackgroundScaledMode);
  9273. if (mScaledBackgroundPixmap.size() != scaledSize)
  9274. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
  9275. painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect());
  9276. } else
  9277. {
  9278. painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()));
  9279. }
  9280. }
  9281. }
  9282. /*! \internal
  9283. This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot
  9284. so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly.
  9285. */
  9286. void QCustomPlot::axisRemoved(QCPAxis *axis)
  9287. {
  9288. if (xAxis == axis)
  9289. xAxis = 0;
  9290. if (xAxis2 == axis)
  9291. xAxis2 = 0;
  9292. if (yAxis == axis)
  9293. yAxis = 0;
  9294. if (yAxis2 == axis)
  9295. yAxis2 = 0;
  9296. // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers
  9297. }
  9298. /*! \internal
  9299. This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so
  9300. it may clear its QCustomPlot::legend member accordingly.
  9301. */
  9302. void QCustomPlot::legendRemoved(QCPLegend *legend)
  9303. {
  9304. if (this->legend == legend)
  9305. this->legend = 0;
  9306. }
  9307. /*! \internal
  9308. Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called
  9309. after every operation that changes the layer indices, like layer removal, layer creation, layer
  9310. moving.
  9311. */
  9312. void QCustomPlot::updateLayerIndices() const
  9313. {
  9314. for (int i=0; i<mLayers.size(); ++i)
  9315. mLayers.at(i)->mIndex = i;
  9316. }
  9317. /*! \internal
  9318. Returns the layerable at pixel position \a pos. If \a onlySelectable is set to true, only those
  9319. layerables that are selectable will be considered. (Layerable subclasses communicate their
  9320. selectability via the QCPLayerable::selectTest method, by returning -1.)
  9321. \a selectionDetails is an output parameter that contains selection specifics of the affected
  9322. layerable. This is useful if the respective layerable shall be given a subsequent
  9323. QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
  9324. information about which part of the layerable was hit, in multi-part layerables (e.g.
  9325. QCPAxis::SelectablePart).
  9326. */
  9327. QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const
  9328. {
  9329. for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex)
  9330. {
  9331. const QList<QCPLayerable*> layerables = mLayers.at(layerIndex)->children();
  9332. double minimumDistance = selectionTolerance()*1.1;
  9333. QCPLayerable *minimumDistanceLayerable = 0;
  9334. for (int i=layerables.size()-1; i>=0; --i)
  9335. {
  9336. if (!layerables.at(i)->realVisibility())
  9337. continue;
  9338. QVariant details;
  9339. double dist = layerables.at(i)->selectTest(pos, onlySelectable, &details);
  9340. if (dist >= 0 && dist < minimumDistance)
  9341. {
  9342. minimumDistance = dist;
  9343. minimumDistanceLayerable = layerables.at(i);
  9344. if (selectionDetails) *selectionDetails = details;
  9345. }
  9346. }
  9347. if (minimumDistance < selectionTolerance())
  9348. return minimumDistanceLayerable;
  9349. }
  9350. return 0;
  9351. }
  9352. /*!
  9353. Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is
  9354. sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead
  9355. to a full resolution file with width 200.) If the \a format supports compression, \a quality may
  9356. be between 0 and 100 to control it.
  9357. Returns true on success. If this function fails, most likely the given \a format isn't supported
  9358. by the system, see Qt docs about QImageWriter::supportedImageFormats().
  9359. \see saveBmp, saveJpg, savePng, savePdf
  9360. */
  9361. bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality)
  9362. {
  9363. QPixmap buffer = toPixmap(width, height, scale);
  9364. if (!buffer.isNull())
  9365. return buffer.save(fileName, format, quality);
  9366. else
  9367. return false;
  9368. }
  9369. /*!
  9370. Renders the plot to a pixmap and returns it.
  9371. The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and
  9372. scale 2.0 lead to a full resolution pixmap with width 200.)
  9373. \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf
  9374. */
  9375. QPixmap QCustomPlot::toPixmap(int width, int height, double scale)
  9376. {
  9377. // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too.
  9378. int newWidth, newHeight;
  9379. if (width == 0 || height == 0)
  9380. {
  9381. newWidth = this->width();
  9382. newHeight = this->height();
  9383. } else
  9384. {
  9385. newWidth = width;
  9386. newHeight = height;
  9387. }
  9388. int scaledWidth = qRound(scale*newWidth);
  9389. int scaledHeight = qRound(scale*newHeight);
  9390. QPixmap result(scaledWidth, scaledHeight);
  9391. result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later
  9392. QCPPainter painter;
  9393. painter.begin(&result);
  9394. if (painter.isActive())
  9395. {
  9396. QRect oldViewport = viewport();
  9397. setViewport(QRect(0, 0, newWidth, newHeight));
  9398. painter.setMode(QCPPainter::pmNoCaching);
  9399. if (!qFuzzyCompare(scale, 1.0))
  9400. {
  9401. if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales
  9402. painter.setMode(QCPPainter::pmNonCosmetic);
  9403. painter.scale(scale, scale);
  9404. }
  9405. if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush)
  9406. painter.fillRect(mViewport, mBackgroundBrush);
  9407. draw(&painter);
  9408. setViewport(oldViewport);
  9409. painter.end();
  9410. } else // might happen if pixmap has width or height zero
  9411. {
  9412. qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap";
  9413. return QPixmap();
  9414. }
  9415. return result;
  9416. }
  9417. /*!
  9418. Renders the plot using the passed \a painter.
  9419. 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
  9420. appear scaled accordingly.
  9421. \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter
  9422. on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with
  9423. the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter.
  9424. \see toPixmap
  9425. */
  9426. void QCustomPlot::toPainter(QCPPainter *painter, int width, int height)
  9427. {
  9428. // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too.
  9429. int newWidth, newHeight;
  9430. if (width == 0 || height == 0)
  9431. {
  9432. newWidth = this->width();
  9433. newHeight = this->height();
  9434. } else
  9435. {
  9436. newWidth = width;
  9437. newHeight = height;
  9438. }
  9439. if (painter->isActive())
  9440. {
  9441. QRect oldViewport = viewport();
  9442. setViewport(QRect(0, 0, newWidth, newHeight));
  9443. painter->setMode(QCPPainter::pmNoCaching);
  9444. // warning: the following is different in toPixmap, because a solid background color is applied there via QPixmap::fill
  9445. // here, we need to do this via QPainter::fillRect.
  9446. if (mBackgroundBrush.style() != Qt::NoBrush)
  9447. painter->fillRect(mViewport, mBackgroundBrush);
  9448. draw(painter);
  9449. setViewport(oldViewport);
  9450. } else
  9451. qDebug() << Q_FUNC_INFO << "Passed painter is not active";
  9452. }
  9453. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9454. //////////////////// QCPColorGradient
  9455. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9456. /*! \class QCPColorGradient
  9457. \brief Defines a color gradient for use with e.g. \ref QCPColorMap
  9458. This class describes a color gradient which can be used to encode data with color. For example,
  9459. QCPColorMap and QCPColorScale have a \ref QCPColorMap::setGradient "setGradient" method which
  9460. takes an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color)
  9461. with a \a position from 0 to 1. In between these defined color positions, the
  9462. color will be interpolated linearly either in RGB or HSV space, see \ref setColorInterpolation.
  9463. Alternatively, load one of the preset color gradients shown in the image below, with \ref
  9464. loadPreset, or by directly specifying the preset in the constructor.
  9465. \image html QCPColorGradient.png
  9466. The fact that the \ref QCPColorGradient(GradientPreset preset) constructor allows directly
  9467. converting a \ref GradientPreset to a QCPColorGradient, you can also directly pass \ref
  9468. GradientPreset to all the \a setGradient methods, e.g.:
  9469. \code
  9470. colorMap->setGradient(QCPColorGradient::gpHot);
  9471. \endcode
  9472. The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the
  9473. color gradient shall be applied periodically (wrapping around) to data values that lie outside
  9474. the data range specified on the plottable instance can be controlled with \ref setPeriodic.
  9475. */
  9476. /*!
  9477. Constructs a new QCPColorGradient initialized with the colors and color interpolation according
  9478. to \a preset.
  9479. The color level count is initialized to 350.
  9480. */
  9481. QCPColorGradient::QCPColorGradient(GradientPreset preset) :
  9482. mLevelCount(350),
  9483. mColorInterpolation(ciRGB),
  9484. mPeriodic(false),
  9485. mColorBufferInvalidated(true)
  9486. {
  9487. mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
  9488. loadPreset(preset);
  9489. }
  9490. /* undocumented operator */
  9491. bool QCPColorGradient::operator==(const QCPColorGradient &other) const
  9492. {
  9493. return ((other.mLevelCount == this->mLevelCount) &&
  9494. (other.mColorInterpolation == this->mColorInterpolation) &&
  9495. (other.mPeriodic == this->mPeriodic) &&
  9496. (other.mColorStops == this->mColorStops));
  9497. }
  9498. /*!
  9499. Sets the number of discretization levels of the color gradient to \a n. The default is 350 which
  9500. is typically enough to create a smooth appearance.
  9501. \image html QCPColorGradient-levelcount.png
  9502. */
  9503. void QCPColorGradient::setLevelCount(int n)
  9504. {
  9505. if (n < 2)
  9506. {
  9507. qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n;
  9508. n = 2;
  9509. }
  9510. if (n != mLevelCount)
  9511. {
  9512. mLevelCount = n;
  9513. mColorBufferInvalidated = true;
  9514. }
  9515. }
  9516. /*!
  9517. Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the
  9518. colors are the values of the passed QMap \a colorStops. In between these color stops, the color
  9519. is interpolated according to \ref setColorInterpolation.
  9520. A more convenient way to create a custom gradient may be to clear all color stops with \ref
  9521. clearColorStops and then adding them one by one with \ref setColorStopAt.
  9522. \see clearColorStops
  9523. */
  9524. void QCPColorGradient::setColorStops(const QMap<double, QColor> &colorStops)
  9525. {
  9526. mColorStops = colorStops;
  9527. mColorBufferInvalidated = true;
  9528. }
  9529. /*!
  9530. Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between
  9531. these color stops, the color is interpolated according to \ref setColorInterpolation.
  9532. \see setColorStops, clearColorStops
  9533. */
  9534. void QCPColorGradient::setColorStopAt(double position, const QColor &color)
  9535. {
  9536. mColorStops.insert(position, color);
  9537. mColorBufferInvalidated = true;
  9538. }
  9539. /*!
  9540. Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be
  9541. interpolated linearly in RGB or in HSV color space.
  9542. For example, a sweep in RGB space from red to green will have a muddy brown intermediate color,
  9543. whereas in HSV space the intermediate color is yellow.
  9544. */
  9545. void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation)
  9546. {
  9547. if (interpolation != mColorInterpolation)
  9548. {
  9549. mColorInterpolation = interpolation;
  9550. mColorBufferInvalidated = true;
  9551. }
  9552. }
  9553. /*!
  9554. Sets whether data points that are outside the configured data range (e.g. \ref
  9555. QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether
  9556. they all have the same color, corresponding to the respective gradient boundary color.
  9557. \image html QCPColorGradient-periodic.png
  9558. As shown in the image above, gradients that have the same start and end color are especially
  9559. suitable for a periodic gradient mapping, since they produce smooth color transitions throughout
  9560. the color map. A preset that has this property is \ref gpHues.
  9561. In practice, using periodic color gradients makes sense when the data corresponds to a periodic
  9562. dimension, such as an angle or a phase. If this is not the case, the color encoding might become
  9563. ambiguous, because multiple different data values are shown as the same color.
  9564. */
  9565. void QCPColorGradient::setPeriodic(bool enabled)
  9566. {
  9567. mPeriodic = enabled;
  9568. }
  9569. /*!
  9570. This method is used to quickly convert a \a data array to colors. The colors will be output in
  9571. the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this
  9572. function. The data range that shall be used for mapping the data value to the gradient is passed
  9573. in \a range. \a logarithmic indicates whether the data values shall be mapped to colors
  9574. logarithmically.
  9575. if \a data actually contains 2D-data linearized via <tt>[row*columnCount + column]</tt>, you can
  9576. set \a dataIndexFactor to <tt>columnCount</tt> to convert a column instead of a row of the data
  9577. array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data
  9578. is addressed <tt>data[i*dataIndexFactor]</tt>.
  9579. */
  9580. void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
  9581. {
  9582. // If you change something here, make sure to also adapt ::color()
  9583. if (!data)
  9584. {
  9585. qDebug() << Q_FUNC_INFO << "null pointer given as data";
  9586. return;
  9587. }
  9588. if (!scanLine)
  9589. {
  9590. qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
  9591. return;
  9592. }
  9593. if (mColorBufferInvalidated)
  9594. updateColorBuffer();
  9595. if (!logarithmic)
  9596. {
  9597. const double posToIndexFactor = mLevelCount/range.size();
  9598. if (mPeriodic)
  9599. {
  9600. for (int i=0; i<n; ++i)
  9601. {
  9602. int index = (int)((data[dataIndexFactor*i]-range.lower)*posToIndexFactor) % mLevelCount;
  9603. if (index < 0)
  9604. index += mLevelCount;
  9605. scanLine[i] = mColorBuffer.at(index);
  9606. }
  9607. } else
  9608. {
  9609. for (int i=0; i<n; ++i)
  9610. {
  9611. int index = (data[dataIndexFactor*i]-range.lower)*posToIndexFactor;
  9612. if (index < 0)
  9613. index = 0;
  9614. else if (index >= mLevelCount)
  9615. index = mLevelCount-1;
  9616. scanLine[i] = mColorBuffer.at(index);
  9617. }
  9618. }
  9619. } else // logarithmic == true
  9620. {
  9621. if (mPeriodic)
  9622. {
  9623. for (int i=0; i<n; ++i)
  9624. {
  9625. int index = (int)(qLn(data[dataIndexFactor*i]/range.lower)/qLn(range.upper/range.lower)*mLevelCount) % mLevelCount;
  9626. if (index < 0)
  9627. index += mLevelCount;
  9628. scanLine[i] = mColorBuffer.at(index);
  9629. }
  9630. } else
  9631. {
  9632. for (int i=0; i<n; ++i)
  9633. {
  9634. int index = qLn(data[dataIndexFactor*i]/range.lower)/qLn(range.upper/range.lower)*mLevelCount;
  9635. if (index < 0)
  9636. index = 0;
  9637. else if (index >= mLevelCount)
  9638. index = mLevelCount-1;
  9639. scanLine[i] = mColorBuffer.at(index);
  9640. }
  9641. }
  9642. }
  9643. }
  9644. /*! \internal
  9645. This method is used to colorize a single data value given in \a position, to colors. The data
  9646. range that shall be used for mapping the data value to the gradient is passed in \a range. \a
  9647. logarithmic indicates whether the data value shall be mapped to a color logarithmically.
  9648. If an entire array of data values shall be converted, rather use \ref colorize, for better
  9649. performance.
  9650. */
  9651. QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic)
  9652. {
  9653. // If you change something here, make sure to also adapt ::colorize()
  9654. if (mColorBufferInvalidated)
  9655. updateColorBuffer();
  9656. int index = 0;
  9657. if (!logarithmic)
  9658. index = (position-range.lower)*mLevelCount/range.size();
  9659. else
  9660. index = qLn(position/range.lower)/qLn(range.upper/range.lower)*mLevelCount;
  9661. if (mPeriodic)
  9662. {
  9663. index = index % mLevelCount;
  9664. if (index < 0)
  9665. index += mLevelCount;
  9666. } else
  9667. {
  9668. if (index < 0)
  9669. index = 0;
  9670. else if (index >= mLevelCount)
  9671. index = mLevelCount-1;
  9672. }
  9673. return mColorBuffer.at(index);
  9674. }
  9675. /*!
  9676. Clears the current color stops and loads the specified \a preset. A preset consists of predefined
  9677. color stops and the corresponding color interpolation method.
  9678. The available presets are:
  9679. \image html QCPColorGradient.png
  9680. */
  9681. void QCPColorGradient::loadPreset(GradientPreset preset)
  9682. {
  9683. clearColorStops();
  9684. switch (preset)
  9685. {
  9686. case gpGrayscale:
  9687. setColorInterpolation(ciRGB);
  9688. setColorStopAt(0, Qt::black);
  9689. setColorStopAt(1, Qt::white);
  9690. break;
  9691. case gpHot:
  9692. setColorInterpolation(ciRGB);
  9693. setColorStopAt(0, QColor(50, 0, 0));
  9694. setColorStopAt(0.2, QColor(180, 10, 0));
  9695. setColorStopAt(0.4, QColor(245, 50, 0));
  9696. setColorStopAt(0.6, QColor(255, 150, 10));
  9697. setColorStopAt(0.8, QColor(255, 255, 50));
  9698. setColorStopAt(1, QColor(255, 255, 255));
  9699. break;
  9700. case gpCold:
  9701. setColorInterpolation(ciRGB);
  9702. setColorStopAt(0, QColor(0, 0, 50));
  9703. setColorStopAt(0.2, QColor(0, 10, 180));
  9704. setColorStopAt(0.4, QColor(0, 50, 245));
  9705. setColorStopAt(0.6, QColor(10, 150, 255));
  9706. setColorStopAt(0.8, QColor(50, 255, 255));
  9707. setColorStopAt(1, QColor(255, 255, 255));
  9708. break;
  9709. case gpNight:
  9710. setColorInterpolation(ciHSV);
  9711. setColorStopAt(0, QColor(10, 20, 30));
  9712. setColorStopAt(1, QColor(250, 255, 250));
  9713. break;
  9714. case gpCandy:
  9715. setColorInterpolation(ciHSV);
  9716. setColorStopAt(0, QColor(0, 0, 255));
  9717. setColorStopAt(1, QColor(255, 250, 250));
  9718. break;
  9719. case gpGeography:
  9720. setColorInterpolation(ciRGB);
  9721. setColorStopAt(0, QColor(70, 170, 210));
  9722. setColorStopAt(0.20, QColor(90, 160, 180));
  9723. setColorStopAt(0.25, QColor(45, 130, 175));
  9724. setColorStopAt(0.30, QColor(100, 140, 125));
  9725. setColorStopAt(0.5, QColor(100, 140, 100));
  9726. setColorStopAt(0.6, QColor(130, 145, 120));
  9727. setColorStopAt(0.7, QColor(140, 130, 120));
  9728. setColorStopAt(0.9, QColor(180, 190, 190));
  9729. setColorStopAt(1, QColor(210, 210, 230));
  9730. break;
  9731. case gpIon:
  9732. setColorInterpolation(ciHSV);
  9733. setColorStopAt(0, QColor(50, 10, 10));
  9734. setColorStopAt(0.45, QColor(0, 0, 255));
  9735. setColorStopAt(0.8, QColor(0, 255, 255));
  9736. setColorStopAt(1, QColor(0, 255, 0));
  9737. break;
  9738. case gpThermal:
  9739. setColorInterpolation(ciRGB);
  9740. setColorStopAt(0, QColor(0, 0, 50));
  9741. setColorStopAt(0.15, QColor(20, 0, 120));
  9742. setColorStopAt(0.33, QColor(200, 30, 140));
  9743. setColorStopAt(0.6, QColor(255, 100, 0));
  9744. setColorStopAt(0.85, QColor(255, 255, 40));
  9745. setColorStopAt(1, QColor(255, 255, 255));
  9746. break;
  9747. case gpPolar:
  9748. setColorInterpolation(ciRGB);
  9749. setColorStopAt(0, QColor(50, 255, 255));
  9750. setColorStopAt(0.18, QColor(10, 70, 255));
  9751. setColorStopAt(0.28, QColor(10, 10, 190));
  9752. setColorStopAt(0.5, QColor(0, 0, 0));
  9753. setColorStopAt(0.72, QColor(190, 10, 10));
  9754. setColorStopAt(0.82, QColor(255, 70, 10));
  9755. setColorStopAt(1, QColor(255, 255, 50));
  9756. break;
  9757. case gpSpectrum:
  9758. setColorInterpolation(ciHSV);
  9759. setColorStopAt(0, QColor(50, 0, 50));
  9760. setColorStopAt(0.15, QColor(0, 0, 255));
  9761. setColorStopAt(0.35, QColor(0, 255, 255));
  9762. setColorStopAt(0.6, QColor(255, 255, 0));
  9763. setColorStopAt(0.75, QColor(255, 30, 0));
  9764. setColorStopAt(1, QColor(50, 0, 0));
  9765. break;
  9766. case gpJet:
  9767. setColorInterpolation(ciRGB);
  9768. setColorStopAt(0, QColor(0, 0, 100));
  9769. setColorStopAt(0.15, QColor(0, 50, 255));
  9770. setColorStopAt(0.35, QColor(0, 255, 255));
  9771. setColorStopAt(0.65, QColor(255, 255, 0));
  9772. setColorStopAt(0.85, QColor(255, 30, 0));
  9773. setColorStopAt(1, QColor(100, 0, 0));
  9774. break;
  9775. case gpHues:
  9776. setColorInterpolation(ciHSV);
  9777. setColorStopAt(0, QColor(255, 0, 0));
  9778. setColorStopAt(1.0/3.0, QColor(0, 0, 255));
  9779. setColorStopAt(2.0/3.0, QColor(0, 255, 0));
  9780. setColorStopAt(1, QColor(255, 0, 0));
  9781. break;
  9782. }
  9783. }
  9784. /*!
  9785. Clears all color stops.
  9786. \see setColorStops, setColorStopAt
  9787. */
  9788. void QCPColorGradient::clearColorStops()
  9789. {
  9790. mColorStops.clear();
  9791. mColorBufferInvalidated = true;
  9792. }
  9793. /*!
  9794. Returns an inverted gradient. The inverted gradient has all properties as this \ref
  9795. QCPColorGradient, but the order of the color stops is inverted.
  9796. \see setColorStops, setColorStopAt
  9797. */
  9798. QCPColorGradient QCPColorGradient::inverted() const
  9799. {
  9800. QCPColorGradient result(*this);
  9801. result.clearColorStops();
  9802. for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
  9803. result.setColorStopAt(1.0-it.key(), it.value());
  9804. return result;
  9805. }
  9806. /*! \internal
  9807. Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly
  9808. convert positions to colors. This is where the interpolation between color stops is calculated.
  9809. */
  9810. void QCPColorGradient::updateColorBuffer()
  9811. {
  9812. if (mColorBuffer.size() != mLevelCount)
  9813. mColorBuffer.resize(mLevelCount);
  9814. if (mColorStops.size() > 1)
  9815. {
  9816. double indexToPosFactor = 1.0/(double)(mLevelCount-1);
  9817. for (int i=0; i<mLevelCount; ++i)
  9818. {
  9819. double position = i*indexToPosFactor;
  9820. QMap<double, QColor>::const_iterator it = mColorStops.lowerBound(position);
  9821. if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop
  9822. {
  9823. mColorBuffer[i] = (it-1).value().rgb();
  9824. } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop
  9825. {
  9826. mColorBuffer[i] = it.value().rgb();
  9827. } else // position is in between stops (or on an intermediate stop), interpolate color
  9828. {
  9829. QMap<double, QColor>::const_iterator high = it;
  9830. QMap<double, QColor>::const_iterator low = it-1;
  9831. double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1
  9832. switch (mColorInterpolation)
  9833. {
  9834. case ciRGB:
  9835. {
  9836. mColorBuffer[i] = qRgb((1-t)*low.value().red() + t*high.value().red(),
  9837. (1-t)*low.value().green() + t*high.value().green(),
  9838. (1-t)*low.value().blue() + t*high.value().blue());
  9839. break;
  9840. }
  9841. case ciHSV:
  9842. {
  9843. QColor lowHsv = low.value().toHsv();
  9844. QColor highHsv = high.value().toHsv();
  9845. double hue = 0;
  9846. double hueDiff = highHsv.hueF()-lowHsv.hueF();
  9847. if (hueDiff > 0.5)
  9848. hue = lowHsv.hueF() - t*(1.0-hueDiff);
  9849. else if (hueDiff < -0.5)
  9850. hue = lowHsv.hueF() + t*(1.0+hueDiff);
  9851. else
  9852. hue = lowHsv.hueF() + t*hueDiff;
  9853. if (hue < 0) hue += 1.0;
  9854. else if (hue >= 1.0) hue -= 1.0;
  9855. mColorBuffer[i] = QColor::fromHsvF(hue, (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(), (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
  9856. break;
  9857. }
  9858. }
  9859. }
  9860. }
  9861. } else if (mColorStops.size() == 1)
  9862. {
  9863. mColorBuffer.fill(mColorStops.constBegin().value().rgb());
  9864. } else // mColorStops is empty, fill color buffer with black
  9865. {
  9866. mColorBuffer.fill(qRgb(0, 0, 0));
  9867. }
  9868. mColorBufferInvalidated = false;
  9869. }
  9870. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9871. //////////////////// QCPAxisRect
  9872. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9873. /*! \class QCPAxisRect
  9874. \brief Holds multiple axes and arranges them in a rectangular shape.
  9875. This class represents an axis rect, a rectangular area that is bounded on all sides with an
  9876. arbitrary number of axes.
  9877. Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the
  9878. layout system allows to have multiple axis rects, e.g. arranged in a grid layout
  9879. (QCustomPlot::plotLayout).
  9880. By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be
  9881. accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index.
  9882. If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be
  9883. invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref
  9884. addAxes. To remove an axis, use \ref removeAxis.
  9885. The axis rect layerable itself only draws a background pixmap or color, if specified (\ref
  9886. setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an
  9887. explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be
  9888. placed on other layers, independently of the axis rect.
  9889. Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref
  9890. insetLayout and can be used to have other layout elements (or even other layouts with multiple
  9891. elements) hovering inside the axis rect.
  9892. If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The
  9893. behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel
  9894. is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable
  9895. via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are
  9896. only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref
  9897. QCP::iRangeZoom.
  9898. \image html AxisRectSpacingOverview.png
  9899. <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed
  9900. line on the far left indicates the viewport/widget border.</center>
  9901. */
  9902. /* start documentation of inline functions */
  9903. /*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const
  9904. Returns the inset layout of this axis rect. It can be used to place other layout elements (or
  9905. even layouts with multiple other elements) inside/on top of an axis rect.
  9906. \see QCPLayoutInset
  9907. */
  9908. /*! \fn int QCPAxisRect::left() const
  9909. Returns the pixel position of the left border of this axis rect. Margins are not taken into
  9910. account here, so the returned value is with respect to the inner \ref rect.
  9911. */
  9912. /*! \fn int QCPAxisRect::right() const
  9913. Returns the pixel position of the right border of this axis rect. Margins are not taken into
  9914. account here, so the returned value is with respect to the inner \ref rect.
  9915. */
  9916. /*! \fn int QCPAxisRect::top() const
  9917. Returns the pixel position of the top border of this axis rect. Margins are not taken into
  9918. account here, so the returned value is with respect to the inner \ref rect.
  9919. */
  9920. /*! \fn int QCPAxisRect::bottom() const
  9921. Returns the pixel position of the bottom border of this axis rect. Margins are not taken into
  9922. account here, so the returned value is with respect to the inner \ref rect.
  9923. */
  9924. /*! \fn int QCPAxisRect::width() const
  9925. Returns the pixel width of this axis rect. Margins are not taken into account here, so the
  9926. returned value is with respect to the inner \ref rect.
  9927. */
  9928. /*! \fn int QCPAxisRect::height() const
  9929. Returns the pixel height of this axis rect. Margins are not taken into account here, so the
  9930. returned value is with respect to the inner \ref rect.
  9931. */
  9932. /*! \fn QSize QCPAxisRect::size() const
  9933. Returns the pixel size of this axis rect. Margins are not taken into account here, so the
  9934. returned value is with respect to the inner \ref rect.
  9935. */
  9936. /*! \fn QPoint QCPAxisRect::topLeft() const
  9937. Returns the top left corner of this axis rect in pixels. Margins are not taken into account here,
  9938. so the returned value is with respect to the inner \ref rect.
  9939. */
  9940. /*! \fn QPoint QCPAxisRect::topRight() const
  9941. Returns the top right corner of this axis rect in pixels. Margins are not taken into account
  9942. here, so the returned value is with respect to the inner \ref rect.
  9943. */
  9944. /*! \fn QPoint QCPAxisRect::bottomLeft() const
  9945. Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account
  9946. here, so the returned value is with respect to the inner \ref rect.
  9947. */
  9948. /*! \fn QPoint QCPAxisRect::bottomRight() const
  9949. Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account
  9950. here, so the returned value is with respect to the inner \ref rect.
  9951. */
  9952. /*! \fn QPoint QCPAxisRect::center() const
  9953. Returns the center of this axis rect in pixels. Margins are not taken into account here, so the
  9954. returned value is with respect to the inner \ref rect.
  9955. */
  9956. /* end documentation of inline functions */
  9957. /*!
  9958. Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four
  9959. sides, the top and right axes are set invisible initially.
  9960. */
  9961. QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) :
  9962. QCPLayoutElement(parentPlot),
  9963. mBackgroundBrush(Qt::NoBrush),
  9964. mBackgroundScaled(true),
  9965. mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
  9966. mInsetLayout(new QCPLayoutInset),
  9967. mRangeDrag(Qt::Horizontal|Qt::Vertical),
  9968. mRangeZoom(Qt::Horizontal|Qt::Vertical),
  9969. mRangeZoomFactorHorz(0.85),
  9970. mRangeZoomFactorVert(0.85),
  9971. mDragging(false)
  9972. {
  9973. mInsetLayout->initializeParentPlot(mParentPlot);
  9974. mInsetLayout->setParentLayerable(this);
  9975. mInsetLayout->setParent(this);
  9976. setMinimumSize(50, 50);
  9977. setMinimumMargins(QMargins(15, 15, 15, 15));
  9978. mAxes.insert(QCPAxis::atLeft, QList<QCPAxis*>());
  9979. mAxes.insert(QCPAxis::atRight, QList<QCPAxis*>());
  9980. mAxes.insert(QCPAxis::atTop, QList<QCPAxis*>());
  9981. mAxes.insert(QCPAxis::atBottom, QList<QCPAxis*>());
  9982. if (setupDefaultAxes)
  9983. {
  9984. QCPAxis *xAxis = addAxis(QCPAxis::atBottom);
  9985. QCPAxis *yAxis = addAxis(QCPAxis::atLeft);
  9986. QCPAxis *xAxis2 = addAxis(QCPAxis::atTop);
  9987. QCPAxis *yAxis2 = addAxis(QCPAxis::atRight);
  9988. setRangeDragAxes(xAxis, yAxis);
  9989. setRangeZoomAxes(xAxis, yAxis);
  9990. xAxis2->setVisible(false);
  9991. yAxis2->setVisible(false);
  9992. xAxis->grid()->setVisible(true);
  9993. yAxis->grid()->setVisible(true);
  9994. xAxis2->grid()->setVisible(false);
  9995. yAxis2->grid()->setVisible(false);
  9996. xAxis2->grid()->setZeroLinePen(Qt::NoPen);
  9997. yAxis2->grid()->setZeroLinePen(Qt::NoPen);
  9998. xAxis2->grid()->setVisible(false);
  9999. yAxis2->grid()->setVisible(false);
  10000. }
  10001. }
  10002. QCPAxisRect::~QCPAxisRect()
  10003. {
  10004. delete mInsetLayout;
  10005. mInsetLayout = 0;
  10006. QList<QCPAxis*> axesList = axes();
  10007. for (int i=0; i<axesList.size(); ++i)
  10008. removeAxis(axesList.at(i));
  10009. }
  10010. /*!
  10011. Returns the number of axes on the axis rect side specified with \a type.
  10012. \see axis
  10013. */
  10014. int QCPAxisRect::axisCount(QCPAxis::AxisType type) const
  10015. {
  10016. return mAxes.value(type).size();
  10017. }
  10018. /*!
  10019. Returns the axis with the given \a index on the axis rect side specified with \a type.
  10020. \see axisCount, axes
  10021. */
  10022. QCPAxis *QCPAxisRect::axis(QCPAxis::AxisType type, int index) const
  10023. {
  10024. QList<QCPAxis*> ax(mAxes.value(type));
  10025. if (index >= 0 && index < ax.size())
  10026. {
  10027. return ax.at(index);
  10028. } else
  10029. {
  10030. qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index;
  10031. return 0;
  10032. }
  10033. }
  10034. /*!
  10035. Returns all axes on the axis rect sides specified with \a types.
  10036. \a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of
  10037. multiple sides.
  10038. \see axis
  10039. */
  10040. QList<QCPAxis*> QCPAxisRect::axes(QCPAxis::AxisTypes types) const
  10041. {
  10042. QList<QCPAxis*> result;
  10043. if (types.testFlag(QCPAxis::atLeft))
  10044. result << mAxes.value(QCPAxis::atLeft);
  10045. if (types.testFlag(QCPAxis::atRight))
  10046. result << mAxes.value(QCPAxis::atRight);
  10047. if (types.testFlag(QCPAxis::atTop))
  10048. result << mAxes.value(QCPAxis::atTop);
  10049. if (types.testFlag(QCPAxis::atBottom))
  10050. result << mAxes.value(QCPAxis::atBottom);
  10051. return result;
  10052. }
  10053. /*! \overload
  10054. Returns all axes of this axis rect.
  10055. */
  10056. QList<QCPAxis*> QCPAxisRect::axes() const
  10057. {
  10058. QList<QCPAxis*> result;
  10059. QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
  10060. while (it.hasNext())
  10061. {
  10062. it.next();
  10063. result << it.value();
  10064. }
  10065. return result;
  10066. }
  10067. /*!
  10068. Adds a new axis to the axis rect side specified with \a type, and returns it.
  10069. If an axis rect side already contains one or more axes, the lower and upper endings of the new
  10070. axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are initialized to \ref
  10071. QCPLineEnding::esHalfBar.
  10072. \see addAxes, setupFullAxesBox
  10073. */
  10074. QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type)
  10075. {
  10076. QCPAxis *newAxis = new QCPAxis(this, type);
  10077. if (mAxes[type].size() > 0) // multiple axes on one side, add half-bar axis ending to additional axes with offset
  10078. {
  10079. bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom);
  10080. newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert));
  10081. newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert));
  10082. }
  10083. mAxes[type].append(newAxis);
  10084. return newAxis;
  10085. }
  10086. /*!
  10087. Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an
  10088. <tt>or</tt>-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once.
  10089. Returns a list of the added axes.
  10090. \see addAxis, setupFullAxesBox
  10091. */
  10092. QList<QCPAxis*> QCPAxisRect::addAxes(QCPAxis::AxisTypes types)
  10093. {
  10094. QList<QCPAxis*> result;
  10095. if (types.testFlag(QCPAxis::atLeft))
  10096. result << addAxis(QCPAxis::atLeft);
  10097. if (types.testFlag(QCPAxis::atRight))
  10098. result << addAxis(QCPAxis::atRight);
  10099. if (types.testFlag(QCPAxis::atTop))
  10100. result << addAxis(QCPAxis::atTop);
  10101. if (types.testFlag(QCPAxis::atBottom))
  10102. result << addAxis(QCPAxis::atBottom);
  10103. return result;
  10104. }
  10105. /*!
  10106. Removes the specified \a axis from the axis rect and deletes it.
  10107. Returns true on success, i.e. if \a axis was a valid axis in this axis rect.
  10108. \see addAxis
  10109. */
  10110. bool QCPAxisRect::removeAxis(QCPAxis *axis)
  10111. {
  10112. // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers:
  10113. QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
  10114. while (it.hasNext())
  10115. {
  10116. it.next();
  10117. if (it.value().contains(axis))
  10118. {
  10119. mAxes[it.key()].removeOne(axis);
  10120. 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)
  10121. parentPlot()->axisRemoved(axis);
  10122. delete axis;
  10123. return true;
  10124. }
  10125. }
  10126. qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast<quintptr>(axis);
  10127. return false;
  10128. }
  10129. /*!
  10130. Convenience function to create an axis on each side that doesn't have any axes yet and set their
  10131. visibility to true. Further, the top/right axes are assigned the following properties of the
  10132. bottom/left axes:
  10133. \li range (\ref QCPAxis::setRange)
  10134. \li range reversed (\ref QCPAxis::setRangeReversed)
  10135. \li scale type (\ref QCPAxis::setScaleType)
  10136. \li scale log base (\ref QCPAxis::setScaleLogBase)
  10137. \li ticks (\ref QCPAxis::setTicks)
  10138. \li auto (major) tick count (\ref QCPAxis::setAutoTickCount)
  10139. \li sub tick count (\ref QCPAxis::setSubTickCount)
  10140. \li auto sub ticks (\ref QCPAxis::setAutoSubTicks)
  10141. \li tick step (\ref QCPAxis::setTickStep)
  10142. \li auto tick step (\ref QCPAxis::setAutoTickStep)
  10143. \li number format (\ref QCPAxis::setNumberFormat)
  10144. \li number precision (\ref QCPAxis::setNumberPrecision)
  10145. \li tick label type (\ref QCPAxis::setTickLabelType)
  10146. \li date time format (\ref QCPAxis::setDateTimeFormat)
  10147. \li date time spec (\ref QCPAxis::setDateTimeSpec)
  10148. Tick labels (\ref QCPAxis::setTickLabels) of the right and top axes are set to false.
  10149. If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom
  10150. and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes.
  10151. */
  10152. void QCPAxisRect::setupFullAxesBox(bool connectRanges)
  10153. {
  10154. QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2;
  10155. if (axisCount(QCPAxis::atBottom) == 0)
  10156. xAxis = addAxis(QCPAxis::atBottom);
  10157. else
  10158. xAxis = axis(QCPAxis::atBottom);
  10159. if (axisCount(QCPAxis::atLeft) == 0)
  10160. yAxis = addAxis(QCPAxis::atLeft);
  10161. else
  10162. yAxis = axis(QCPAxis::atLeft);
  10163. if (axisCount(QCPAxis::atTop) == 0)
  10164. xAxis2 = addAxis(QCPAxis::atTop);
  10165. else
  10166. xAxis2 = axis(QCPAxis::atTop);
  10167. if (axisCount(QCPAxis::atRight) == 0)
  10168. yAxis2 = addAxis(QCPAxis::atRight);
  10169. else
  10170. yAxis2 = axis(QCPAxis::atRight);
  10171. xAxis->setVisible(true);
  10172. yAxis->setVisible(true);
  10173. xAxis2->setVisible(true);
  10174. yAxis2->setVisible(true);
  10175. xAxis2->setTickLabels(false);
  10176. yAxis2->setTickLabels(false);
  10177. xAxis2->setRange(xAxis->range());
  10178. xAxis2->setRangeReversed(xAxis->rangeReversed());
  10179. xAxis2->setScaleType(xAxis->scaleType());
  10180. xAxis2->setScaleLogBase(xAxis->scaleLogBase());
  10181. xAxis2->setTicks(xAxis->ticks());
  10182. xAxis2->setAutoTickCount(xAxis->autoTickCount());
  10183. xAxis2->setSubTickCount(xAxis->subTickCount());
  10184. xAxis2->setAutoSubTicks(xAxis->autoSubTicks());
  10185. xAxis2->setTickStep(xAxis->tickStep());
  10186. xAxis2->setAutoTickStep(xAxis->autoTickStep());
  10187. xAxis2->setNumberFormat(xAxis->numberFormat());
  10188. xAxis2->setNumberPrecision(xAxis->numberPrecision());
  10189. xAxis2->setTickLabelType(xAxis->tickLabelType());
  10190. xAxis2->setDateTimeFormat(xAxis->dateTimeFormat());
  10191. xAxis2->setDateTimeSpec(xAxis->dateTimeSpec());
  10192. yAxis2->setRange(yAxis->range());
  10193. yAxis2->setRangeReversed(yAxis->rangeReversed());
  10194. yAxis2->setScaleType(yAxis->scaleType());
  10195. yAxis2->setScaleLogBase(yAxis->scaleLogBase());
  10196. yAxis2->setTicks(yAxis->ticks());
  10197. yAxis2->setAutoTickCount(yAxis->autoTickCount());
  10198. yAxis2->setSubTickCount(yAxis->subTickCount());
  10199. yAxis2->setAutoSubTicks(yAxis->autoSubTicks());
  10200. yAxis2->setTickStep(yAxis->tickStep());
  10201. yAxis2->setAutoTickStep(yAxis->autoTickStep());
  10202. yAxis2->setNumberFormat(yAxis->numberFormat());
  10203. yAxis2->setNumberPrecision(yAxis->numberPrecision());
  10204. yAxis2->setTickLabelType(yAxis->tickLabelType());
  10205. yAxis2->setDateTimeFormat(yAxis->dateTimeFormat());
  10206. yAxis2->setDateTimeSpec(yAxis->dateTimeSpec());
  10207. if (connectRanges)
  10208. {
  10209. connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange)));
  10210. connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange)));
  10211. }
  10212. }
  10213. /*!
  10214. Returns a list of all the plottables that are associated with this axis rect.
  10215. A plottable is considered associated with an axis rect if its key or value axis (or both) is in
  10216. this axis rect.
  10217. \see graphs, items
  10218. */
  10219. QList<QCPAbstractPlottable*> QCPAxisRect::plottables() const
  10220. {
  10221. // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries
  10222. QList<QCPAbstractPlottable*> result;
  10223. for (int i=0; i<mParentPlot->mPlottables.size(); ++i)
  10224. {
  10225. if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this ||mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this)
  10226. result.append(mParentPlot->mPlottables.at(i));
  10227. }
  10228. return result;
  10229. }
  10230. /*!
  10231. Returns a list of all the graphs that are associated with this axis rect.
  10232. A graph is considered associated with an axis rect if its key or value axis (or both) is in
  10233. this axis rect.
  10234. \see plottables, items
  10235. */
  10236. QList<QCPGraph*> QCPAxisRect::graphs() const
  10237. {
  10238. // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries
  10239. QList<QCPGraph*> result;
  10240. for (int i=0; i<mParentPlot->mGraphs.size(); ++i)
  10241. {
  10242. if (mParentPlot->mGraphs.at(i)->keyAxis()->axisRect() == this || mParentPlot->mGraphs.at(i)->valueAxis()->axisRect() == this)
  10243. result.append(mParentPlot->mGraphs.at(i));
  10244. }
  10245. return result;
  10246. }
  10247. /*!
  10248. Returns a list of all the items that are associated with this axis rect.
  10249. An item is considered associated with an axis rect if any of its positions has key or value axis
  10250. set to an axis that is in this axis rect, or if any of its positions has \ref
  10251. QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref
  10252. QCPAbstractItem::setClipAxisRect) is set to this axis rect.
  10253. \see plottables, graphs
  10254. */
  10255. QList<QCPAbstractItem *> QCPAxisRect::items() const
  10256. {
  10257. // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries
  10258. // and miss those items that have this axis rect as clipAxisRect.
  10259. QList<QCPAbstractItem*> result;
  10260. for (int itemId=0; itemId<mParentPlot->mItems.size(); ++itemId)
  10261. {
  10262. if (mParentPlot->mItems.at(itemId)->clipAxisRect() == this)
  10263. {
  10264. result.append(mParentPlot->mItems.at(itemId));
  10265. continue;
  10266. }
  10267. QList<QCPItemPosition*> positions = mParentPlot->mItems.at(itemId)->positions();
  10268. for (int posId=0; posId<positions.size(); ++posId)
  10269. {
  10270. if (positions.at(posId)->axisRect() == this ||
  10271. positions.at(posId)->keyAxis()->axisRect() == this ||
  10272. positions.at(posId)->valueAxis()->axisRect() == this)
  10273. {
  10274. result.append(mParentPlot->mItems.at(itemId));
  10275. break;
  10276. }
  10277. }
  10278. }
  10279. return result;
  10280. }
  10281. /*!
  10282. This method is called automatically upon replot and doesn't need to be called by users of
  10283. QCPAxisRect.
  10284. Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
  10285. and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
  10286. QCPInsetLayout::update function.
  10287. */
  10288. void QCPAxisRect::update(UpdatePhase phase)
  10289. {
  10290. QCPLayoutElement::update(phase);
  10291. switch (phase)
  10292. {
  10293. case upPreparation:
  10294. {
  10295. QList<QCPAxis*> allAxes = axes();
  10296. for (int i=0; i<allAxes.size(); ++i)
  10297. allAxes.at(i)->setupTickVectors();
  10298. break;
  10299. }
  10300. case upLayout:
  10301. {
  10302. mInsetLayout->setOuterRect(rect());
  10303. break;
  10304. }
  10305. default: break;
  10306. }
  10307. // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout):
  10308. mInsetLayout->update(phase);
  10309. }
  10310. /* inherits documentation from base class */
  10311. QList<QCPLayoutElement*> QCPAxisRect::elements(bool recursive) const
  10312. {
  10313. QList<QCPLayoutElement*> result;
  10314. if (mInsetLayout)
  10315. {
  10316. result << mInsetLayout;
  10317. if (recursive)
  10318. result << mInsetLayout->elements(recursive);
  10319. }
  10320. return result;
  10321. }
  10322. /* inherits documentation from base class */
  10323. void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const
  10324. {
  10325. painter->setAntialiasing(false);
  10326. }
  10327. /* inherits documentation from base class */
  10328. void QCPAxisRect::draw(QCPPainter *painter)
  10329. {
  10330. drawBackground(painter);
  10331. }
  10332. /*!
  10333. Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the
  10334. axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect
  10335. backgrounds are usually drawn below everything else.
  10336. For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be
  10337. enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio
  10338. is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  10339. consider using the overloaded version of this function.
  10340. Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref
  10341. setBackground(const QBrush &brush).
  10342. \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush)
  10343. */
  10344. void QCPAxisRect::setBackground(const QPixmap &pm)
  10345. {
  10346. mBackgroundPixmap = pm;
  10347. mScaledBackgroundPixmap = QPixmap();
  10348. }
  10349. /*! \overload
  10350. Sets \a brush as the background brush. The axis rect background will be filled with this brush.
  10351. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds
  10352. are usually drawn below everything else.
  10353. The brush will be drawn before (under) any background pixmap, which may be specified with \ref
  10354. setBackground(const QPixmap &pm).
  10355. To disable drawing of a background brush, set \a brush to Qt::NoBrush.
  10356. \see setBackground(const QPixmap &pm)
  10357. */
  10358. void QCPAxisRect::setBackground(const QBrush &brush)
  10359. {
  10360. mBackgroundBrush = brush;
  10361. }
  10362. /*! \overload
  10363. Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it
  10364. shall be scaled in one call.
  10365. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  10366. */
  10367. void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
  10368. {
  10369. mBackgroundPixmap = pm;
  10370. mScaledBackgroundPixmap = QPixmap();
  10371. mBackgroundScaled = scaled;
  10372. mBackgroundScaledMode = mode;
  10373. }
  10374. /*!
  10375. Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled
  10376. is set to true, you may control whether and how the aspect ratio of the original pixmap is
  10377. preserved with \ref setBackgroundScaledMode.
  10378. Note that the scaled version of the original pixmap is buffered, so there is no performance
  10379. penalty on replots. (Except when the axis rect dimensions are changed continuously.)
  10380. \see setBackground, setBackgroundScaledMode
  10381. */
  10382. void QCPAxisRect::setBackgroundScaled(bool scaled)
  10383. {
  10384. mBackgroundScaled = scaled;
  10385. }
  10386. /*!
  10387. If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to
  10388. define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved.
  10389. \see setBackground, setBackgroundScaled
  10390. */
  10391. void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  10392. {
  10393. mBackgroundScaledMode = mode;
  10394. }
  10395. /*!
  10396. Returns the range drag axis of the \a orientation provided.
  10397. \see setRangeDragAxes
  10398. */
  10399. QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation)
  10400. {
  10401. return (orientation == Qt::Horizontal ? mRangeDragHorzAxis.data() : mRangeDragVertAxis.data());
  10402. }
  10403. /*!
  10404. Returns the range zoom axis of the \a orientation provided.
  10405. \see setRangeZoomAxes
  10406. */
  10407. QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation)
  10408. {
  10409. return (orientation == Qt::Horizontal ? mRangeZoomHorzAxis.data() : mRangeZoomVertAxis.data());
  10410. }
  10411. /*!
  10412. Returns the range zoom factor of the \a orientation provided.
  10413. \see setRangeZoomFactor
  10414. */
  10415. double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation)
  10416. {
  10417. return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert);
  10418. }
  10419. /*!
  10420. Sets which axis orientation may be range dragged by the user with mouse interaction.
  10421. What orientation corresponds to which specific axis can be set with
  10422. \ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By
  10423. default, the horizontal axis is the bottom axis (xAxis) and the vertical axis
  10424. is the left axis (yAxis).
  10425. To disable range dragging entirely, pass 0 as \a orientations or remove \ref QCP::iRangeDrag from \ref
  10426. QCustomPlot::setInteractions. To enable range dragging for both directions, pass <tt>Qt::Horizontal |
  10427. Qt::Vertical</tt> as \a orientations.
  10428. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
  10429. contains \ref QCP::iRangeDrag to enable the range dragging interaction.
  10430. \see setRangeZoom, setRangeDragAxes, setNoAntialiasingOnDrag
  10431. */
  10432. void QCPAxisRect::setRangeDrag(Qt::Orientations orientations)
  10433. {
  10434. mRangeDrag = orientations;
  10435. }
  10436. /*!
  10437. Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation
  10438. corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal,
  10439. QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical
  10440. axis is the left axis (yAxis).
  10441. To disable range zooming entirely, pass 0 as \a orientations or remove \ref QCP::iRangeZoom from \ref
  10442. QCustomPlot::setInteractions. To enable range zooming for both directions, pass <tt>Qt::Horizontal |
  10443. Qt::Vertical</tt> as \a orientations.
  10444. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
  10445. contains \ref QCP::iRangeZoom to enable the range zooming interaction.
  10446. \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag
  10447. */
  10448. void QCPAxisRect::setRangeZoom(Qt::Orientations orientations)
  10449. {
  10450. mRangeZoom = orientations;
  10451. }
  10452. /*!
  10453. Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging
  10454. on the QCustomPlot widget.
  10455. \see setRangeZoomAxes
  10456. */
  10457. void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical)
  10458. {
  10459. mRangeDragHorzAxis = horizontal;
  10460. mRangeDragVertAxis = vertical;
  10461. }
  10462. /*!
  10463. Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on the
  10464. QCustomPlot widget. The two axes can be zoomed with different strengths, when different factors
  10465. are passed to \ref setRangeZoomFactor(double horizontalFactor, double verticalFactor).
  10466. \see setRangeDragAxes
  10467. */
  10468. void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical)
  10469. {
  10470. mRangeZoomHorzAxis = horizontal;
  10471. mRangeZoomVertAxis = vertical;
  10472. }
  10473. /*!
  10474. Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with
  10475. \ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to
  10476. let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal
  10477. and which is vertical, can be set with \ref setRangeZoomAxes.
  10478. When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user)
  10479. will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the
  10480. same scrolling direction will zoom out.
  10481. */
  10482. void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor)
  10483. {
  10484. mRangeZoomFactorHorz = horizontalFactor;
  10485. mRangeZoomFactorVert = verticalFactor;
  10486. }
  10487. /*! \overload
  10488. Sets both the horizontal and vertical zoom \a factor.
  10489. */
  10490. void QCPAxisRect::setRangeZoomFactor(double factor)
  10491. {
  10492. mRangeZoomFactorHorz = factor;
  10493. mRangeZoomFactorVert = factor;
  10494. }
  10495. /*! \internal
  10496. Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a
  10497. pixmap.
  10498. If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an
  10499. according filling inside the axis rect with the provided \a painter.
  10500. Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version
  10501. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  10502. the axis rect with the provided \a painter. The scaled version is buffered in
  10503. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  10504. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  10505. dependant on the \ref setBackgroundScaledMode), or when a differend axis backgroud pixmap was
  10506. set.
  10507. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  10508. */
  10509. void QCPAxisRect::drawBackground(QCPPainter *painter)
  10510. {
  10511. // draw background fill:
  10512. if (mBackgroundBrush != Qt::NoBrush)
  10513. painter->fillRect(mRect, mBackgroundBrush);
  10514. // draw background pixmap (on top of fill, if brush specified):
  10515. if (!mBackgroundPixmap.isNull())
  10516. {
  10517. if (mBackgroundScaled)
  10518. {
  10519. // check whether mScaledBackground needs to be updated:
  10520. QSize scaledSize(mBackgroundPixmap.size());
  10521. scaledSize.scale(mRect.size(), mBackgroundScaledMode);
  10522. if (mScaledBackgroundPixmap.size() != scaledSize)
  10523. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
  10524. painter->drawPixmap(mRect.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect());
  10525. } else
  10526. {
  10527. painter->drawPixmap(mRect.topLeft(), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()));
  10528. }
  10529. }
  10530. }
  10531. /*! \internal
  10532. This function makes sure multiple axes on the side specified with \a type don't collide, but are
  10533. distributed according to their respective space requirement (QCPAxis::calculateMargin).
  10534. It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the
  10535. one with index zero.
  10536. This function is called by \ref calculateAutoMargin.
  10537. */
  10538. void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type)
  10539. {
  10540. const QList<QCPAxis*> axesList = mAxes.value(type);
  10541. if (axesList.isEmpty())
  10542. return;
  10543. 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
  10544. for (int i=1; i<axesList.size(); ++i)
  10545. {
  10546. int offset = axesList.at(i-1)->offset() + axesList.at(i-1)->calculateMargin();
  10547. 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)
  10548. {
  10549. if (!isFirstVisible)
  10550. offset += axesList.at(i)->tickLengthIn();
  10551. isFirstVisible = false;
  10552. }
  10553. axesList.at(i)->setOffset(offset);
  10554. }
  10555. }
  10556. /* inherits documentation from base class */
  10557. int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side)
  10558. {
  10559. if (!mAutoMargins.testFlag(side))
  10560. qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin";
  10561. updateAxesOffset(QCPAxis::marginSideToAxisType(side));
  10562. // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call
  10563. const QList<QCPAxis*> axesList = mAxes.value(QCPAxis::marginSideToAxisType(side));
  10564. if (axesList.size() > 0)
  10565. return axesList.last()->offset() + axesList.last()->calculateMargin();
  10566. else
  10567. return 0;
  10568. }
  10569. /*! \internal
  10570. Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
  10571. pressed, the range dragging interaction is initialized (the actual range manipulation happens in
  10572. the \ref mouseMoveEvent).
  10573. The mDragging flag is set to true and some anchor points are set that are needed to determine the
  10574. distance the mouse was dragged in the mouse move/release events later.
  10575. \see mouseMoveEvent, mouseReleaseEvent
  10576. */
  10577. void QCPAxisRect::mousePressEvent(QMouseEvent *event)
  10578. {
  10579. 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)
  10580. if (event->buttons() & Qt::LeftButton)
  10581. {
  10582. mDragging = true;
  10583. // initialize antialiasing backup in case we start dragging:
  10584. if (mParentPlot->noAntialiasingOnDrag())
  10585. {
  10586. mAADragBackup = mParentPlot->antialiasedElements();
  10587. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  10588. }
  10589. // Mouse range dragging interaction:
  10590. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  10591. {
  10592. if (mRangeDragHorzAxis)
  10593. mDragStartHorzRange = mRangeDragHorzAxis.data()->range();
  10594. if (mRangeDragVertAxis)
  10595. mDragStartVertRange = mRangeDragVertAxis.data()->range();
  10596. }
  10597. }
  10598. }
  10599. /*! \internal
  10600. Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a
  10601. preceding \ref mousePressEvent, the range is moved accordingly.
  10602. \see mousePressEvent, mouseReleaseEvent
  10603. */
  10604. void QCPAxisRect::mouseMoveEvent(QMouseEvent *event)
  10605. {
  10606. // Mouse range dragging interaction:
  10607. if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  10608. {
  10609. if (mRangeDrag.testFlag(Qt::Horizontal))
  10610. {
  10611. if (QCPAxis *rangeDragHorzAxis = mRangeDragHorzAxis.data())
  10612. {
  10613. if (rangeDragHorzAxis->mScaleType == QCPAxis::stLinear)
  10614. {
  10615. double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) - rangeDragHorzAxis->pixelToCoord(event->pos().x());
  10616. rangeDragHorzAxis->setRange(mDragStartHorzRange.lower+diff, mDragStartHorzRange.upper+diff);
  10617. } else if (rangeDragHorzAxis->mScaleType == QCPAxis::stLogarithmic)
  10618. {
  10619. double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) / rangeDragHorzAxis->pixelToCoord(event->pos().x());
  10620. rangeDragHorzAxis->setRange(mDragStartHorzRange.lower*diff, mDragStartHorzRange.upper*diff);
  10621. }
  10622. }
  10623. }
  10624. if (mRangeDrag.testFlag(Qt::Vertical))
  10625. {
  10626. if (QCPAxis *rangeDragVertAxis = mRangeDragVertAxis.data())
  10627. {
  10628. if (rangeDragVertAxis->mScaleType == QCPAxis::stLinear)
  10629. {
  10630. double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) - rangeDragVertAxis->pixelToCoord(event->pos().y());
  10631. rangeDragVertAxis->setRange(mDragStartVertRange.lower+diff, mDragStartVertRange.upper+diff);
  10632. } else if (rangeDragVertAxis->mScaleType == QCPAxis::stLogarithmic)
  10633. {
  10634. double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) / rangeDragVertAxis->pixelToCoord(event->pos().y());
  10635. rangeDragVertAxis->setRange(mDragStartVertRange.lower*diff, mDragStartVertRange.upper*diff);
  10636. }
  10637. }
  10638. }
  10639. if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot
  10640. {
  10641. if (mParentPlot->noAntialiasingOnDrag())
  10642. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  10643. mParentPlot->replot();
  10644. }
  10645. }
  10646. }
  10647. /* inherits documentation from base class */
  10648. void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event)
  10649. {
  10650. Q_UNUSED(event)
  10651. mDragging = false;
  10652. if (mParentPlot->noAntialiasingOnDrag())
  10653. {
  10654. mParentPlot->setAntialiasedElements(mAADragBackup);
  10655. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  10656. }
  10657. }
  10658. /*! \internal
  10659. Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
  10660. ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
  10661. the scaling operation is the current cursor position inside the axis rect. The scaling factor is
  10662. dependant on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
  10663. zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
  10664. Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse
  10665. wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be
  10666. multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as
  10667. exponent of the range zoom factor. This takes care of the wheel direction automatically, by
  10668. inverting the factor, when the wheel step is negative (f^-1 = 1/f).
  10669. */
  10670. void QCPAxisRect::wheelEvent(QWheelEvent *event)
  10671. {
  10672. // Mouse range zooming interaction:
  10673. if (mParentPlot->interactions().testFlag(QCP::iRangeZoom))
  10674. {
  10675. if (mRangeZoom != 0)
  10676. {
  10677. double factor;
  10678. double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually
  10679. if (mRangeZoom.testFlag(Qt::Horizontal))
  10680. {
  10681. factor = pow(mRangeZoomFactorHorz, wheelSteps);
  10682. if (mRangeZoomHorzAxis.data())
  10683. mRangeZoomHorzAxis.data()->scaleRange(factor, mRangeZoomHorzAxis.data()->pixelToCoord(event->pos().x()));
  10684. }
  10685. if (mRangeZoom.testFlag(Qt::Vertical))
  10686. {
  10687. factor = pow(mRangeZoomFactorVert, wheelSteps);
  10688. if (mRangeZoomVertAxis.data())
  10689. mRangeZoomVertAxis.data()->scaleRange(factor, mRangeZoomVertAxis.data()->pixelToCoord(event->pos().y()));
  10690. }
  10691. mParentPlot->replot();
  10692. }
  10693. }
  10694. }
  10695. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10696. //////////////////// QCPAbstractLegendItem
  10697. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10698. /*! \class QCPAbstractLegendItem
  10699. \brief The abstract base class for all entries in a QCPLegend.
  10700. It defines a very basic interface for entries in a QCPLegend. For representing plottables in the
  10701. legend, the subclass \ref QCPPlottableLegendItem is more suitable.
  10702. Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry
  10703. that's not even associated with a plottable).
  10704. You must implement the following pure virtual functions:
  10705. \li \ref draw (from QCPLayerable)
  10706. You inherit the following members you may use:
  10707. <table>
  10708. <tr>
  10709. <td>QCPLegend *\b mParentLegend</td>
  10710. <td>A pointer to the parent QCPLegend.</td>
  10711. </tr><tr>
  10712. <td>QFont \b mFont</td>
  10713. <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>
  10714. </tr>
  10715. </table>
  10716. */
  10717. /* start of documentation of signals */
  10718. /*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected)
  10719. This signal is emitted when the selection state of this legend item has changed, either by user
  10720. interaction or by a direct call to \ref setSelected.
  10721. */
  10722. /* end of documentation of signals */
  10723. /*!
  10724. Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not
  10725. cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately.
  10726. */
  10727. QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) :
  10728. QCPLayoutElement(parent->parentPlot()),
  10729. mParentLegend(parent),
  10730. mFont(parent->font()),
  10731. mTextColor(parent->textColor()),
  10732. mSelectedFont(parent->selectedFont()),
  10733. mSelectedTextColor(parent->selectedTextColor()),
  10734. mSelectable(true),
  10735. mSelected(false)
  10736. {
  10737. setLayer("legend");
  10738. setMargins(QMargins(8, 2, 8, 2));
  10739. }
  10740. /*!
  10741. Sets the default font of this specific legend item to \a font.
  10742. \see setTextColor, QCPLegend::setFont
  10743. */
  10744. void QCPAbstractLegendItem::setFont(const QFont &font)
  10745. {
  10746. mFont = font;
  10747. }
  10748. /*!
  10749. Sets the default text color of this specific legend item to \a color.
  10750. \see setFont, QCPLegend::setTextColor
  10751. */
  10752. void QCPAbstractLegendItem::setTextColor(const QColor &color)
  10753. {
  10754. mTextColor = color;
  10755. }
  10756. /*!
  10757. When this legend item is selected, \a font is used to draw generic text, instead of the normal
  10758. font set with \ref setFont.
  10759. \see setFont, QCPLegend::setSelectedFont
  10760. */
  10761. void QCPAbstractLegendItem::setSelectedFont(const QFont &font)
  10762. {
  10763. mSelectedFont = font;
  10764. }
  10765. /*!
  10766. When this legend item is selected, \a color is used to draw generic text, instead of the normal
  10767. color set with \ref setTextColor.
  10768. \see setTextColor, QCPLegend::setSelectedTextColor
  10769. */
  10770. void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color)
  10771. {
  10772. mSelectedTextColor = color;
  10773. }
  10774. /*!
  10775. Sets whether this specific legend item is selectable.
  10776. \see setSelectedParts, QCustomPlot::setInteractions
  10777. */
  10778. void QCPAbstractLegendItem::setSelectable(bool selectable)
  10779. {
  10780. if (mSelectable != selectable)
  10781. {
  10782. mSelectable = selectable;
  10783. emit selectableChanged(mSelectable);
  10784. }
  10785. }
  10786. /*!
  10787. Sets whether this specific legend item is selected.
  10788. It is possible to set the selection state of this item by calling this function directly, even if
  10789. setSelectable is set to false.
  10790. \see setSelectableParts, QCustomPlot::setInteractions
  10791. */
  10792. void QCPAbstractLegendItem::setSelected(bool selected)
  10793. {
  10794. if (mSelected != selected)
  10795. {
  10796. mSelected = selected;
  10797. emit selectionChanged(mSelected);
  10798. }
  10799. }
  10800. /* inherits documentation from base class */
  10801. double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  10802. {
  10803. Q_UNUSED(details)
  10804. if (!mParentPlot) return -1;
  10805. if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems)))
  10806. return -1;
  10807. if (mRect.contains(pos.toPoint()))
  10808. return mParentPlot->selectionTolerance()*0.99;
  10809. else
  10810. return -1;
  10811. }
  10812. /* inherits documentation from base class */
  10813. void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
  10814. {
  10815. applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems);
  10816. }
  10817. /* inherits documentation from base class */
  10818. QRect QCPAbstractLegendItem::clipRect() const
  10819. {
  10820. return mOuterRect;
  10821. }
  10822. /* inherits documentation from base class */
  10823. void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  10824. {
  10825. Q_UNUSED(event)
  10826. Q_UNUSED(details)
  10827. if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
  10828. {
  10829. bool selBefore = mSelected;
  10830. setSelected(additive ? !mSelected : true);
  10831. if (selectionStateChanged)
  10832. *selectionStateChanged = mSelected != selBefore;
  10833. }
  10834. }
  10835. /* inherits documentation from base class */
  10836. void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged)
  10837. {
  10838. if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
  10839. {
  10840. bool selBefore = mSelected;
  10841. setSelected(false);
  10842. if (selectionStateChanged)
  10843. *selectionStateChanged = mSelected != selBefore;
  10844. }
  10845. }
  10846. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10847. //////////////////// QCPPlottableLegendItem
  10848. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10849. /*! \class QCPPlottableLegendItem
  10850. \brief A legend item representing a plottable with an icon and the plottable name.
  10851. This is the standard legend item for plottables. It displays an icon of the plottable next to the
  10852. plottable name. The icon is drawn by the respective plottable itself (\ref
  10853. QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable.
  10854. For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the
  10855. middle.
  10856. Legend items of this type are always associated with one plottable (retrievable via the
  10857. plottable() function and settable with the constructor). You may change the font of the plottable
  10858. name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref
  10859. QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding.
  10860. The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend
  10861. creates/removes legend items of this type in the default implementation. However, these functions
  10862. may be reimplemented such that a different kind of legend item (e.g a direct subclass of
  10863. QCPAbstractLegendItem) is used for that plottable.
  10864. Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of
  10865. QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout
  10866. interface, QCPLegend has specialized functions for handling legend items conveniently, see the
  10867. documentation of \ref QCPLegend.
  10868. */
  10869. /*!
  10870. Creates a new legend item associated with \a plottable.
  10871. Once it's created, it can be added to the legend via \ref QCPLegend::addItem.
  10872. A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref
  10873. QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend.
  10874. */
  10875. QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) :
  10876. QCPAbstractLegendItem(parent),
  10877. mPlottable(plottable)
  10878. {
  10879. }
  10880. /*! \internal
  10881. Returns the pen that shall be used to draw the icon border, taking into account the selection
  10882. state of this item.
  10883. */
  10884. QPen QCPPlottableLegendItem::getIconBorderPen() const
  10885. {
  10886. return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen();
  10887. }
  10888. /*! \internal
  10889. Returns the text color that shall be used to draw text, taking into account the selection state
  10890. of this item.
  10891. */
  10892. QColor QCPPlottableLegendItem::getTextColor() const
  10893. {
  10894. return mSelected ? mSelectedTextColor : mTextColor;
  10895. }
  10896. /*! \internal
  10897. Returns the font that shall be used to draw text, taking into account the selection state of this
  10898. item.
  10899. */
  10900. QFont QCPPlottableLegendItem::getFont() const
  10901. {
  10902. return mSelected ? mSelectedFont : mFont;
  10903. }
  10904. /*! \internal
  10905. Draws the item with \a painter. The size and position of the drawn legend item is defined by the
  10906. parent layout (typically a \ref QCPLegend) and the \ref minimumSizeHint and \ref maximumSizeHint
  10907. of this legend item.
  10908. */
  10909. void QCPPlottableLegendItem::draw(QCPPainter *painter)
  10910. {
  10911. if (!mPlottable) return;
  10912. painter->setFont(getFont());
  10913. painter->setPen(QPen(getTextColor()));
  10914. QSizeF iconSize = mParentLegend->iconSize();
  10915. QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
  10916. QRectF iconRect(mRect.topLeft(), iconSize);
  10917. int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops
  10918. painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name());
  10919. // draw icon:
  10920. painter->save();
  10921. painter->setClipRect(iconRect, Qt::IntersectClip);
  10922. mPlottable->drawLegendIcon(painter, iconRect);
  10923. painter->restore();
  10924. // draw icon border:
  10925. if (getIconBorderPen().style() != Qt::NoPen)
  10926. {
  10927. painter->setPen(getIconBorderPen());
  10928. painter->setBrush(Qt::NoBrush);
  10929. painter->drawRect(iconRect);
  10930. }
  10931. }
  10932. /*! \internal
  10933. Calculates and returns the size of this item. This includes the icon, the text and the padding in
  10934. between.
  10935. */
  10936. QSize QCPPlottableLegendItem::minimumSizeHint() const
  10937. {
  10938. if (!mPlottable) return QSize();
  10939. QSize result(0, 0);
  10940. QRect textRect;
  10941. QFontMetrics fontMetrics(getFont());
  10942. QSize iconSize = mParentLegend->iconSize();
  10943. textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
  10944. result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width() + mMargins.left() + mMargins.right());
  10945. result.setHeight(qMax(textRect.height(), iconSize.height()) + mMargins.top() + mMargins.bottom());
  10946. return result;
  10947. }
  10948. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10949. //////////////////// QCPLegend
  10950. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10951. /*! \class QCPLegend
  10952. \brief Manages a legend inside a QCustomPlot.
  10953. A legend is a small box somewhere in the plot which lists plottables with their name and icon.
  10954. Normally, the legend is populated by calling \ref QCPAbstractPlottable::addToLegend. The
  10955. respective legend item can be removed with \ref QCPAbstractPlottable::removeFromLegend. However,
  10956. QCPLegend also offers an interface to add and manipulate legend items directly: \ref item, \ref
  10957. itemWithPlottable, \ref itemCount, \ref addItem, \ref removeItem, etc.
  10958. The QCPLegend derives from QCPLayoutGrid and as such can be placed in any position a
  10959. QCPLayoutElement may be positioned. The legend items are themselves QCPLayoutElements which are
  10960. placed in the grid layout of the legend. QCPLegend only adds an interface specialized for
  10961. handling child elements of type QCPAbstractLegendItem, as mentioned above. In principle, any
  10962. other layout elements may also be added to a legend via the normal \ref QCPLayoutGrid interface.
  10963. However, the QCPAbstractLegendItem-Interface will ignore those elements (e.g. \ref itemCount will
  10964. only return the number of items with QCPAbstractLegendItems type).
  10965. By default, every QCustomPlot has one legend (QCustomPlot::legend) which is placed in the inset
  10966. layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another
  10967. position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend
  10968. outside of the axis rect, place it anywhere else with the QCPLayout/QCPLayoutElement interface.
  10969. */
  10970. /* start of documentation of signals */
  10971. /*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection);
  10972. This signal is emitted when the selection state of this legend has changed.
  10973. \see setSelectedParts, setSelectableParts
  10974. */
  10975. /* end of documentation of signals */
  10976. /*!
  10977. Constructs a new QCPLegend instance with \a parentPlot as the containing plot and default values.
  10978. Note that by default, QCustomPlot already contains a legend ready to be used as
  10979. QCustomPlot::legend
  10980. */
  10981. QCPLegend::QCPLegend()
  10982. {
  10983. setRowSpacing(0);
  10984. setColumnSpacing(10);
  10985. setMargins(QMargins(2, 3, 2, 2));
  10986. setAntialiased(false);
  10987. setIconSize(32, 18);
  10988. setIconTextPadding(7);
  10989. setSelectableParts(spLegendBox | spItems);
  10990. setSelectedParts(spNone);
  10991. setBorderPen(QPen(Qt::black));
  10992. setSelectedBorderPen(QPen(Qt::blue, 2));
  10993. setIconBorderPen(Qt::NoPen);
  10994. setSelectedIconBorderPen(QPen(Qt::blue, 2));
  10995. setBrush(Qt::white);
  10996. setSelectedBrush(Qt::white);
  10997. setTextColor(Qt::black);
  10998. setSelectedTextColor(Qt::blue);
  10999. }
  11000. QCPLegend::~QCPLegend()
  11001. {
  11002. clearItems();
  11003. if (mParentPlot)
  11004. mParentPlot->legendRemoved(this);
  11005. }
  11006. /* no doc for getter, see setSelectedParts */
  11007. QCPLegend::SelectableParts QCPLegend::selectedParts() const
  11008. {
  11009. // check whether any legend elements selected, if yes, add spItems to return value
  11010. bool hasSelectedItems = false;
  11011. for (int i=0; i<itemCount(); ++i)
  11012. {
  11013. if (item(i) && item(i)->selected())
  11014. {
  11015. hasSelectedItems = true;
  11016. break;
  11017. }
  11018. }
  11019. if (hasSelectedItems)
  11020. return mSelectedParts | spItems;
  11021. else
  11022. return mSelectedParts & ~spItems;
  11023. }
  11024. /*!
  11025. Sets the pen, the border of the entire legend is drawn with.
  11026. */
  11027. void QCPLegend::setBorderPen(const QPen &pen)
  11028. {
  11029. mBorderPen = pen;
  11030. }
  11031. /*!
  11032. Sets the brush of the legend background.
  11033. */
  11034. void QCPLegend::setBrush(const QBrush &brush)
  11035. {
  11036. mBrush = brush;
  11037. }
  11038. /*!
  11039. Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will
  11040. use this font by default. However, a different font can be specified on a per-item-basis by
  11041. accessing the specific legend item.
  11042. This function will also set \a font on all already existing legend items.
  11043. \see QCPAbstractLegendItem::setFont
  11044. */
  11045. void QCPLegend::setFont(const QFont &font)
  11046. {
  11047. mFont = font;
  11048. for (int i=0; i<itemCount(); ++i)
  11049. {
  11050. if (item(i))
  11051. item(i)->setFont(mFont);
  11052. }
  11053. }
  11054. /*!
  11055. Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph)
  11056. will use this color by default. However, a different colors can be specified on a per-item-basis
  11057. by accessing the specific legend item.
  11058. This function will also set \a color on all already existing legend items.
  11059. \see QCPAbstractLegendItem::setTextColor
  11060. */
  11061. void QCPLegend::setTextColor(const QColor &color)
  11062. {
  11063. mTextColor = color;
  11064. for (int i=0; i<itemCount(); ++i)
  11065. {
  11066. if (item(i))
  11067. item(i)->setTextColor(color);
  11068. }
  11069. }
  11070. /*!
  11071. Sets the size of legend icons. Legend items that draw an icon (e.g. a visual
  11072. representation of the graph) will use this size by default.
  11073. */
  11074. void QCPLegend::setIconSize(const QSize &size)
  11075. {
  11076. mIconSize = size;
  11077. }
  11078. /*! \overload
  11079. */
  11080. void QCPLegend::setIconSize(int width, int height)
  11081. {
  11082. mIconSize.setWidth(width);
  11083. mIconSize.setHeight(height);
  11084. }
  11085. /*!
  11086. Sets the horizontal space in pixels between the legend icon and the text next to it.
  11087. Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the
  11088. name of the graph) will use this space by default.
  11089. */
  11090. void QCPLegend::setIconTextPadding(int padding)
  11091. {
  11092. mIconTextPadding = padding;
  11093. }
  11094. /*!
  11095. Sets the pen used to draw a border around each legend icon. Legend items that draw an
  11096. icon (e.g. a visual representation of the graph) will use this pen by default.
  11097. If no border is wanted, set this to \a Qt::NoPen.
  11098. */
  11099. void QCPLegend::setIconBorderPen(const QPen &pen)
  11100. {
  11101. mIconBorderPen = pen;
  11102. }
  11103. /*!
  11104. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  11105. (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.)
  11106. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  11107. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  11108. directly.
  11109. \see SelectablePart, setSelectedParts
  11110. */
  11111. void QCPLegend::setSelectableParts(const SelectableParts &selectable)
  11112. {
  11113. if (mSelectableParts != selectable)
  11114. {
  11115. mSelectableParts = selectable;
  11116. emit selectableChanged(mSelectableParts);
  11117. }
  11118. }
  11119. /*!
  11120. Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part
  11121. is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected
  11122. doesn't contain \ref spItems, those items become deselected.
  11123. The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions
  11124. contains iSelectLegend. You only need to call this function when you wish to change the selection
  11125. state manually.
  11126. This function can change the selection state of a part even when \ref setSelectableParts was set to a
  11127. value that actually excludes the part.
  11128. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  11129. Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set
  11130. before, because there's no way to specify which exact items to newly select. Do this by calling
  11131. \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select.
  11132. \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush,
  11133. setSelectedFont
  11134. */
  11135. void QCPLegend::setSelectedParts(const SelectableParts &selected)
  11136. {
  11137. SelectableParts newSelected = selected;
  11138. mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed
  11139. if (mSelectedParts != newSelected)
  11140. {
  11141. if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that)
  11142. {
  11143. qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function";
  11144. newSelected &= ~spItems;
  11145. }
  11146. if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection
  11147. {
  11148. for (int i=0; i<itemCount(); ++i)
  11149. {
  11150. if (item(i))
  11151. item(i)->setSelected(false);
  11152. }
  11153. }
  11154. mSelectedParts = newSelected;
  11155. emit selectionChanged(mSelectedParts);
  11156. }
  11157. }
  11158. /*!
  11159. When the legend box is selected, this pen is used to draw the border instead of the normal pen
  11160. set via \ref setBorderPen.
  11161. \see setSelectedParts, setSelectableParts, setSelectedBrush
  11162. */
  11163. void QCPLegend::setSelectedBorderPen(const QPen &pen)
  11164. {
  11165. mSelectedBorderPen = pen;
  11166. }
  11167. /*!
  11168. Sets the pen legend items will use to draw their icon borders, when they are selected.
  11169. \see setSelectedParts, setSelectableParts, setSelectedFont
  11170. */
  11171. void QCPLegend::setSelectedIconBorderPen(const QPen &pen)
  11172. {
  11173. mSelectedIconBorderPen = pen;
  11174. }
  11175. /*!
  11176. When the legend box is selected, this brush is used to draw the legend background instead of the normal brush
  11177. set via \ref setBrush.
  11178. \see setSelectedParts, setSelectableParts, setSelectedBorderPen
  11179. */
  11180. void QCPLegend::setSelectedBrush(const QBrush &brush)
  11181. {
  11182. mSelectedBrush = brush;
  11183. }
  11184. /*!
  11185. Sets the default font that is used by legend items when they are selected.
  11186. This function will also set \a font on all already existing legend items.
  11187. \see setFont, QCPAbstractLegendItem::setSelectedFont
  11188. */
  11189. void QCPLegend::setSelectedFont(const QFont &font)
  11190. {
  11191. mSelectedFont = font;
  11192. for (int i=0; i<itemCount(); ++i)
  11193. {
  11194. if (item(i))
  11195. item(i)->setSelectedFont(font);
  11196. }
  11197. }
  11198. /*!
  11199. Sets the default text color that is used by legend items when they are selected.
  11200. This function will also set \a color on all already existing legend items.
  11201. \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor
  11202. */
  11203. void QCPLegend::setSelectedTextColor(const QColor &color)
  11204. {
  11205. mSelectedTextColor = color;
  11206. for (int i=0; i<itemCount(); ++i)
  11207. {
  11208. if (item(i))
  11209. item(i)->setSelectedTextColor(color);
  11210. }
  11211. }
  11212. /*!
  11213. Returns the item with index \a i.
  11214. \see itemCount
  11215. */
  11216. QCPAbstractLegendItem *QCPLegend::item(int index) const
  11217. {
  11218. return qobject_cast<QCPAbstractLegendItem*>(elementAt(index));
  11219. }
  11220. /*!
  11221. Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
  11222. If such an item isn't in the legend, returns 0.
  11223. \see hasItemWithPlottable
  11224. */
  11225. QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const
  11226. {
  11227. for (int i=0; i<itemCount(); ++i)
  11228. {
  11229. if (QCPPlottableLegendItem *pli = qobject_cast<QCPPlottableLegendItem*>(item(i)))
  11230. {
  11231. if (pli->plottable() == plottable)
  11232. return pli;
  11233. }
  11234. }
  11235. return 0;
  11236. }
  11237. /*!
  11238. Returns the number of items currently in the legend.
  11239. \see item
  11240. */
  11241. int QCPLegend::itemCount() const
  11242. {
  11243. return elementCount();
  11244. }
  11245. /*!
  11246. Returns whether the legend contains \a itm.
  11247. */
  11248. bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const
  11249. {
  11250. for (int i=0; i<itemCount(); ++i)
  11251. {
  11252. if (item == this->item(i))
  11253. return true;
  11254. }
  11255. return false;
  11256. }
  11257. /*!
  11258. Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
  11259. If such an item isn't in the legend, returns false.
  11260. \see itemWithPlottable
  11261. */
  11262. bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const
  11263. {
  11264. return itemWithPlottable(plottable);
  11265. }
  11266. /*!
  11267. Adds \a item to the legend, if it's not present already.
  11268. Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added.
  11269. The legend takes ownership of the item.
  11270. */
  11271. bool QCPLegend::addItem(QCPAbstractLegendItem *item)
  11272. {
  11273. if (!hasItem(item))
  11274. {
  11275. return addElement(rowCount(), 0, item);
  11276. } else
  11277. return false;
  11278. }
  11279. /*!
  11280. Removes the item with index \a index from the legend.
  11281. Returns true, if successful.
  11282. \see itemCount, clearItems
  11283. */
  11284. bool QCPLegend::removeItem(int index)
  11285. {
  11286. if (QCPAbstractLegendItem *ali = item(index))
  11287. {
  11288. bool success = remove(ali);
  11289. simplify();
  11290. return success;
  11291. } else
  11292. return false;
  11293. }
  11294. /*! \overload
  11295. Removes \a item from the legend.
  11296. Returns true, if successful.
  11297. \see clearItems
  11298. */
  11299. bool QCPLegend::removeItem(QCPAbstractLegendItem *item)
  11300. {
  11301. bool success = remove(item);
  11302. simplify();
  11303. return success;
  11304. }
  11305. /*!
  11306. Removes all items from the legend.
  11307. */
  11308. void QCPLegend::clearItems()
  11309. {
  11310. for (int i=itemCount()-1; i>=0; --i)
  11311. removeItem(i);
  11312. }
  11313. /*!
  11314. Returns the legend items that are currently selected. If no items are selected,
  11315. the list is empty.
  11316. \see QCPAbstractLegendItem::setSelected, setSelectable
  11317. */
  11318. QList<QCPAbstractLegendItem *> QCPLegend::selectedItems() const
  11319. {
  11320. QList<QCPAbstractLegendItem*> result;
  11321. for (int i=0; i<itemCount(); ++i)
  11322. {
  11323. if (QCPAbstractLegendItem *ali = item(i))
  11324. {
  11325. if (ali->selected())
  11326. result.append(ali);
  11327. }
  11328. }
  11329. return result;
  11330. }
  11331. /*! \internal
  11332. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  11333. before drawing main legend elements.
  11334. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  11335. This function takes into account the local setting of the antialiasing flag as well as the
  11336. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  11337. QCustomPlot::setNotAntialiasedElements.
  11338. \see setAntialiased
  11339. */
  11340. void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const
  11341. {
  11342. applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend);
  11343. }
  11344. /*! \internal
  11345. Returns the pen used to paint the border of the legend, taking into account the selection state
  11346. of the legend box.
  11347. */
  11348. QPen QCPLegend::getBorderPen() const
  11349. {
  11350. return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen;
  11351. }
  11352. /*! \internal
  11353. Returns the brush used to paint the background of the legend, taking into account the selection
  11354. state of the legend box.
  11355. */
  11356. QBrush QCPLegend::getBrush() const
  11357. {
  11358. return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush;
  11359. }
  11360. /*! \internal
  11361. Draws the legend box with the provided \a painter. The individual legend items are layerables
  11362. themselves, thus are drawn independently.
  11363. */
  11364. void QCPLegend::draw(QCPPainter *painter)
  11365. {
  11366. // draw background rect:
  11367. painter->setBrush(getBrush());
  11368. painter->setPen(getBorderPen());
  11369. painter->drawRect(mOuterRect);
  11370. }
  11371. /* inherits documentation from base class */
  11372. double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  11373. {
  11374. if (!mParentPlot) return -1;
  11375. if (onlySelectable && !mSelectableParts.testFlag(spLegendBox))
  11376. return -1;
  11377. if (mOuterRect.contains(pos.toPoint()))
  11378. {
  11379. if (details) details->setValue(spLegendBox);
  11380. return mParentPlot->selectionTolerance()*0.99;
  11381. }
  11382. return -1;
  11383. }
  11384. /* inherits documentation from base class */
  11385. void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  11386. {
  11387. Q_UNUSED(event)
  11388. mSelectedParts = selectedParts(); // in case item selection has changed
  11389. if (details.value<SelectablePart>() == spLegendBox && mSelectableParts.testFlag(spLegendBox))
  11390. {
  11391. SelectableParts selBefore = mSelectedParts;
  11392. 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)
  11393. if (selectionStateChanged)
  11394. *selectionStateChanged = mSelectedParts != selBefore;
  11395. }
  11396. }
  11397. /* inherits documentation from base class */
  11398. void QCPLegend::deselectEvent(bool *selectionStateChanged)
  11399. {
  11400. mSelectedParts = selectedParts(); // in case item selection has changed
  11401. if (mSelectableParts.testFlag(spLegendBox))
  11402. {
  11403. SelectableParts selBefore = mSelectedParts;
  11404. setSelectedParts(selectedParts() & ~spLegendBox);
  11405. if (selectionStateChanged)
  11406. *selectionStateChanged = mSelectedParts != selBefore;
  11407. }
  11408. }
  11409. /* inherits documentation from base class */
  11410. QCP::Interaction QCPLegend::selectionCategory() const
  11411. {
  11412. return QCP::iSelectLegend;
  11413. }
  11414. /* inherits documentation from base class */
  11415. QCP::Interaction QCPAbstractLegendItem::selectionCategory() const
  11416. {
  11417. return QCP::iSelectLegend;
  11418. }
  11419. /* inherits documentation from base class */
  11420. void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot)
  11421. {
  11422. Q_UNUSED(parentPlot)
  11423. }
  11424. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11425. //////////////////// QCPPlotTitle
  11426. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11427. /*! \class QCPPlotTitle
  11428. \brief A layout element displaying a plot title text
  11429. The text may be specified with \ref setText, theformatting can be controlled with \ref setFont
  11430. and \ref setTextColor.
  11431. A plot title can be added as follows:
  11432. \code
  11433. customPlot->plotLayout()->insertRow(0); // inserts an empty row above the default axis rect
  11434. customPlot->plotLayout()->addElement(0, 0, new QCPPlotTitle(customPlot, "Your Plot Title"));
  11435. \endcode
  11436. Since a plot title is a common requirement, QCustomPlot offers specialized selection signals for
  11437. easy interaction with QCPPlotTitle. If a layout element of type QCPPlotTitle is clicked, the
  11438. signal \ref QCustomPlot::titleClick is emitted. A double click emits the \ref
  11439. QCustomPlot::titleDoubleClick signal.
  11440. */
  11441. /* start documentation of signals */
  11442. /*! \fn void QCPPlotTitle::selectionChanged(bool selected)
  11443. This signal is emitted when the selection state has changed to \a selected, either by user
  11444. interaction or by a direct call to \ref setSelected.
  11445. \see setSelected, setSelectable
  11446. */
  11447. /* end documentation of signals */
  11448. /*!
  11449. Creates a new QCPPlotTitle instance and sets default values. The initial text is empty (\ref setText).
  11450. To set the title text in the constructor, rather use \ref QCPPlotTitle(QCustomPlot *parentPlot, const QString &text).
  11451. */
  11452. QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot) :
  11453. QCPLayoutElement(parentPlot),
  11454. mFont(QFont("sans serif", 13*1.5, QFont::Bold)),
  11455. mTextColor(Qt::black),
  11456. mSelectedFont(QFont("sans serif", 13*1.6, QFont::Bold)),
  11457. mSelectedTextColor(Qt::blue),
  11458. mSelectable(false),
  11459. mSelected(false)
  11460. {
  11461. if (parentPlot)
  11462. {
  11463. setLayer(parentPlot->currentLayer());
  11464. mFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold);
  11465. mSelectedFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold);
  11466. }
  11467. setMargins(QMargins(5, 5, 5, 0));
  11468. }
  11469. /*! \overload
  11470. Creates a new QCPPlotTitle instance and sets default values. The initial text is set to \a text.
  11471. */
  11472. QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot, const QString &text) :
  11473. QCPLayoutElement(parentPlot),
  11474. mText(text),
  11475. mFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold)),
  11476. mTextColor(Qt::black),
  11477. mSelectedFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold)),
  11478. mSelectedTextColor(Qt::blue),
  11479. mSelectable(false),
  11480. mSelected(false)
  11481. {
  11482. setLayer("axes");
  11483. setMargins(QMargins(5, 5, 5, 0));
  11484. }
  11485. /*!
  11486. Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n".
  11487. \see setFont, setTextColor
  11488. */
  11489. void QCPPlotTitle::setText(const QString &text)
  11490. {
  11491. mText = text;
  11492. }
  11493. /*!
  11494. Sets the \a font of the title text.
  11495. \see setTextColor, setSelectedFont
  11496. */
  11497. void QCPPlotTitle::setFont(const QFont &font)
  11498. {
  11499. mFont = font;
  11500. }
  11501. /*!
  11502. Sets the \a color of the title text.
  11503. \see setFont, setSelectedTextColor
  11504. */
  11505. void QCPPlotTitle::setTextColor(const QColor &color)
  11506. {
  11507. mTextColor = color;
  11508. }
  11509. /*!
  11510. Sets the \a font of the title text that will be used if the plot title is selected (\ref setSelected).
  11511. \see setFont
  11512. */
  11513. void QCPPlotTitle::setSelectedFont(const QFont &font)
  11514. {
  11515. mSelectedFont = font;
  11516. }
  11517. /*!
  11518. Sets the \a color of the title text that will be used if the plot title is selected (\ref setSelected).
  11519. \see setTextColor
  11520. */
  11521. void QCPPlotTitle::setSelectedTextColor(const QColor &color)
  11522. {
  11523. mSelectedTextColor = color;
  11524. }
  11525. /*!
  11526. Sets whether the user may select this plot title to \a selectable.
  11527. Note that even when \a selectable is set to <tt>false</tt>, the selection state may be changed
  11528. programmatically via \ref setSelected.
  11529. */
  11530. void QCPPlotTitle::setSelectable(bool selectable)
  11531. {
  11532. if (mSelectable != selectable)
  11533. {
  11534. mSelectable = selectable;
  11535. emit selectableChanged(mSelectable);
  11536. }
  11537. }
  11538. /*!
  11539. Sets the selection state of this plot title to \a selected. If the selection has changed, \ref
  11540. selectionChanged is emitted.
  11541. Note that this function can change the selection state independently of the current \ref
  11542. setSelectable state.
  11543. */
  11544. void QCPPlotTitle::setSelected(bool selected)
  11545. {
  11546. if (mSelected != selected)
  11547. {
  11548. mSelected = selected;
  11549. emit selectionChanged(mSelected);
  11550. }
  11551. }
  11552. /* inherits documentation from base class */
  11553. void QCPPlotTitle::applyDefaultAntialiasingHint(QCPPainter *painter) const
  11554. {
  11555. applyAntialiasingHint(painter, mAntialiased, QCP::aeNone);
  11556. }
  11557. /* inherits documentation from base class */
  11558. void QCPPlotTitle::draw(QCPPainter *painter)
  11559. {
  11560. painter->setFont(mainFont());
  11561. painter->setPen(QPen(mainTextColor()));
  11562. painter->drawText(mRect, Qt::AlignCenter, mText, &mTextBoundingRect);
  11563. }
  11564. /* inherits documentation from base class */
  11565. QSize QCPPlotTitle::minimumSizeHint() const
  11566. {
  11567. QFontMetrics metrics(mFont);
  11568. QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size();
  11569. result.rwidth() += mMargins.left() + mMargins.right();
  11570. result.rheight() += mMargins.top() + mMargins.bottom();
  11571. return result;
  11572. }
  11573. /* inherits documentation from base class */
  11574. QSize QCPPlotTitle::maximumSizeHint() const
  11575. {
  11576. QFontMetrics metrics(mFont);
  11577. QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size();
  11578. result.rheight() += mMargins.top() + mMargins.bottom();
  11579. result.setWidth(QWIDGETSIZE_MAX);
  11580. return result;
  11581. }
  11582. /* inherits documentation from base class */
  11583. void QCPPlotTitle::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  11584. {
  11585. Q_UNUSED(event)
  11586. Q_UNUSED(details)
  11587. if (mSelectable)
  11588. {
  11589. bool selBefore = mSelected;
  11590. setSelected(additive ? !mSelected : true);
  11591. if (selectionStateChanged)
  11592. *selectionStateChanged = mSelected != selBefore;
  11593. }
  11594. }
  11595. /* inherits documentation from base class */
  11596. void QCPPlotTitle::deselectEvent(bool *selectionStateChanged)
  11597. {
  11598. if (mSelectable)
  11599. {
  11600. bool selBefore = mSelected;
  11601. setSelected(false);
  11602. if (selectionStateChanged)
  11603. *selectionStateChanged = mSelected != selBefore;
  11604. }
  11605. }
  11606. /* inherits documentation from base class */
  11607. double QCPPlotTitle::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  11608. {
  11609. Q_UNUSED(details)
  11610. if (onlySelectable && !mSelectable)
  11611. return -1;
  11612. if (mTextBoundingRect.contains(pos.toPoint()))
  11613. return mParentPlot->selectionTolerance()*0.99;
  11614. else
  11615. return -1;
  11616. }
  11617. /*! \internal
  11618. Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to
  11619. <tt>true</tt>, else mFont is returned.
  11620. */
  11621. QFont QCPPlotTitle::mainFont() const
  11622. {
  11623. return mSelected ? mSelectedFont : mFont;
  11624. }
  11625. /*! \internal
  11626. Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to
  11627. <tt>true</tt>, else mTextColor is returned.
  11628. */
  11629. QColor QCPPlotTitle::mainTextColor() const
  11630. {
  11631. return mSelected ? mSelectedTextColor : mTextColor;
  11632. }
  11633. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11634. //////////////////// QCPColorScale
  11635. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11636. /*! \class QCPColorScale
  11637. \brief A color scale for use with color coding data such as QCPColorMap
  11638. This layout element can be placed on the plot to correlate a color gradient with data values. It
  11639. is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps".
  11640. \image html QCPColorScale.png
  11641. The color scale can be either horizontal or vertical, as shown in the image above. The
  11642. orientation and the side where the numbers appear is controlled with \ref setType.
  11643. Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are
  11644. connected, they share their gradient, data range and data scale type (\ref setGradient, \ref
  11645. setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color
  11646. scale, to make them all synchronize these properties.
  11647. To have finer control over the number display and axis behaviour, you can directly access the
  11648. \ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if
  11649. you want to change the number of automatically generated ticks, call
  11650. \code
  11651. colorScale->axis()->setAutoTickCount(3);
  11652. \endcode
  11653. Placing a color scale next to the main axis rect works like with any other layout element:
  11654. \code
  11655. QCPColorScale *colorScale = new QCPColorScale(customPlot);
  11656. customPlot->plotLayout()->addElement(0, 1, colorScale);
  11657. colorScale->setLabel("Some Label Text");
  11658. \endcode
  11659. In this case we have placed it to the right of the default axis rect, so it wasn't necessary to
  11660. call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color
  11661. scale can be set with \ref setLabel.
  11662. For optimum appearance (like in the image above), it may be desirable to line up the axis rect and
  11663. the borders of the color scale. Use a \ref QCPMarginGroup to achieve this:
  11664. \code
  11665. QCPMarginGroup *group = new QCPMarginGroup(customPlot);
  11666. colorScale->setMarginGroup(QCP::msTop|QCP::msBottom, group);
  11667. customPlot->axisRect()->setMarginGroup(QCP::msTop|QCP::msBottom, group);
  11668. \endcode
  11669. Color scales are initialized with a non-zero minimum top and bottom margin (\ref
  11670. setMinimumMargins), because vertical color scales are most common and the minimum top/bottom
  11671. margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a
  11672. horizontal color scale by setting \ref setType to \ref QCPAxis::atBottom or \ref QCPAxis::atTop, you
  11673. might want to also change the minimum margins accordingly, e.g. \ref
  11674. setMinimumMargins(QMargins(6, 0, 6, 0)).
  11675. */
  11676. /* start documentation of inline functions */
  11677. /*! \fn QCPAxis *QCPColorScale::axis() const
  11678. Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the
  11679. appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its
  11680. interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref
  11681. setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref
  11682. QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on
  11683. the QCPColorScale or on its QCPAxis.
  11684. If the type of the color scale is changed with \ref setType, the axis returned by this method
  11685. will change, too, to either the left, right, bottom or top axis, depending on which type was set.
  11686. */
  11687. /* end documentation of signals */
  11688. /* start documentation of signals */
  11689. /*! \fn void QCPColorScale::dataRangeChanged(QCPRange newRange);
  11690. This signal is emitted when the data range changes.
  11691. \see setDataRange
  11692. */
  11693. /*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
  11694. This signal is emitted when the data scale type changes.
  11695. \see setDataScaleType
  11696. */
  11697. /*! \fn void QCPColorScale::gradientChanged(QCPColorGradient newGradient);
  11698. This signal is emitted when the gradient changes.
  11699. \see setGradient
  11700. */
  11701. /* end documentation of signals */
  11702. /*!
  11703. Constructs a new QCPColorScale.
  11704. */
  11705. QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) :
  11706. QCPLayoutElement(parentPlot),
  11707. mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight
  11708. mDataScaleType(QCPAxis::stLinear),
  11709. mBarWidth(20),
  11710. mAxisRect(new QCPColorScaleAxisRectPrivate(this))
  11711. {
  11712. 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)
  11713. setType(QCPAxis::atRight);
  11714. setDataRange(QCPRange(0, 6));
  11715. }
  11716. QCPColorScale::~QCPColorScale()
  11717. {
  11718. delete mAxisRect;
  11719. }
  11720. /* undocumented getter */
  11721. QString QCPColorScale::label() const
  11722. {
  11723. if (!mColorAxis)
  11724. {
  11725. qDebug() << Q_FUNC_INFO << "internal color axis undefined";
  11726. return QString();
  11727. }
  11728. return mColorAxis.data()->label();
  11729. }
  11730. /* undocumented getter */
  11731. bool QCPColorScale::rangeDrag() const
  11732. {
  11733. if (!mAxisRect)
  11734. {
  11735. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  11736. return false;
  11737. }
  11738. return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) &&
  11739. mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) &&
  11740. mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
  11741. }
  11742. /* undocumented getter */
  11743. bool QCPColorScale::rangeZoom() const
  11744. {
  11745. if (!mAxisRect)
  11746. {
  11747. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  11748. return false;
  11749. }
  11750. return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) &&
  11751. mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) &&
  11752. mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
  11753. }
  11754. /*!
  11755. Sets at which side of the color scale the axis is placed, and thus also its orientation.
  11756. Note that after setting \a type to a different value, the axis returned by \ref axis() will
  11757. be a different one. The new axis will adopt the following properties from the previous axis: The
  11758. range, scale type, log base and label.
  11759. */
  11760. void QCPColorScale::setType(QCPAxis::AxisType type)
  11761. {
  11762. if (!mAxisRect)
  11763. {
  11764. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  11765. return;
  11766. }
  11767. if (mType != type)
  11768. {
  11769. mType = type;
  11770. QCPRange rangeTransfer(0, 6);
  11771. double logBaseTransfer = 10;
  11772. QString labelTransfer;
  11773. // revert some settings on old axis:
  11774. if (mColorAxis)
  11775. {
  11776. rangeTransfer = mColorAxis.data()->range();
  11777. labelTransfer = mColorAxis.data()->label();
  11778. logBaseTransfer = mColorAxis.data()->scaleLogBase();
  11779. mColorAxis.data()->setLabel("");
  11780. disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  11781. disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  11782. }
  11783. foreach (QCPAxis::AxisType atype, QList<QCPAxis::AxisType>() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop)
  11784. {
  11785. mAxisRect.data()->axis(atype)->setTicks(atype == mType);
  11786. mAxisRect.data()->axis(atype)->setTickLabels(atype== mType);
  11787. }
  11788. // set new mColorAxis pointer:
  11789. mColorAxis = mAxisRect.data()->axis(mType);
  11790. // transfer settings to new axis:
  11791. mColorAxis.data()->setRange(rangeTransfer); // transfer range of old axis to new one (necessary if axis changes from vertical to horizontal or vice versa)
  11792. mColorAxis.data()->setLabel(labelTransfer);
  11793. 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
  11794. connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  11795. connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  11796. mAxisRect.data()->setRangeDragAxes(QCPAxis::orientation(mType) == Qt::Horizontal ? mColorAxis.data() : 0,
  11797. QCPAxis::orientation(mType) == Qt::Vertical ? mColorAxis.data() : 0);
  11798. }
  11799. }
  11800. /*!
  11801. Sets the range spanned by the color gradient and that is shown by the axis in the color scale.
  11802. It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is
  11803. also equivalent to directly accessing the \ref axis and setting its range with \ref
  11804. QCPAxis::setRange.
  11805. \see setDataScaleType, setGradient, rescaleDataRange
  11806. */
  11807. void QCPColorScale::setDataRange(const QCPRange &dataRange)
  11808. {
  11809. if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
  11810. {
  11811. mDataRange = dataRange;
  11812. if (mColorAxis)
  11813. mColorAxis.data()->setRange(mDataRange);
  11814. emit dataRangeChanged(mDataRange);
  11815. }
  11816. }
  11817. /*!
  11818. Sets the scale type of the color scale, i.e. whether values are linearly associated with colors
  11819. or logarithmically.
  11820. It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is
  11821. also equivalent to directly accessing the \ref axis and setting its scale type with \ref
  11822. QCPAxis::setScaleType.
  11823. \see setDataRange, setGradient
  11824. */
  11825. void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType)
  11826. {
  11827. if (mDataScaleType != scaleType)
  11828. {
  11829. mDataScaleType = scaleType;
  11830. if (mColorAxis)
  11831. mColorAxis.data()->setScaleType(mDataScaleType);
  11832. if (mDataScaleType == QCPAxis::stLogarithmic)
  11833. setDataRange(mDataRange.sanitizedForLogScale());
  11834. emit dataScaleTypeChanged(mDataScaleType);
  11835. }
  11836. }
  11837. /*!
  11838. Sets the color gradient that will be used to represent data values.
  11839. It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps.
  11840. \see setDataRange, setDataScaleType
  11841. */
  11842. void QCPColorScale::setGradient(const QCPColorGradient &gradient)
  11843. {
  11844. if (mGradient != gradient)
  11845. {
  11846. mGradient = gradient;
  11847. if (mAxisRect)
  11848. mAxisRect.data()->mGradientImageInvalidated = true;
  11849. emit gradientChanged(mGradient);
  11850. }
  11851. }
  11852. /*!
  11853. Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on
  11854. the internal \ref axis.
  11855. */
  11856. void QCPColorScale::setLabel(const QString &str)
  11857. {
  11858. if (!mColorAxis)
  11859. {
  11860. qDebug() << Q_FUNC_INFO << "internal color axis undefined";
  11861. return;
  11862. }
  11863. mColorAxis.data()->setLabel(str);
  11864. }
  11865. /*!
  11866. Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed
  11867. will have.
  11868. */
  11869. void QCPColorScale::setBarWidth(int width)
  11870. {
  11871. mBarWidth = width;
  11872. }
  11873. /*!
  11874. Sets whether the user can drag the data range (\ref setDataRange).
  11875. Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref
  11876. QCustomPlot::setInteractions) to allow range dragging.
  11877. */
  11878. void QCPColorScale::setRangeDrag(bool enabled)
  11879. {
  11880. if (!mAxisRect)
  11881. {
  11882. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  11883. return;
  11884. }
  11885. if (enabled)
  11886. mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType));
  11887. else
  11888. mAxisRect.data()->setRangeDrag(0);
  11889. }
  11890. /*!
  11891. Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel.
  11892. Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref
  11893. QCustomPlot::setInteractions) to allow range dragging.
  11894. */
  11895. void QCPColorScale::setRangeZoom(bool enabled)
  11896. {
  11897. if (!mAxisRect)
  11898. {
  11899. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  11900. return;
  11901. }
  11902. if (enabled)
  11903. mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType));
  11904. else
  11905. mAxisRect.data()->setRangeZoom(0);
  11906. }
  11907. /*!
  11908. Returns a list of all the color maps associated with this color scale.
  11909. */
  11910. QList<QCPColorMap*> QCPColorScale::colorMaps() const
  11911. {
  11912. QList<QCPColorMap*> result;
  11913. for (int i=0; i<mParentPlot->plottableCount(); ++i)
  11914. {
  11915. if (QCPColorMap *cm = qobject_cast<QCPColorMap*>(mParentPlot->plottable(i)))
  11916. if (cm->colorScale() == this)
  11917. result.append(cm);
  11918. }
  11919. return result;
  11920. }
  11921. /*!
  11922. Changes the data range such that all color maps associated with this color scale are fully mapped
  11923. to the gradient in the data dimension.
  11924. \see setDataRange
  11925. */
  11926. void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps)
  11927. {
  11928. QList<QCPColorMap*> maps = colorMaps();
  11929. QCPRange newRange;
  11930. bool haveRange = false;
  11931. int sign = 0; // TODO: should change this to QCPAbstractPlottable::SignDomain later (currently is protected, maybe move to QCP namespace)
  11932. if (mDataScaleType == QCPAxis::stLogarithmic)
  11933. sign = (mDataRange.upper < 0 ? -1 : 1);
  11934. for (int i=0; i<maps.size(); ++i)
  11935. {
  11936. if (!maps.at(i)->realVisibility() && onlyVisibleMaps)
  11937. continue;
  11938. QCPRange mapRange;
  11939. if (maps.at(i)->colorScale() == this)
  11940. {
  11941. bool currentFoundRange = true;
  11942. mapRange = maps.at(i)->data()->dataBounds();
  11943. if (sign == 1)
  11944. {
  11945. if (mapRange.lower <= 0 && mapRange.upper > 0)
  11946. mapRange.lower = mapRange.upper*1e-3;
  11947. else if (mapRange.lower <= 0 && mapRange.upper <= 0)
  11948. currentFoundRange = false;
  11949. } else if (sign == -1)
  11950. {
  11951. if (mapRange.upper >= 0 && mapRange.lower < 0)
  11952. mapRange.upper = mapRange.lower*1e-3;
  11953. else if (mapRange.upper >= 0 && mapRange.lower >= 0)
  11954. currentFoundRange = false;
  11955. }
  11956. if (currentFoundRange)
  11957. {
  11958. if (!haveRange)
  11959. newRange = mapRange;
  11960. else
  11961. newRange.expand(mapRange);
  11962. haveRange = true;
  11963. }
  11964. }
  11965. }
  11966. if (haveRange)
  11967. {
  11968. 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
  11969. {
  11970. 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
  11971. if (mDataScaleType == QCPAxis::stLinear)
  11972. {
  11973. newRange.lower = center-mDataRange.size()/2.0;
  11974. newRange.upper = center+mDataRange.size()/2.0;
  11975. } else // mScaleType == stLogarithmic
  11976. {
  11977. newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower);
  11978. newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower);
  11979. }
  11980. }
  11981. setDataRange(newRange);
  11982. }
  11983. }
  11984. /* inherits documentation from base class */
  11985. void QCPColorScale::update(UpdatePhase phase)
  11986. {
  11987. QCPLayoutElement::update(phase);
  11988. if (!mAxisRect)
  11989. {
  11990. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  11991. return;
  11992. }
  11993. mAxisRect.data()->update(phase);
  11994. switch (phase)
  11995. {
  11996. case upMargins:
  11997. {
  11998. if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop)
  11999. {
  12000. setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom());
  12001. setMinimumSize(0, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom());
  12002. } else
  12003. {
  12004. setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), QWIDGETSIZE_MAX);
  12005. setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), 0);
  12006. }
  12007. break;
  12008. }
  12009. case upLayout:
  12010. {
  12011. mAxisRect.data()->setOuterRect(rect());
  12012. break;
  12013. }
  12014. default: break;
  12015. }
  12016. }
  12017. /* inherits documentation from base class */
  12018. void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const
  12019. {
  12020. painter->setAntialiasing(false);
  12021. }
  12022. /* inherits documentation from base class */
  12023. void QCPColorScale::mousePressEvent(QMouseEvent *event)
  12024. {
  12025. if (!mAxisRect)
  12026. {
  12027. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  12028. return;
  12029. }
  12030. mAxisRect.data()->mousePressEvent(event);
  12031. }
  12032. /* inherits documentation from base class */
  12033. void QCPColorScale::mouseMoveEvent(QMouseEvent *event)
  12034. {
  12035. if (!mAxisRect)
  12036. {
  12037. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  12038. return;
  12039. }
  12040. mAxisRect.data()->mouseMoveEvent(event);
  12041. }
  12042. /* inherits documentation from base class */
  12043. void QCPColorScale::mouseReleaseEvent(QMouseEvent *event)
  12044. {
  12045. if (!mAxisRect)
  12046. {
  12047. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  12048. return;
  12049. }
  12050. mAxisRect.data()->mouseReleaseEvent(event);
  12051. }
  12052. /* inherits documentation from base class */
  12053. void QCPColorScale::wheelEvent(QWheelEvent *event)
  12054. {
  12055. if (!mAxisRect)
  12056. {
  12057. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  12058. return;
  12059. }
  12060. mAxisRect.data()->wheelEvent(event);
  12061. }
  12062. ////////////////////////////////////////////////////////////////////////////////////////////////////
  12063. //////////////////// QCPColorScaleAxisRectPrivate
  12064. ////////////////////////////////////////////////////////////////////////////////////////////////////
  12065. /*! \class QCPColorScaleAxisRectPrivate
  12066. \internal
  12067. \brief An axis rect subclass for use in a QCPColorScale
  12068. This is a private class and not part of the public QCustomPlot interface.
  12069. It provides the axis rect functionality for the QCPColorScale class.
  12070. */
  12071. /*!
  12072. Creates a new instance, as a child of \a parentColorScale.
  12073. */
  12074. QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) :
  12075. QCPAxisRect(parentColorScale->parentPlot(), true),
  12076. mParentColorScale(parentColorScale),
  12077. mGradientImageInvalidated(true)
  12078. {
  12079. setParentLayerable(parentColorScale);
  12080. setMinimumMargins(QMargins(0, 0, 0, 0));
  12081. foreach (QCPAxis::AxisType type, QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight)
  12082. {
  12083. axis(type)->setVisible(true);
  12084. axis(type)->grid()->setVisible(false);
  12085. axis(type)->setPadding(0);
  12086. connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts)));
  12087. connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts)));
  12088. }
  12089. connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange)));
  12090. connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange)));
  12091. connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange)));
  12092. connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange)));
  12093. connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType)));
  12094. connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType)));
  12095. connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType)));
  12096. connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType)));
  12097. // make layer transfers of color scale transfer to axis rect and axes
  12098. // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect:
  12099. connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*)));
  12100. foreach (QCPAxis::AxisType type, QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight)
  12101. connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*)));
  12102. }
  12103. /*! \internal
  12104. Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws
  12105. it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation.
  12106. */
  12107. void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter)
  12108. {
  12109. if (mGradientImageInvalidated)
  12110. updateGradientImage();
  12111. bool mirrorHorz = false;
  12112. bool mirrorVert = false;
  12113. if (mParentColorScale->mColorAxis)
  12114. {
  12115. mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop);
  12116. mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight);
  12117. }
  12118. painter->drawImage(rect(), mGradientImage.mirrored(mirrorHorz, mirrorVert));
  12119. QCPAxisRect::draw(painter);
  12120. }
  12121. /*! \internal
  12122. Uses the current gradient of the parent \ref QCPColorScale (specified in the constructor) to
  12123. generate a gradient image. This gradient image will be used in the \ref draw method.
  12124. */
  12125. void QCPColorScaleAxisRectPrivate::updateGradientImage()
  12126. {
  12127. if (rect().isEmpty())
  12128. return;
  12129. int n = mParentColorScale->mGradient.levelCount();
  12130. int w, h;
  12131. QVector<double> data(n);
  12132. for (int i=0; i<n; ++i)
  12133. data[i] = i;
  12134. if (mParentColorScale->mType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop)
  12135. {
  12136. w = n;
  12137. h = rect().height();
  12138. mGradientImage = QImage(w, h, QImage::Format_RGB32);
  12139. QVector<QRgb*> pixels;
  12140. for (int y=0; y<h; ++y)
  12141. pixels.append(reinterpret_cast<QRgb*>(mGradientImage.scanLine(y)));
  12142. mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n);
  12143. for (int y=1; y<h; ++y)
  12144. memcpy(pixels.at(y), pixels.first(), n*sizeof(QRgb));
  12145. } else
  12146. {
  12147. w = rect().width();
  12148. h = n;
  12149. mGradientImage = QImage(w, h, QImage::Format_RGB32);
  12150. for (int y=0; y<h; ++y)
  12151. {
  12152. QRgb *pixels = reinterpret_cast<QRgb*>(mGradientImage.scanLine(y));
  12153. const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1));
  12154. for (int x=0; x<w; ++x)
  12155. pixels[x] = lineColor;
  12156. }
  12157. }
  12158. mGradientImageInvalidated = false;
  12159. }
  12160. /*! \internal
  12161. This slot is connected to the selectionChanged signals of the four axes in the constructor. It
  12162. synchronizes the selection state of the axes.
  12163. */
  12164. void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts selectedParts)
  12165. {
  12166. // axis bases of four axes shall always (de-)selected synchronously:
  12167. foreach (QCPAxis::AxisType type, QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight)
  12168. {
  12169. if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
  12170. if (senderAxis->axisType() == type)
  12171. continue;
  12172. if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
  12173. {
  12174. if (selectedParts.testFlag(QCPAxis::spAxis))
  12175. axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis);
  12176. else
  12177. axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis);
  12178. }
  12179. }
  12180. }
  12181. /*! \internal
  12182. This slot is connected to the selectableChanged signals of the four axes in the constructor. It
  12183. synchronizes the selectability of the axes.
  12184. */
  12185. void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts)
  12186. {
  12187. // synchronize axis base selectability:
  12188. foreach (QCPAxis::AxisType type, QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight)
  12189. {
  12190. if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
  12191. if (senderAxis->axisType() == type)
  12192. continue;
  12193. if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
  12194. {
  12195. if (selectableParts.testFlag(QCPAxis::spAxis))
  12196. axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis);
  12197. else
  12198. axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis);
  12199. }
  12200. }
  12201. }
  12202. ////////////////////////////////////////////////////////////////////////////////////////////////////
  12203. //////////////////// QCPData
  12204. ////////////////////////////////////////////////////////////////////////////////////////////////////
  12205. /*! \class QCPData
  12206. \brief Holds the data of one single data point for QCPGraph.
  12207. The container for storing multiple data points is \ref QCPDataMap.
  12208. The stored data is:
  12209. \li \a key: coordinate on the key axis of this data point
  12210. \li \a value: coordinate on the value axis of this data point
  12211. \li \a keyErrorMinus: negative error in the key dimension (for error bars)
  12212. \li \a keyErrorPlus: positive error in the key dimension (for error bars)
  12213. \li \a valueErrorMinus: negative error in the value dimension (for error bars)
  12214. \li \a valueErrorPlus: positive error in the value dimension (for error bars)
  12215. \see QCPDataMap
  12216. */
  12217. /*!
  12218. Constructs a data point with key, value and all errors set to zero.
  12219. */
  12220. QCPData::QCPData() :
  12221. key(0),
  12222. value(0),
  12223. keyErrorPlus(0),
  12224. keyErrorMinus(0),
  12225. valueErrorPlus(0),
  12226. valueErrorMinus(0)
  12227. {
  12228. }
  12229. /*!
  12230. Constructs a data point with the specified \a key and \a value. All errors are set to zero.
  12231. */
  12232. QCPData::QCPData(double key, double value) :
  12233. key(key),
  12234. value(value),
  12235. keyErrorPlus(0),
  12236. keyErrorMinus(0),
  12237. valueErrorPlus(0),
  12238. valueErrorMinus(0)
  12239. {
  12240. }
  12241. ////////////////////////////////////////////////////////////////////////////////////////////////////
  12242. //////////////////// QCPGraph
  12243. ////////////////////////////////////////////////////////////////////////////////////////////////////
  12244. /*! \class QCPGraph
  12245. \brief A plottable representing a graph in a plot.
  12246. \image html QCPGraph.png
  12247. Usually QCustomPlot creates graphs internally via QCustomPlot::addGraph and the resulting
  12248. instance is accessed via QCustomPlot::graph.
  12249. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
  12250. also access and modify the graph's data via the \ref data method, which returns a pointer to the
  12251. internal \ref QCPDataMap.
  12252. Graphs are used to display single-valued data. Single-valued means that there should only be one
  12253. data point per unique key coordinate. In other words, the graph can't have \a loops. If you do
  12254. want to plot non-single-valued curves, rather use the QCPCurve plottable.
  12255. \section appearance Changing the appearance
  12256. The appearance of the graph is mainly determined by the line style, scatter style, brush and pen
  12257. of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen).
  12258. \subsection filling Filling under or between graphs
  12259. QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to
  12260. the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill,
  12261. just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent.
  12262. By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill
  12263. between this graph and another one, call \ref setChannelFillGraph with the other graph as
  12264. parameter.
  12265. \see QCustomPlot::addGraph, QCustomPlot::graph, QCPLegend::addGraph
  12266. */
  12267. /* start of documentation of inline functions */
  12268. /*! \fn QCPDataMap *QCPGraph::data() const
  12269. Returns a pointer to the internal data storage of type \ref QCPDataMap. You may use it to
  12270. directly manipulate the data, which may be more convenient and faster than using the regular \ref
  12271. setData or \ref addData methods, in certain situations.
  12272. */
  12273. /* end of documentation of inline functions */
  12274. /*!
  12275. Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  12276. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  12277. the same orientation. If either of these restrictions is violated, a corresponding message is
  12278. printed to the debug output (qDebug), the construction is not aborted, though.
  12279. The constructed QCPGraph can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
  12280. then takes ownership of the graph.
  12281. To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function.
  12282. */
  12283. QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  12284. QCPAbstractPlottable(keyAxis, valueAxis)
  12285. {
  12286. mData = new QCPDataMap;
  12287. setPen(QPen(Qt::blue, 0));
  12288. setErrorPen(QPen(Qt::black));
  12289. setBrush(Qt::NoBrush);
  12290. setSelectedPen(QPen(QColor(80, 80, 255), 2.5));
  12291. setSelectedBrush(Qt::NoBrush);
  12292. setLineStyle(lsLine);
  12293. setErrorType(etNone);
  12294. setErrorBarSize(6);
  12295. setErrorBarSkipSymbol(true);
  12296. setChannelFillGraph(0);
  12297. setAdaptiveSampling(true);
  12298. }
  12299. QCPGraph::~QCPGraph()
  12300. {
  12301. delete mData;
  12302. }
  12303. /*!
  12304. Replaces the current data with the provided \a data.
  12305. If \a copy is set to true, data points in \a data will only be copied. if false, the graph
  12306. takes ownership of the passed data and replaces the internal data pointer with it. This is
  12307. significantly faster than copying for large datasets.
  12308. Alternatively, you can also access and modify the graph's data via the \ref data method, which
  12309. returns a pointer to the internal \ref QCPDataMap.
  12310. */
  12311. void QCPGraph::setData(QCPDataMap *data, bool copy)
  12312. {
  12313. if (copy)
  12314. {
  12315. *mData = *data;
  12316. } else
  12317. {
  12318. delete mData;
  12319. mData = data;
  12320. }
  12321. }
  12322. /*! \overload
  12323. Replaces the current data with the provided points in \a key and \a value pairs. The provided
  12324. vectors should have equal length. Else, the number of added points will be the size of the
  12325. smallest vector.
  12326. */
  12327. void QCPGraph::setData(const QVector<double> &key, const QVector<double> &value)
  12328. {
  12329. mData->clear();
  12330. int n = key.size();
  12331. n = qMin(n, value.size());
  12332. QCPData newData;
  12333. for (int i=0; i<n; ++i)
  12334. {
  12335. newData.key = key[i];
  12336. newData.value = value[i];
  12337. mData->insertMulti(newData.key, newData);
  12338. }
  12339. }
  12340. /*!
  12341. Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
  12342. symmetrical value error of the data points are set to the values in \a valueError.
  12343. For error bars to show appropriately, see \ref setErrorType.
  12344. The provided vectors should have equal length. Else, the number of added points will be the size of the
  12345. smallest vector.
  12346. For asymmetrical errors (plus different from minus), see the overloaded version of this function.
  12347. */
  12348. void QCPGraph::setDataValueError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &valueError)
  12349. {
  12350. mData->clear();
  12351. int n = key.size();
  12352. n = qMin(n, value.size());
  12353. n = qMin(n, valueError.size());
  12354. QCPData newData;
  12355. for (int i=0; i<n; ++i)
  12356. {
  12357. newData.key = key[i];
  12358. newData.value = value[i];
  12359. newData.valueErrorMinus = valueError[i];
  12360. newData.valueErrorPlus = valueError[i];
  12361. mData->insertMulti(key[i], newData);
  12362. }
  12363. }
  12364. /*!
  12365. \overload
  12366. Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
  12367. negative value error of the data points are set to the values in \a valueErrorMinus, the positive
  12368. value error to \a valueErrorPlus.
  12369. For error bars to show appropriately, see \ref setErrorType.
  12370. The provided vectors should have equal length. Else, the number of added points will be the size of the
  12371. smallest vector.
  12372. */
  12373. void QCPGraph::setDataValueError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &valueErrorMinus, const QVector<double> &valueErrorPlus)
  12374. {
  12375. mData->clear();
  12376. int n = key.size();
  12377. n = qMin(n, value.size());
  12378. n = qMin(n, valueErrorMinus.size());
  12379. n = qMin(n, valueErrorPlus.size());
  12380. QCPData newData;
  12381. for (int i=0; i<n; ++i)
  12382. {
  12383. newData.key = key[i];
  12384. newData.value = value[i];
  12385. newData.valueErrorMinus = valueErrorMinus[i];
  12386. newData.valueErrorPlus = valueErrorPlus[i];
  12387. mData->insertMulti(key[i], newData);
  12388. }
  12389. }
  12390. /*!
  12391. Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
  12392. symmetrical key error of the data points are set to the values in \a keyError.
  12393. For error bars to show appropriately, see \ref setErrorType.
  12394. The provided vectors should have equal length. Else, the number of added points will be the size of the
  12395. smallest vector.
  12396. For asymmetrical errors (plus different from minus), see the overloaded version of this function.
  12397. */
  12398. void QCPGraph::setDataKeyError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyError)
  12399. {
  12400. mData->clear();
  12401. int n = key.size();
  12402. n = qMin(n, value.size());
  12403. n = qMin(n, keyError.size());
  12404. QCPData newData;
  12405. for (int i=0; i<n; ++i)
  12406. {
  12407. newData.key = key[i];
  12408. newData.value = value[i];
  12409. newData.keyErrorMinus = keyError[i];
  12410. newData.keyErrorPlus = keyError[i];
  12411. mData->insertMulti(key[i], newData);
  12412. }
  12413. }
  12414. /*!
  12415. \overload
  12416. Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
  12417. negative key error of the data points are set to the values in \a keyErrorMinus, the positive
  12418. key error to \a keyErrorPlus.
  12419. For error bars to show appropriately, see \ref setErrorType.
  12420. The provided vectors should have equal length. Else, the number of added points will be the size of the
  12421. smallest vector.
  12422. */
  12423. void QCPGraph::setDataKeyError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyErrorMinus, const QVector<double> &keyErrorPlus)
  12424. {
  12425. mData->clear();
  12426. int n = key.size();
  12427. n = qMin(n, value.size());
  12428. n = qMin(n, keyErrorMinus.size());
  12429. n = qMin(n, keyErrorPlus.size());
  12430. QCPData newData;
  12431. for (int i=0; i<n; ++i)
  12432. {
  12433. newData.key = key[i];
  12434. newData.value = value[i];
  12435. newData.keyErrorMinus = keyErrorMinus[i];
  12436. newData.keyErrorPlus = keyErrorPlus[i];
  12437. mData->insertMulti(key[i], newData);
  12438. }
  12439. }
  12440. /*!
  12441. Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
  12442. symmetrical key and value errors of the data points are set to the values in \a keyError and \a valueError.
  12443. For error bars to show appropriately, see \ref setErrorType.
  12444. The provided vectors should have equal length. Else, the number of added points will be the size of the
  12445. smallest vector.
  12446. For asymmetrical errors (plus different from minus), see the overloaded version of this function.
  12447. */
  12448. void QCPGraph::setDataBothError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyError, const QVector<double> &valueError)
  12449. {
  12450. mData->clear();
  12451. int n = key.size();
  12452. n = qMin(n, value.size());
  12453. n = qMin(n, valueError.size());
  12454. n = qMin(n, keyError.size());
  12455. QCPData newData;
  12456. for (int i=0; i<n; ++i)
  12457. {
  12458. newData.key = key[i];
  12459. newData.value = value[i];
  12460. newData.keyErrorMinus = keyError[i];
  12461. newData.keyErrorPlus = keyError[i];
  12462. newData.valueErrorMinus = valueError[i];
  12463. newData.valueErrorPlus = valueError[i];
  12464. mData->insertMulti(key[i], newData);
  12465. }
  12466. }
  12467. /*!
  12468. \overload
  12469. Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
  12470. negative key and value errors of the data points are set to the values in \a keyErrorMinus and \a valueErrorMinus. The positive
  12471. key and value errors are set to the values in \a keyErrorPlus \a valueErrorPlus.
  12472. For error bars to show appropriately, see \ref setErrorType.
  12473. The provided vectors should have equal length. Else, the number of added points will be the size of the
  12474. smallest vector.
  12475. */
  12476. 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)
  12477. {
  12478. mData->clear();
  12479. int n = key.size();
  12480. n = qMin(n, value.size());
  12481. n = qMin(n, valueErrorMinus.size());
  12482. n = qMin(n, valueErrorPlus.size());
  12483. n = qMin(n, keyErrorMinus.size());
  12484. n = qMin(n, keyErrorPlus.size());
  12485. QCPData newData;
  12486. for (int i=0; i<n; ++i)
  12487. {
  12488. newData.key = key[i];
  12489. newData.value = value[i];
  12490. newData.keyErrorMinus = keyErrorMinus[i];
  12491. newData.keyErrorPlus = keyErrorPlus[i];
  12492. newData.valueErrorMinus = valueErrorMinus[i];
  12493. newData.valueErrorPlus = valueErrorPlus[i];
  12494. mData->insertMulti(key[i], newData);
  12495. }
  12496. }
  12497. /*!
  12498. Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
  12499. \ref lsNone and \ref setScatterStyle to the desired scatter style.
  12500. \see setScatterStyle
  12501. */
  12502. void QCPGraph::setLineStyle(LineStyle ls)
  12503. {
  12504. mLineStyle = ls;
  12505. }
  12506. /*!
  12507. Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points
  12508. are drawn (e.g. for line-only-plots with appropriate line style).
  12509. \see QCPScatterStyle, setLineStyle
  12510. */
  12511. void QCPGraph::setScatterStyle(const QCPScatterStyle &style)
  12512. {
  12513. mScatterStyle = style;
  12514. }
  12515. /*!
  12516. Sets which kind of error bars (Key Error, Value Error or both) should be drawn on each data
  12517. point. If you set \a errorType to something other than \ref etNone, make sure to actually pass
  12518. error data via the specific setData functions along with the data points (e.g. \ref
  12519. setDataValueError, \ref setDataKeyError, \ref setDataBothError).
  12520. \see ErrorType
  12521. */
  12522. void QCPGraph::setErrorType(ErrorType errorType)
  12523. {
  12524. mErrorType = errorType;
  12525. }
  12526. /*!
  12527. Sets the pen with which the error bars will be drawn.
  12528. \see setErrorBarSize, setErrorType
  12529. */
  12530. void QCPGraph::setErrorPen(const QPen &pen)
  12531. {
  12532. mErrorPen = pen;
  12533. }
  12534. /*!
  12535. Sets the width of the handles at both ends of an error bar in pixels.
  12536. */
  12537. void QCPGraph::setErrorBarSize(double size)
  12538. {
  12539. mErrorBarSize = size;
  12540. }
  12541. /*!
  12542. If \a enabled is set to true, the error bar will not be drawn as a solid line under the scatter symbol but
  12543. leave some free space around the symbol.
  12544. This feature uses the current scatter size (\ref QCPScatterStyle::setSize) to determine the size
  12545. of the area to leave blank. So when drawing Pixmaps as scatter points (\ref
  12546. QCPScatterStyle::ssPixmap), the scatter size must be set manually to a value corresponding to the
  12547. size of the Pixmap, if the error bars should leave gaps to its boundaries.
  12548. \ref setErrorType, setErrorBarSize, setScatterStyle
  12549. */
  12550. void QCPGraph::setErrorBarSkipSymbol(bool enabled)
  12551. {
  12552. mErrorBarSkipSymbol = enabled;
  12553. }
  12554. /*!
  12555. Sets the target graph for filling the area between this graph and \a targetGraph with the current
  12556. brush (\ref setBrush).
  12557. When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To
  12558. disable any filling, set the brush to Qt::NoBrush.
  12559. \see setBrush
  12560. */
  12561. void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph)
  12562. {
  12563. // prevent setting channel target to this graph itself:
  12564. if (targetGraph == this)
  12565. {
  12566. qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself";
  12567. mChannelFillGraph = 0;
  12568. return;
  12569. }
  12570. // prevent setting channel target to a graph not in the plot:
  12571. if (targetGraph && targetGraph->mParentPlot != mParentPlot)
  12572. {
  12573. qDebug() << Q_FUNC_INFO << "targetGraph not in same plot";
  12574. mChannelFillGraph = 0;
  12575. return;
  12576. }
  12577. mChannelFillGraph = targetGraph;
  12578. }
  12579. /*!
  12580. Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive
  12581. sampling technique can drastically improve the replot performance for graphs with a larger number
  12582. of points (e.g. above 10,000), without notably changing the appearance of the graph.
  12583. By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive
  12584. sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no
  12585. disadvantage in almost all cases.
  12586. \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling"
  12587. As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are
  12588. reproduced reliably, as well as the overall shape of the data set. The replot time reduces
  12589. dramatically though. This allows QCustomPlot to display large amounts of data in realtime.
  12590. \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling"
  12591. Care must be taken when using high-density scatter plots in combination with adaptive sampling.
  12592. The adaptive sampling algorithm treats scatter plots more carefully than line plots which still
  12593. gives a significant reduction of replot times, but not quite as much as for line plots. This is
  12594. because scatter plots inherently need more data points to be preserved in order to still resemble
  12595. the original, non-adaptive-sampling plot. As shown above, the results still aren't quite
  12596. identical, as banding occurs for the outer data points. This is in fact intentional, such that
  12597. the boundaries of the data cloud stay visible to the viewer. How strong the banding appears,
  12598. depends on the point density, i.e. the number of points in the plot.
  12599. For some situations with scatter plots it might thus be desirable to manually turn adaptive
  12600. sampling off. For example, when saving the plot to disk. This can be achieved by setting \a
  12601. enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled
  12602. back to true afterwards.
  12603. */
  12604. void QCPGraph::setAdaptiveSampling(bool enabled)
  12605. {
  12606. mAdaptiveSampling = enabled;
  12607. }
  12608. /*!
  12609. Adds the provided data points in \a dataMap to the current data.
  12610. Alternatively, you can also access and modify the graph's data via the \ref data method, which
  12611. returns a pointer to the internal \ref QCPDataMap.
  12612. \see removeData
  12613. */
  12614. void QCPGraph::addData(const QCPDataMap &dataMap)
  12615. {
  12616. mData->unite(dataMap);
  12617. }
  12618. /*! \overload
  12619. Adds the provided single data point in \a data to the current data.
  12620. Alternatively, you can also access and modify the graph's data via the \ref data method, which
  12621. returns a pointer to the internal \ref QCPDataMap.
  12622. \see removeData
  12623. */
  12624. void QCPGraph::addData(const QCPData &data)
  12625. {
  12626. mData->insertMulti(data.key, data);
  12627. }
  12628. /*! \overload
  12629. Adds the provided single data point as \a key and \a value pair to the current data.
  12630. Alternatively, you can also access and modify the graph's data via the \ref data method, which
  12631. returns a pointer to the internal \ref QCPDataMap.
  12632. \see removeData
  12633. */
  12634. void QCPGraph::addData(double key, double value)
  12635. {
  12636. QCPData newData;
  12637. newData.key = key;
  12638. newData.value = value;
  12639. mData->insertMulti(newData.key, newData);
  12640. }
  12641. /*! \overload
  12642. Adds the provided data points as \a key and \a value pairs to the current data.
  12643. Alternatively, you can also access and modify the graph's data via the \ref data method, which
  12644. returns a pointer to the internal \ref QCPDataMap.
  12645. \see removeData
  12646. */
  12647. void QCPGraph::addData(const QVector<double> &keys, const QVector<double> &values)
  12648. {
  12649. int n = qMin(keys.size(), values.size());
  12650. QCPData newData;
  12651. for (int i=0; i<n; ++i)
  12652. {
  12653. newData.key = keys[i];
  12654. newData.value = values[i];
  12655. mData->insertMulti(newData.key, newData);
  12656. }
  12657. }
  12658. /*!
  12659. Removes all data points with keys smaller than \a key.
  12660. \see addData, clearData
  12661. */
  12662. void QCPGraph::removeDataBefore(double key)
  12663. {
  12664. QCPDataMap::iterator it = mData->begin();
  12665. while (it != mData->end() && it.key() < key)
  12666. it = mData->erase(it);
  12667. }
  12668. /*!
  12669. Removes all data points with keys greater than \a key.
  12670. \see addData, clearData
  12671. */
  12672. void QCPGraph::removeDataAfter(double key)
  12673. {
  12674. if (mData->isEmpty()) return;
  12675. QCPDataMap::iterator it = mData->upperBound(key);
  12676. while (it != mData->end())
  12677. it = mData->erase(it);
  12678. }
  12679. /*!
  12680. Removes all data points with keys between \a fromKey and \a toKey.
  12681. if \a fromKey is greater or equal to \a toKey, the function does nothing. To remove
  12682. a single data point with known key, use \ref removeData(double key).
  12683. \see addData, clearData
  12684. */
  12685. void QCPGraph::removeData(double fromKey, double toKey)
  12686. {
  12687. if (fromKey >= toKey || mData->isEmpty()) return;
  12688. QCPDataMap::iterator it = mData->upperBound(fromKey);
  12689. QCPDataMap::iterator itEnd = mData->upperBound(toKey);
  12690. while (it != itEnd)
  12691. it = mData->erase(it);
  12692. }
  12693. /*! \overload
  12694. Removes a single data point at \a key. If the position is not known with absolute precision,
  12695. consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval around
  12696. the suspected position, depeding on the precision with which the key is known.
  12697. \see addData, clearData
  12698. */
  12699. void QCPGraph::removeData(double key)
  12700. {
  12701. mData->remove(key);
  12702. }
  12703. /*!
  12704. Removes all data points.
  12705. \see removeData, removeDataAfter, removeDataBefore
  12706. */
  12707. void QCPGraph::clearData()
  12708. {
  12709. mData->clear();
  12710. }
  12711. /* inherits documentation from base class */
  12712. double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  12713. {
  12714. Q_UNUSED(details)
  12715. if ((onlySelectable && !mSelectable) || mData->isEmpty())
  12716. return -1;
  12717. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  12718. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
  12719. return pointDistance(pos);
  12720. else
  12721. return -1;
  12722. }
  12723. /*! \overload
  12724. Allows to define whether error bars are taken into consideration when determining the new axis
  12725. range.
  12726. \see rescaleKeyAxis, rescaleValueAxis, QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
  12727. */
  12728. void QCPGraph::rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const
  12729. {
  12730. rescaleKeyAxis(onlyEnlarge, includeErrorBars);
  12731. rescaleValueAxis(onlyEnlarge, includeErrorBars);
  12732. }
  12733. /*! \overload
  12734. Allows to define whether error bars (of kind \ref QCPGraph::etKey) are taken into consideration
  12735. when determining the new axis range.
  12736. \see rescaleAxes, QCPAbstractPlottable::rescaleKeyAxis
  12737. */
  12738. void QCPGraph::rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const
  12739. {
  12740. // this code is a copy of QCPAbstractPlottable::rescaleKeyAxis with the only change
  12741. // that getKeyRange is passed the includeErrorBars value.
  12742. if (mData->isEmpty()) return;
  12743. QCPAxis *keyAxis = mKeyAxis.data();
  12744. if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
  12745. SignDomain signDomain = sdBoth;
  12746. if (keyAxis->scaleType() == QCPAxis::stLogarithmic)
  12747. signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive);
  12748. bool foundRange;
  12749. QCPRange newRange = getKeyRange(foundRange, signDomain, includeErrorBars);
  12750. if (foundRange)
  12751. {
  12752. if (onlyEnlarge)
  12753. {
  12754. if (keyAxis->range().lower < newRange.lower)
  12755. newRange.lower = keyAxis->range().lower;
  12756. if (keyAxis->range().upper > newRange.upper)
  12757. newRange.upper = keyAxis->range().upper;
  12758. }
  12759. keyAxis->setRange(newRange);
  12760. }
  12761. }
  12762. /*! \overload
  12763. Allows to define whether error bars (of kind \ref QCPGraph::etValue) are taken into consideration
  12764. when determining the new axis range.
  12765. \see rescaleAxes, QCPAbstractPlottable::rescaleValueAxis
  12766. */
  12767. void QCPGraph::rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const
  12768. {
  12769. // this code is a copy of QCPAbstractPlottable::rescaleValueAxis with the only change
  12770. // is that getValueRange is passed the includeErrorBars value.
  12771. if (mData->isEmpty()) return;
  12772. QCPAxis *valueAxis = mValueAxis.data();
  12773. if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; }
  12774. SignDomain signDomain = sdBoth;
  12775. if (valueAxis->scaleType() == QCPAxis::stLogarithmic)
  12776. signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive);
  12777. bool foundRange;
  12778. QCPRange newRange = getValueRange(foundRange, signDomain, includeErrorBars);
  12779. if (foundRange)
  12780. {
  12781. if (onlyEnlarge)
  12782. {
  12783. if (valueAxis->range().lower < newRange.lower)
  12784. newRange.lower = valueAxis->range().lower;
  12785. if (valueAxis->range().upper > newRange.upper)
  12786. newRange.upper = valueAxis->range().upper;
  12787. }
  12788. valueAxis->setRange(newRange);
  12789. }
  12790. }
  12791. /* inherits documentation from base class */
  12792. void QCPGraph::draw(QCPPainter *painter)
  12793. {
  12794. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  12795. if (mKeyAxis.data()->range().size() <= 0 || mData->isEmpty()) return;
  12796. if (mLineStyle == lsNone && mScatterStyle.isNone()) return;
  12797. // allocate line and (if necessary) point vectors:
  12798. QVector<QPointF> *lineData = new QVector<QPointF>;
  12799. QVector<QCPData> *scatterData = 0;
  12800. if (!mScatterStyle.isNone())
  12801. scatterData = new QVector<QCPData>;
  12802. // fill vectors with data appropriate to plot style:
  12803. getPlotData(lineData, scatterData);
  12804. // check data validity if flag set:
  12805. #ifdef QCUSTOMPLOT_CHECK_DATA
  12806. QCPDataMap::const_iterator it;
  12807. for (it = mData->constBegin(); it != mData->constEnd(); ++it)
  12808. {
  12809. if (QCP::isInvalidData(it.value().key, it.value().value) ||
  12810. QCP::isInvalidData(it.value().keyErrorPlus, it.value().keyErrorMinus) ||
  12811. QCP::isInvalidData(it.value().valueErrorPlus, it.value().valueErrorPlus))
  12812. qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name();
  12813. }
  12814. #endif
  12815. // draw fill of graph:
  12816. drawFill(painter, lineData);
  12817. // draw line:
  12818. if (mLineStyle == lsImpulse)
  12819. drawImpulsePlot(painter, lineData);
  12820. else if (mLineStyle != lsNone)
  12821. drawLinePlot(painter, lineData); // also step plots can be drawn as a line plot
  12822. // draw scatters:
  12823. if (scatterData)
  12824. drawScatterPlot(painter, scatterData);
  12825. // free allocated line and point vectors:
  12826. delete lineData;
  12827. if (scatterData)
  12828. delete scatterData;
  12829. }
  12830. /* inherits documentation from base class */
  12831. void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  12832. {
  12833. // draw fill:
  12834. if (mBrush.style() != Qt::NoBrush)
  12835. {
  12836. applyFillAntialiasingHint(painter);
  12837. painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
  12838. }
  12839. // draw line vertically centered:
  12840. if (mLineStyle != lsNone)
  12841. {
  12842. applyDefaultAntialiasingHint(painter);
  12843. painter->setPen(mPen);
  12844. 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
  12845. }
  12846. // draw scatter symbol:
  12847. if (!mScatterStyle.isNone())
  12848. {
  12849. applyScattersAntialiasingHint(painter);
  12850. // scale scatter pixmap if it's too large to fit in legend icon rect:
  12851. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
  12852. {
  12853. QCPScatterStyle scaledStyle(mScatterStyle);
  12854. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  12855. scaledStyle.applyTo(painter, mPen);
  12856. scaledStyle.drawShape(painter, QRectF(rect).center());
  12857. } else
  12858. {
  12859. mScatterStyle.applyTo(painter, mPen);
  12860. mScatterStyle.drawShape(painter, QRectF(rect).center());
  12861. }
  12862. }
  12863. }
  12864. /*! \internal
  12865. This function branches out to the line style specific "get(...)PlotData" functions, according to
  12866. the line style of the graph.
  12867. \a lineData will be filled with raw points that will be drawn with the according draw functions,
  12868. e.g. \ref drawLinePlot and \ref drawImpulsePlot. These aren't necessarily the original data
  12869. points, since for step plots for example, additional points are needed for drawing lines that
  12870. make up steps. If the line style of the graph is \ref lsNone, the \a lineData vector will be left
  12871. untouched.
  12872. \a scatterData will be filled with the original data points so \ref drawScatterPlot can draw the
  12873. scatter symbols accordingly. If no scatters need to be drawn, i.e. the scatter style's shape is
  12874. \ref QCPScatterStyle::ssNone, pass 0 as \a scatterData, and this step will be skipped.
  12875. \see getScatterPlotData, getLinePlotData, getStepLeftPlotData, getStepRightPlotData,
  12876. getStepCenterPlotData, getImpulsePlotData
  12877. */
  12878. void QCPGraph::getPlotData(QVector<QPointF> *lineData, QVector<QCPData> *scatterData) const
  12879. {
  12880. switch(mLineStyle)
  12881. {
  12882. case lsNone: getScatterPlotData(scatterData); break;
  12883. case lsLine: getLinePlotData(lineData, scatterData); break;
  12884. case lsStepLeft: getStepLeftPlotData(lineData, scatterData); break;
  12885. case lsStepRight: getStepRightPlotData(lineData, scatterData); break;
  12886. case lsStepCenter: getStepCenterPlotData(lineData, scatterData); break;
  12887. case lsImpulse: getImpulsePlotData(lineData, scatterData); break;
  12888. }
  12889. }
  12890. /*! \internal
  12891. If line style is \ref lsNone and the scatter style's shape is not \ref QCPScatterStyle::ssNone,
  12892. this function serves at providing the visible data points in \a scatterData, so the \ref
  12893. drawScatterPlot function can draw the scatter points accordingly.
  12894. If line style is not \ref lsNone, this function is not called and the data for the scatter points
  12895. are (if needed) calculated inside the corresponding other "get(...)PlotData" functions.
  12896. \see drawScatterPlot
  12897. */
  12898. void QCPGraph::getScatterPlotData(QVector<QCPData> *scatterData) const
  12899. {
  12900. getPreparedData(0, scatterData);
  12901. }
  12902. /*! \internal
  12903. Places the raw data points needed for a normal linearly connected graph in \a linePixelData.
  12904. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
  12905. points that are visible for drawing scatter points, if necessary. If drawing scatter points is
  12906. disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
  12907. scatterData, and the function will skip filling the vector.
  12908. \see drawLinePlot
  12909. */
  12910. void QCPGraph::getLinePlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
  12911. {
  12912. QCPAxis *keyAxis = mKeyAxis.data();
  12913. QCPAxis *valueAxis = mValueAxis.data();
  12914. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  12915. if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; }
  12916. QVector<QCPData> lineData;
  12917. getPreparedData(&lineData, scatterData);
  12918. linePixelData->reserve(lineData.size()+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
  12919. linePixelData->resize(lineData.size());
  12920. // transform lineData points to pixels:
  12921. if (keyAxis->orientation() == Qt::Vertical)
  12922. {
  12923. for (int i=0; i<lineData.size(); ++i)
  12924. {
  12925. (*linePixelData)[i].setX(valueAxis->coordToPixel(lineData.at(i).value));
  12926. (*linePixelData)[i].setY(keyAxis->coordToPixel(lineData.at(i).key));
  12927. }
  12928. } else // key axis is horizontal
  12929. {
  12930. for (int i=0; i<lineData.size(); ++i)
  12931. {
  12932. (*linePixelData)[i].setX(keyAxis->coordToPixel(lineData.at(i).key));
  12933. (*linePixelData)[i].setY(valueAxis->coordToPixel(lineData.at(i).value));
  12934. }
  12935. }
  12936. }
  12937. /*!
  12938. \internal
  12939. Places the raw data points needed for a step plot with left oriented steps in \a lineData.
  12940. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
  12941. points that are visible for drawing scatter points, if necessary. If drawing scatter points is
  12942. disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
  12943. scatterData, and the function will skip filling the vector.
  12944. \see drawLinePlot
  12945. */
  12946. void QCPGraph::getStepLeftPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
  12947. {
  12948. QCPAxis *keyAxis = mKeyAxis.data();
  12949. QCPAxis *valueAxis = mValueAxis.data();
  12950. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  12951. if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; }
  12952. QVector<QCPData> lineData;
  12953. getPreparedData(&lineData, scatterData);
  12954. linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
  12955. linePixelData->resize(lineData.size()*2);
  12956. // calculate steps from lineData and transform to pixel coordinates:
  12957. if (keyAxis->orientation() == Qt::Vertical)
  12958. {
  12959. double lastValue = valueAxis->coordToPixel(lineData.first().value);
  12960. double key;
  12961. for (int i=0; i<lineData.size(); ++i)
  12962. {
  12963. key = keyAxis->coordToPixel(lineData.at(i).key);
  12964. (*linePixelData)[i*2+0].setX(lastValue);
  12965. (*linePixelData)[i*2+0].setY(key);
  12966. lastValue = valueAxis->coordToPixel(lineData.at(i).value);
  12967. (*linePixelData)[i*2+1].setX(lastValue);
  12968. (*linePixelData)[i*2+1].setY(key);
  12969. }
  12970. } else // key axis is horizontal
  12971. {
  12972. double lastValue = valueAxis->coordToPixel(lineData.first().value);
  12973. double key;
  12974. for (int i=0; i<lineData.size(); ++i)
  12975. {
  12976. key = keyAxis->coordToPixel(lineData.at(i).key);
  12977. (*linePixelData)[i*2+0].setX(key);
  12978. (*linePixelData)[i*2+0].setY(lastValue);
  12979. lastValue = valueAxis->coordToPixel(lineData.at(i).value);
  12980. (*linePixelData)[i*2+1].setX(key);
  12981. (*linePixelData)[i*2+1].setY(lastValue);
  12982. }
  12983. }
  12984. }
  12985. /*!
  12986. \internal
  12987. Places the raw data points needed for a step plot with right oriented steps in \a lineData.
  12988. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
  12989. points that are visible for drawing scatter points, if necessary. If drawing scatter points is
  12990. disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
  12991. scatterData, and the function will skip filling the vector.
  12992. \see drawLinePlot
  12993. */
  12994. void QCPGraph::getStepRightPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
  12995. {
  12996. QCPAxis *keyAxis = mKeyAxis.data();
  12997. QCPAxis *valueAxis = mValueAxis.data();
  12998. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  12999. if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; }
  13000. QVector<QCPData> lineData;
  13001. getPreparedData(&lineData, scatterData);
  13002. linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
  13003. linePixelData->resize(lineData.size()*2);
  13004. // calculate steps from lineData and transform to pixel coordinates:
  13005. if (keyAxis->orientation() == Qt::Vertical)
  13006. {
  13007. double lastKey = keyAxis->coordToPixel(lineData.first().key);
  13008. double value;
  13009. for (int i=0; i<lineData.size(); ++i)
  13010. {
  13011. value = valueAxis->coordToPixel(lineData.at(i).value);
  13012. (*linePixelData)[i*2+0].setX(value);
  13013. (*linePixelData)[i*2+0].setY(lastKey);
  13014. lastKey = keyAxis->coordToPixel(lineData.at(i).key);
  13015. (*linePixelData)[i*2+1].setX(value);
  13016. (*linePixelData)[i*2+1].setY(lastKey);
  13017. }
  13018. } else // key axis is horizontal
  13019. {
  13020. double lastKey = keyAxis->coordToPixel(lineData.first().key);
  13021. double value;
  13022. for (int i=0; i<lineData.size(); ++i)
  13023. {
  13024. value = valueAxis->coordToPixel(lineData.at(i).value);
  13025. (*linePixelData)[i*2+0].setX(lastKey);
  13026. (*linePixelData)[i*2+0].setY(value);
  13027. lastKey = keyAxis->coordToPixel(lineData.at(i).key);
  13028. (*linePixelData)[i*2+1].setX(lastKey);
  13029. (*linePixelData)[i*2+1].setY(value);
  13030. }
  13031. }
  13032. }
  13033. /*!
  13034. \internal
  13035. Places the raw data points needed for a step plot with centered steps in \a lineData.
  13036. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
  13037. points that are visible for drawing scatter points, if necessary. If drawing scatter points is
  13038. disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
  13039. scatterData, and the function will skip filling the vector.
  13040. \see drawLinePlot
  13041. */
  13042. void QCPGraph::getStepCenterPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
  13043. {
  13044. QCPAxis *keyAxis = mKeyAxis.data();
  13045. QCPAxis *valueAxis = mValueAxis.data();
  13046. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  13047. if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; }
  13048. QVector<QCPData> lineData;
  13049. getPreparedData(&lineData, scatterData);
  13050. linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
  13051. linePixelData->resize(lineData.size()*2);
  13052. // calculate steps from lineData and transform to pixel coordinates:
  13053. if (keyAxis->orientation() == Qt::Vertical)
  13054. {
  13055. double lastKey = keyAxis->coordToPixel(lineData.first().key);
  13056. double lastValue = valueAxis->coordToPixel(lineData.first().value);
  13057. double key;
  13058. (*linePixelData)[0].setX(lastValue);
  13059. (*linePixelData)[0].setY(lastKey);
  13060. for (int i=1; i<lineData.size(); ++i)
  13061. {
  13062. key = (keyAxis->coordToPixel(lineData.at(i).key)+lastKey)*0.5;
  13063. (*linePixelData)[i*2-1].setX(lastValue);
  13064. (*linePixelData)[i*2-1].setY(key);
  13065. lastValue = valueAxis->coordToPixel(lineData.at(i).value);
  13066. lastKey = keyAxis->coordToPixel(lineData.at(i).key);
  13067. (*linePixelData)[i*2+0].setX(lastValue);
  13068. (*linePixelData)[i*2+0].setY(key);
  13069. }
  13070. (*linePixelData)[lineData.size()*2-1].setX(lastValue);
  13071. (*linePixelData)[lineData.size()*2-1].setY(lastKey);
  13072. } else // key axis is horizontal
  13073. {
  13074. double lastKey = keyAxis->coordToPixel(lineData.first().key);
  13075. double lastValue = valueAxis->coordToPixel(lineData.first().value);
  13076. double key;
  13077. (*linePixelData)[0].setX(lastKey);
  13078. (*linePixelData)[0].setY(lastValue);
  13079. for (int i=1; i<lineData.size(); ++i)
  13080. {
  13081. key = (keyAxis->coordToPixel(lineData.at(i).key)+lastKey)*0.5;
  13082. (*linePixelData)[i*2-1].setX(key);
  13083. (*linePixelData)[i*2-1].setY(lastValue);
  13084. lastValue = valueAxis->coordToPixel(lineData.at(i).value);
  13085. lastKey = keyAxis->coordToPixel(lineData.at(i).key);
  13086. (*linePixelData)[i*2+0].setX(key);
  13087. (*linePixelData)[i*2+0].setY(lastValue);
  13088. }
  13089. (*linePixelData)[lineData.size()*2-1].setX(lastKey);
  13090. (*linePixelData)[lineData.size()*2-1].setY(lastValue);
  13091. }
  13092. }
  13093. /*!
  13094. \internal
  13095. Places the raw data points needed for an impulse plot in \a lineData.
  13096. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
  13097. points that are visible for drawing scatter points, if necessary. If drawing scatter points is
  13098. disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
  13099. scatterData, and the function will skip filling the vector.
  13100. \see drawImpulsePlot
  13101. */
  13102. void QCPGraph::getImpulsePlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
  13103. {
  13104. QCPAxis *keyAxis = mKeyAxis.data();
  13105. QCPAxis *valueAxis = mValueAxis.data();
  13106. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  13107. if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; }
  13108. QVector<QCPData> lineData;
  13109. getPreparedData(&lineData, scatterData);
  13110. linePixelData->resize(lineData.size()*2); // no need to reserve 2 extra points because impulse plot has no fill
  13111. // transform lineData points to pixels:
  13112. if (keyAxis->orientation() == Qt::Vertical)
  13113. {
  13114. double zeroPointX = valueAxis->coordToPixel(0);
  13115. double key;
  13116. for (int i=0; i<lineData.size(); ++i)
  13117. {
  13118. key = keyAxis->coordToPixel(lineData.at(i).key);
  13119. (*linePixelData)[i*2+0].setX(zeroPointX);
  13120. (*linePixelData)[i*2+0].setY(key);
  13121. (*linePixelData)[i*2+1].setX(valueAxis->coordToPixel(lineData.at(i).value));
  13122. (*linePixelData)[i*2+1].setY(key);
  13123. }
  13124. } else // key axis is horizontal
  13125. {
  13126. double zeroPointY = valueAxis->coordToPixel(0);
  13127. double key;
  13128. for (int i=0; i<lineData.size(); ++i)
  13129. {
  13130. key = keyAxis->coordToPixel(lineData.at(i).key);
  13131. (*linePixelData)[i*2+0].setX(key);
  13132. (*linePixelData)[i*2+0].setY(zeroPointY);
  13133. (*linePixelData)[i*2+1].setX(key);
  13134. (*linePixelData)[i*2+1].setY(valueAxis->coordToPixel(lineData.at(i).value));
  13135. }
  13136. }
  13137. }
  13138. /*! \internal
  13139. Draws the fill of the graph with the specified brush.
  13140. If the fill is a normal fill towards the zero-value-line, only the \a lineData is required (and
  13141. two extra points at the zero-value-line, which are added by \ref addFillBasePoints and removed by
  13142. \ref removeFillBasePoints after the fill drawing is done).
  13143. If the fill is a channel fill between this QCPGraph and another QCPGraph (mChannelFillGraph), the
  13144. more complex polygon is calculated with the \ref getChannelFillPolygon function.
  13145. \see drawLinePlot
  13146. */
  13147. void QCPGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lineData) const
  13148. {
  13149. if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot
  13150. if (mainBrush().style() == Qt::NoBrush || mainBrush().color().alpha() == 0) return;
  13151. applyFillAntialiasingHint(painter);
  13152. if (!mChannelFillGraph)
  13153. {
  13154. // draw base fill under graph, fill goes all the way to the zero-value-line:
  13155. addFillBasePoints(lineData);
  13156. painter->setPen(Qt::NoPen);
  13157. painter->setBrush(mainBrush());
  13158. painter->drawPolygon(QPolygonF(*lineData));
  13159. removeFillBasePoints(lineData);
  13160. } else
  13161. {
  13162. // draw channel fill between this graph and mChannelFillGraph:
  13163. painter->setPen(Qt::NoPen);
  13164. painter->setBrush(mainBrush());
  13165. painter->drawPolygon(getChannelFillPolygon(lineData));
  13166. }
  13167. }
  13168. /*! \internal
  13169. Draws scatter symbols at every data point passed in \a scatterData. scatter symbols are independent
  13170. of the line style and are always drawn if the scatter style's shape is not \ref
  13171. QCPScatterStyle::ssNone. Hence, the \a scatterData vector is outputted by all "get(...)PlotData"
  13172. functions, together with the (line style dependent) line data.
  13173. \see drawLinePlot, drawImpulsePlot
  13174. */
  13175. void QCPGraph::drawScatterPlot(QCPPainter *painter, QVector<QCPData> *scatterData) const
  13176. {
  13177. QCPAxis *keyAxis = mKeyAxis.data();
  13178. QCPAxis *valueAxis = mValueAxis.data();
  13179. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  13180. // draw error bars:
  13181. if (mErrorType != etNone)
  13182. {
  13183. applyErrorBarsAntialiasingHint(painter);
  13184. painter->setPen(mErrorPen);
  13185. if (keyAxis->orientation() == Qt::Vertical)
  13186. {
  13187. for (int i=0; i<scatterData->size(); ++i)
  13188. drawError(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key), scatterData->at(i));
  13189. } else
  13190. {
  13191. for (int i=0; i<scatterData->size(); ++i)
  13192. drawError(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value), scatterData->at(i));
  13193. }
  13194. }
  13195. // draw scatter point symbols:
  13196. applyScattersAntialiasingHint(painter);
  13197. mScatterStyle.applyTo(painter, mPen);
  13198. if (keyAxis->orientation() == Qt::Vertical)
  13199. {
  13200. for (int i=0; i<scatterData->size(); ++i)
  13201. mScatterStyle.drawShape(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key));
  13202. } else
  13203. {
  13204. for (int i=0; i<scatterData->size(); ++i)
  13205. mScatterStyle.drawShape(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value));
  13206. }
  13207. }
  13208. /*! \internal
  13209. Draws line graphs from the provided data. It connects all points in \a lineData, which was
  13210. created by one of the "get(...)PlotData" functions for line styles that require simple line
  13211. connections between the point vector they create. These are for example \ref getLinePlotData,
  13212. \ref getStepLeftPlotData, \ref getStepRightPlotData and \ref getStepCenterPlotData.
  13213. \see drawScatterPlot, drawImpulsePlot
  13214. */
  13215. void QCPGraph::drawLinePlot(QCPPainter *painter, QVector<QPointF> *lineData) const
  13216. {
  13217. // draw line of graph:
  13218. if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)
  13219. {
  13220. applyDefaultAntialiasingHint(painter);
  13221. painter->setPen(mainPen());
  13222. painter->setBrush(Qt::NoBrush);
  13223. /* Draws polyline in batches, currently not used:
  13224. int p = 0;
  13225. while (p < lineData->size())
  13226. {
  13227. int batch = qMin(25, lineData->size()-p);
  13228. if (p != 0)
  13229. {
  13230. ++batch;
  13231. --p; // to draw the connection lines between two batches
  13232. }
  13233. painter->drawPolyline(lineData->constData()+p, batch);
  13234. p += batch;
  13235. }
  13236. */
  13237. // if drawing solid line and not in PDF, use much faster line drawing instead of polyline:
  13238. if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) &&
  13239. painter->pen().style() == Qt::SolidLine &&
  13240. !painter->modes().testFlag(QCPPainter::pmVectorized)&&
  13241. !painter->modes().testFlag(QCPPainter::pmNoCaching))
  13242. {
  13243. for (int i=1; i<lineData->size(); ++i)
  13244. painter->drawLine(lineData->at(i-1), lineData->at(i));
  13245. } else
  13246. {
  13247. painter->drawPolyline(QPolygonF(*lineData));
  13248. }
  13249. }
  13250. }
  13251. /*! \internal
  13252. Draws impulses from the provided data, i.e. it connects all line pairs in \a lineData, which was
  13253. created by \ref getImpulsePlotData.
  13254. \see drawScatterPlot, drawLinePlot
  13255. */
  13256. void QCPGraph::drawImpulsePlot(QCPPainter *painter, QVector<QPointF> *lineData) const
  13257. {
  13258. // draw impulses:
  13259. if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)
  13260. {
  13261. applyDefaultAntialiasingHint(painter);
  13262. QPen pen = mainPen();
  13263. pen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line
  13264. painter->setPen(pen);
  13265. painter->setBrush(Qt::NoBrush);
  13266. painter->drawLines(*lineData);
  13267. }
  13268. }
  13269. /*! \internal
  13270. Returns the \a lineData and \a scatterData that need to be plotted for this graph taking into
  13271. consideration the current axis ranges and, if \ref setAdaptiveSampling is enabled, local point
  13272. densities.
  13273. 0 may be passed as \a lineData or \a scatterData to indicate that the respective dataset isn't
  13274. needed. For example, if the scatter style (\ref setScatterStyle) is \ref QCPScatterStyle::ssNone, \a
  13275. scatterData should be 0 to prevent unnecessary calculations.
  13276. This method is used by the various "get(...)PlotData" methods to get the basic working set of data.
  13277. */
  13278. void QCPGraph::getPreparedData(QVector<QCPData> *lineData, QVector<QCPData> *scatterData) const
  13279. {
  13280. QCPAxis *keyAxis = mKeyAxis.data();
  13281. QCPAxis *valueAxis = mValueAxis.data();
  13282. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  13283. // get visible data range:
  13284. QCPDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point
  13285. getVisibleDataBounds(lower, upper);
  13286. if (lower == mData->constEnd() || upper == mData->constEnd())
  13287. return;
  13288. // count points in visible range, taking into account that we only need to count to the limit maxCount if using adaptive sampling:
  13289. int maxCount = std::numeric_limits<int>::max();
  13290. if (mAdaptiveSampling)
  13291. {
  13292. int keyPixelSpan = qAbs(keyAxis->coordToPixel(lower.key())-keyAxis->coordToPixel(upper.key()));
  13293. maxCount = 2*keyPixelSpan+2;
  13294. }
  13295. int dataCount = countDataInBounds(lower, upper, maxCount);
  13296. if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
  13297. {
  13298. if (lineData)
  13299. {
  13300. QCPDataMap::const_iterator it = lower;
  13301. QCPDataMap::const_iterator upperEnd = upper+1;
  13302. double minValue = it.value().value;
  13303. double maxValue = it.value().value;
  13304. QCPDataMap::const_iterator currentIntervalFirstPoint = it;
  13305. int reversedFactor = keyAxis->rangeReversed() ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction
  13306. int reversedRound = keyAxis->rangeReversed() ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
  13307. double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound));
  13308. double lastIntervalEndKey = currentIntervalStartKey;
  13309. double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
  13310. bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
  13311. int intervalDataCount = 1;
  13312. ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect
  13313. while (it != upperEnd)
  13314. {
  13315. if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary
  13316. {
  13317. if (it.value().value < minValue)
  13318. minValue = it.value().value;
  13319. else if (it.value().value > maxValue)
  13320. maxValue = it.value().value;
  13321. ++intervalDataCount;
  13322. } else // new pixel interval started
  13323. {
  13324. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
  13325. {
  13326. if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point
  13327. lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value));
  13328. lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
  13329. lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
  13330. 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
  13331. lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.8, (it-1).value().value));
  13332. } else
  13333. lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value));
  13334. lastIntervalEndKey = (it-1).value().key;
  13335. minValue = it.value().value;
  13336. maxValue = it.value().value;
  13337. currentIntervalFirstPoint = it;
  13338. currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound));
  13339. if (keyEpsilonVariable)
  13340. keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
  13341. intervalDataCount = 1;
  13342. }
  13343. ++it;
  13344. }
  13345. // handle last interval:
  13346. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
  13347. {
  13348. if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point
  13349. lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value));
  13350. lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
  13351. lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
  13352. } else
  13353. lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value));
  13354. }
  13355. if (scatterData)
  13356. {
  13357. double valueMaxRange = valueAxis->range().upper;
  13358. double valueMinRange = valueAxis->range().lower;
  13359. QCPDataMap::const_iterator it = lower;
  13360. QCPDataMap::const_iterator upperEnd = upper+1;
  13361. double minValue = it.value().value;
  13362. double maxValue = it.value().value;
  13363. QCPDataMap::const_iterator minValueIt = it;
  13364. QCPDataMap::const_iterator maxValueIt = it;
  13365. QCPDataMap::const_iterator currentIntervalStart = it;
  13366. int reversedFactor = keyAxis->rangeReversed() ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction
  13367. int reversedRound = keyAxis->rangeReversed() ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
  13368. double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound));
  13369. double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
  13370. bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
  13371. int intervalDataCount = 1;
  13372. ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect
  13373. while (it != upperEnd)
  13374. {
  13375. if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary
  13376. {
  13377. if (it.value().value < minValue && it.value().value > valueMinRange && it.value().value < valueMaxRange)
  13378. {
  13379. minValue = it.value().value;
  13380. minValueIt = it;
  13381. } else if (it.value().value > maxValue && it.value().value > valueMinRange && it.value().value < valueMaxRange)
  13382. {
  13383. maxValue = it.value().value;
  13384. maxValueIt = it;
  13385. }
  13386. ++intervalDataCount;
  13387. } else // new pixel started
  13388. {
  13389. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
  13390. {
  13391. // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
  13392. double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
  13393. int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
  13394. QCPDataMap::const_iterator intervalIt = currentIntervalStart;
  13395. int c = 0;
  13396. while (intervalIt != it)
  13397. {
  13398. if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange)
  13399. scatterData->append(intervalIt.value());
  13400. ++c;
  13401. ++intervalIt;
  13402. }
  13403. } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange)
  13404. scatterData->append(currentIntervalStart.value());
  13405. minValue = it.value().value;
  13406. maxValue = it.value().value;
  13407. currentIntervalStart = it;
  13408. currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound));
  13409. if (keyEpsilonVariable)
  13410. keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
  13411. intervalDataCount = 1;
  13412. }
  13413. ++it;
  13414. }
  13415. // handle last interval:
  13416. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
  13417. {
  13418. // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
  13419. double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
  13420. int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
  13421. QCPDataMap::const_iterator intervalIt = currentIntervalStart;
  13422. int c = 0;
  13423. while (intervalIt != it)
  13424. {
  13425. if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange)
  13426. scatterData->append(intervalIt.value());
  13427. ++c;
  13428. ++intervalIt;
  13429. }
  13430. } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange)
  13431. scatterData->append(currentIntervalStart.value());
  13432. }
  13433. } else // don't use adaptive sampling algorithm, transfer points one-to-one from the map into the output parameters
  13434. {
  13435. QVector<QCPData> *dataVector = 0;
  13436. if (lineData)
  13437. dataVector = lineData;
  13438. else if (scatterData)
  13439. dataVector = scatterData;
  13440. if (dataVector)
  13441. {
  13442. QCPDataMap::const_iterator it = lower;
  13443. QCPDataMap::const_iterator upperEnd = upper+1;
  13444. dataVector->reserve(dataCount+2); // +2 for possible fill end points
  13445. while (it != upperEnd)
  13446. {
  13447. dataVector->append(it.value());
  13448. ++it;
  13449. }
  13450. }
  13451. if (lineData && scatterData)
  13452. *scatterData = *dataVector;
  13453. }
  13454. }
  13455. /*! \internal
  13456. called by the scatter drawing function (\ref drawScatterPlot) to draw the error bars on one data
  13457. point. \a x and \a y pixel positions of the data point are passed since they are already known in
  13458. pixel coordinates in the drawing function, so we save some extra coordToPixel transforms here. \a
  13459. data is therefore only used for the errors, not key and value.
  13460. */
  13461. void QCPGraph::drawError(QCPPainter *painter, double x, double y, const QCPData &data) const
  13462. {
  13463. QCPAxis *keyAxis = mKeyAxis.data();
  13464. QCPAxis *valueAxis = mValueAxis.data();
  13465. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  13466. double a, b; // positions of error bar bounds in pixels
  13467. double barWidthHalf = mErrorBarSize*0.5;
  13468. double skipSymbolMargin = mScatterStyle.size(); // pixels left blank per side, when mErrorBarSkipSymbol is true
  13469. if (keyAxis->orientation() == Qt::Vertical)
  13470. {
  13471. // draw key error vertically and value error horizontally
  13472. if (mErrorType == etKey || mErrorType == etBoth)
  13473. {
  13474. a = keyAxis->coordToPixel(data.key-data.keyErrorMinus);
  13475. b = keyAxis->coordToPixel(data.key+data.keyErrorPlus);
  13476. if (keyAxis->rangeReversed())
  13477. qSwap(a,b);
  13478. // draw spine:
  13479. if (mErrorBarSkipSymbol)
  13480. {
  13481. if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
  13482. painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin));
  13483. if (y-b > skipSymbolMargin)
  13484. painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b));
  13485. } else
  13486. painter->drawLine(QLineF(x, a, x, b));
  13487. // draw handles:
  13488. painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a));
  13489. painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b));
  13490. }
  13491. if (mErrorType == etValue || mErrorType == etBoth)
  13492. {
  13493. a = valueAxis->coordToPixel(data.value-data.valueErrorMinus);
  13494. b = valueAxis->coordToPixel(data.value+data.valueErrorPlus);
  13495. if (valueAxis->rangeReversed())
  13496. qSwap(a,b);
  13497. // draw spine:
  13498. if (mErrorBarSkipSymbol)
  13499. {
  13500. if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
  13501. painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y));
  13502. if (b-x > skipSymbolMargin)
  13503. painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y));
  13504. } else
  13505. painter->drawLine(QLineF(a, y, b, y));
  13506. // draw handles:
  13507. painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf));
  13508. painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf));
  13509. }
  13510. } else // mKeyAxis->orientation() is Qt::Horizontal
  13511. {
  13512. // draw value error vertically and key error horizontally
  13513. if (mErrorType == etKey || mErrorType == etBoth)
  13514. {
  13515. a = keyAxis->coordToPixel(data.key-data.keyErrorMinus);
  13516. b = keyAxis->coordToPixel(data.key+data.keyErrorPlus);
  13517. if (keyAxis->rangeReversed())
  13518. qSwap(a,b);
  13519. // draw spine:
  13520. if (mErrorBarSkipSymbol)
  13521. {
  13522. if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
  13523. painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y));
  13524. if (b-x > skipSymbolMargin)
  13525. painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y));
  13526. } else
  13527. painter->drawLine(QLineF(a, y, b, y));
  13528. // draw handles:
  13529. painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf));
  13530. painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf));
  13531. }
  13532. if (mErrorType == etValue || mErrorType == etBoth)
  13533. {
  13534. a = valueAxis->coordToPixel(data.value-data.valueErrorMinus);
  13535. b = valueAxis->coordToPixel(data.value+data.valueErrorPlus);
  13536. if (valueAxis->rangeReversed())
  13537. qSwap(a,b);
  13538. // draw spine:
  13539. if (mErrorBarSkipSymbol)
  13540. {
  13541. if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
  13542. painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin));
  13543. if (y-b > skipSymbolMargin)
  13544. painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b));
  13545. } else
  13546. painter->drawLine(QLineF(x, a, x, b));
  13547. // draw handles:
  13548. painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a));
  13549. painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b));
  13550. }
  13551. }
  13552. }
  13553. /*! \internal
  13554. called by \ref getPreparedData to determine which data (key) range is visible at the current key
  13555. axis range setting, so only that needs to be processed.
  13556. \a lower returns an iterator to the lowest data point that needs to be taken into account when
  13557. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  13558. lower may still be just outside the visible range.
  13559. \a upper returns an iterator to the highest data point. Same as before, \a upper may also lie
  13560. just outside of the visible range.
  13561. if the graph contains no data, both \a lower and \a upper point to constEnd.
  13562. */
  13563. void QCPGraph::getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMap::const_iterator &upper) const
  13564. {
  13565. if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
  13566. if (mData->isEmpty())
  13567. {
  13568. lower = mData->constEnd();
  13569. upper = mData->constEnd();
  13570. return;
  13571. }
  13572. // get visible data range as QMap iterators
  13573. QCPDataMap::const_iterator lbound = mData->lowerBound(mKeyAxis.data()->range().lower);
  13574. QCPDataMap::const_iterator ubound = mData->upperBound(mKeyAxis.data()->range().upper);
  13575. bool lowoutlier = lbound != mData->constBegin(); // indicates whether there exist points below axis range
  13576. bool highoutlier = ubound != mData->constEnd(); // indicates whether there exist points above axis range
  13577. lower = (lowoutlier ? lbound-1 : lbound); // data point range that will be actually drawn
  13578. upper = (highoutlier ? ubound : ubound-1); // data point range that will be actually drawn
  13579. }
  13580. /*! \internal
  13581. Counts the number of data points between \a lower and \a upper (including them), up to a maximum
  13582. of \a maxCount.
  13583. This function is used by \ref getPreparedData to determine whether adaptive sampling shall be
  13584. used (if enabled via \ref setAdaptiveSampling) or not. This is also why counting of data points
  13585. only needs to be done until \a maxCount is reached, which should be set to the number of data
  13586. points at which adaptive sampling sets in.
  13587. */
  13588. int QCPGraph::countDataInBounds(const QCPDataMap::const_iterator &lower, const QCPDataMap::const_iterator &upper, int maxCount) const
  13589. {
  13590. if (upper == mData->constEnd() && lower == mData->constEnd())
  13591. return 0;
  13592. QCPDataMap::const_iterator it = lower;
  13593. int count = 1;
  13594. while (it != upper && count < maxCount)
  13595. {
  13596. ++it;
  13597. ++count;
  13598. }
  13599. return count;
  13600. }
  13601. /*! \internal
  13602. The line data vector generated by e.g. getLinePlotData contains only the line that connects the
  13603. data points. If the graph needs to be filled, two additional points need to be added at the
  13604. value-zero-line in the lower and upper key positions of the graph. This function calculates these
  13605. points and adds them to the end of \a lineData. Since the fill is typically drawn before the line
  13606. stroke, these added points need to be removed again after the fill is done, with the
  13607. removeFillBasePoints function.
  13608. The expanding of \a lineData by two points will not cause unnecessary memory reallocations,
  13609. because the data vector generation functions (getLinePlotData etc.) reserve two extra points when
  13610. they allocate memory for \a lineData.
  13611. \see removeFillBasePoints, lowerFillBasePoint, upperFillBasePoint
  13612. */
  13613. void QCPGraph::addFillBasePoints(QVector<QPointF> *lineData) const
  13614. {
  13615. if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
  13616. // append points that close the polygon fill at the key axis:
  13617. if (mKeyAxis.data()->orientation() == Qt::Vertical)
  13618. {
  13619. *lineData << upperFillBasePoint(lineData->last().y());
  13620. *lineData << lowerFillBasePoint(lineData->first().y());
  13621. } else
  13622. {
  13623. *lineData << upperFillBasePoint(lineData->last().x());
  13624. *lineData << lowerFillBasePoint(lineData->first().x());
  13625. }
  13626. }
  13627. /*! \internal
  13628. removes the two points from \a lineData that were added by \ref addFillBasePoints.
  13629. \see addFillBasePoints, lowerFillBasePoint, upperFillBasePoint
  13630. */
  13631. void QCPGraph::removeFillBasePoints(QVector<QPointF> *lineData) const
  13632. {
  13633. lineData->remove(lineData->size()-2, 2);
  13634. }
  13635. /*! \internal
  13636. called by \ref addFillBasePoints to conveniently assign the point which closes the fill polygon
  13637. on the lower side of the zero-value-line parallel to the key axis. The logarithmic axis scale
  13638. case is a bit special, since the zero-value-line in pixel coordinates is in positive or negative
  13639. infinity. So this case is handled separately by just closing the fill polygon on the axis which
  13640. lies in the direction towards the zero value.
  13641. \a lowerKey will be the the key (in pixels) of the returned point. Depending on whether the key
  13642. axis is horizontal or vertical, \a lowerKey will end up as the x or y value of the returned
  13643. point, respectively.
  13644. \see upperFillBasePoint, addFillBasePoints
  13645. */
  13646. QPointF QCPGraph::lowerFillBasePoint(double lowerKey) const
  13647. {
  13648. QCPAxis *keyAxis = mKeyAxis.data();
  13649. QCPAxis *valueAxis = mValueAxis.data();
  13650. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
  13651. QPointF point;
  13652. if (valueAxis->scaleType() == QCPAxis::stLinear)
  13653. {
  13654. if (keyAxis->axisType() == QCPAxis::atLeft)
  13655. {
  13656. point.setX(valueAxis->coordToPixel(0));
  13657. point.setY(lowerKey);
  13658. } else if (keyAxis->axisType() == QCPAxis::atRight)
  13659. {
  13660. point.setX(valueAxis->coordToPixel(0));
  13661. point.setY(lowerKey);
  13662. } else if (keyAxis->axisType() == QCPAxis::atTop)
  13663. {
  13664. point.setX(lowerKey);
  13665. point.setY(valueAxis->coordToPixel(0));
  13666. } else if (keyAxis->axisType() == QCPAxis::atBottom)
  13667. {
  13668. point.setX(lowerKey);
  13669. point.setY(valueAxis->coordToPixel(0));
  13670. }
  13671. } else // valueAxis->mScaleType == QCPAxis::stLogarithmic
  13672. {
  13673. // In logarithmic scaling we can't just draw to value zero so we just fill all the way
  13674. // to the axis which is in the direction towards zero
  13675. if (keyAxis->orientation() == Qt::Vertical)
  13676. {
  13677. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
  13678. (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
  13679. point.setX(keyAxis->axisRect()->right());
  13680. else
  13681. point.setX(keyAxis->axisRect()->left());
  13682. point.setY(lowerKey);
  13683. } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom)
  13684. {
  13685. point.setX(lowerKey);
  13686. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
  13687. (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
  13688. point.setY(keyAxis->axisRect()->top());
  13689. else
  13690. point.setY(keyAxis->axisRect()->bottom());
  13691. }
  13692. }
  13693. return point;
  13694. }
  13695. /*! \internal
  13696. called by \ref addFillBasePoints to conveniently assign the point which closes the fill
  13697. polygon on the upper side of the zero-value-line parallel to the key axis. The logarithmic axis
  13698. scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or
  13699. negative infinity. So this case is handled separately by just closing the fill polygon on the
  13700. axis which lies in the direction towards the zero value.
  13701. \a upperKey will be the the key (in pixels) of the returned point. Depending on whether the key
  13702. axis is horizontal or vertical, \a upperKey will end up as the x or y value of the returned
  13703. point, respectively.
  13704. \see lowerFillBasePoint, addFillBasePoints
  13705. */
  13706. QPointF QCPGraph::upperFillBasePoint(double upperKey) const
  13707. {
  13708. QCPAxis *keyAxis = mKeyAxis.data();
  13709. QCPAxis *valueAxis = mValueAxis.data();
  13710. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
  13711. QPointF point;
  13712. if (valueAxis->scaleType() == QCPAxis::stLinear)
  13713. {
  13714. if (keyAxis->axisType() == QCPAxis::atLeft)
  13715. {
  13716. point.setX(valueAxis->coordToPixel(0));
  13717. point.setY(upperKey);
  13718. } else if (keyAxis->axisType() == QCPAxis::atRight)
  13719. {
  13720. point.setX(valueAxis->coordToPixel(0));
  13721. point.setY(upperKey);
  13722. } else if (keyAxis->axisType() == QCPAxis::atTop)
  13723. {
  13724. point.setX(upperKey);
  13725. point.setY(valueAxis->coordToPixel(0));
  13726. } else if (keyAxis->axisType() == QCPAxis::atBottom)
  13727. {
  13728. point.setX(upperKey);
  13729. point.setY(valueAxis->coordToPixel(0));
  13730. }
  13731. } else // valueAxis->mScaleType == QCPAxis::stLogarithmic
  13732. {
  13733. // In logarithmic scaling we can't just draw to value 0 so we just fill all the way
  13734. // to the axis which is in the direction towards 0
  13735. if (keyAxis->orientation() == Qt::Vertical)
  13736. {
  13737. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
  13738. (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
  13739. point.setX(keyAxis->axisRect()->right());
  13740. else
  13741. point.setX(keyAxis->axisRect()->left());
  13742. point.setY(upperKey);
  13743. } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom)
  13744. {
  13745. point.setX(upperKey);
  13746. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
  13747. (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
  13748. point.setY(keyAxis->axisRect()->top());
  13749. else
  13750. point.setY(keyAxis->axisRect()->bottom());
  13751. }
  13752. }
  13753. return point;
  13754. }
  13755. /*! \internal
  13756. Generates the polygon needed for drawing channel fills between this graph (data passed via \a
  13757. lineData) and the graph specified by mChannelFillGraph (data generated by calling its \ref
  13758. getPlotData function). May return an empty polygon if the key ranges have no overlap or fill
  13759. target graph and this graph don't have same orientation (i.e. both key axes horizontal or both
  13760. key axes vertical). For increased performance (due to implicit sharing), keep the returned
  13761. QPolygonF const.
  13762. */
  13763. const QPolygonF QCPGraph::getChannelFillPolygon(const QVector<QPointF> *lineData) const
  13764. {
  13765. if (!mChannelFillGraph)
  13766. return QPolygonF();
  13767. QCPAxis *keyAxis = mKeyAxis.data();
  13768. QCPAxis *valueAxis = mValueAxis.data();
  13769. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); }
  13770. if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); }
  13771. if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation())
  13772. 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)
  13773. if (lineData->isEmpty()) return QPolygonF();
  13774. QVector<QPointF> otherData;
  13775. mChannelFillGraph.data()->getPlotData(&otherData, 0);
  13776. if (otherData.isEmpty()) return QPolygonF();
  13777. QVector<QPointF> thisData;
  13778. thisData.reserve(lineData->size()+otherData.size()); // because we will join both vectors at end of this function
  13779. for (int i=0; i<lineData->size(); ++i) // don't use the vector<<(vector), it squeezes internally, which ruins the performance tuning with reserve()
  13780. thisData << lineData->at(i);
  13781. // pointers to be able to swap them, depending which data range needs cropping:
  13782. QVector<QPointF> *staticData = &thisData;
  13783. QVector<QPointF> *croppedData = &otherData;
  13784. // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType):
  13785. if (keyAxis->orientation() == Qt::Horizontal)
  13786. {
  13787. // x is key
  13788. // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys:
  13789. if (staticData->first().x() > staticData->last().x())
  13790. {
  13791. int size = staticData->size();
  13792. for (int i=0; i<size/2; ++i)
  13793. qSwap((*staticData)[i], (*staticData)[size-1-i]);
  13794. }
  13795. if (croppedData->first().x() > croppedData->last().x())
  13796. {
  13797. int size = croppedData->size();
  13798. for (int i=0; i<size/2; ++i)
  13799. qSwap((*croppedData)[i], (*croppedData)[size-1-i]);
  13800. }
  13801. // crop lower bound:
  13802. if (staticData->first().x() < croppedData->first().x()) // other one must be cropped
  13803. qSwap(staticData, croppedData);
  13804. int lowBound = findIndexBelowX(croppedData, staticData->first().x());
  13805. if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
  13806. croppedData->remove(0, lowBound);
  13807. // set lowest point of cropped data to fit exactly key position of first static data
  13808. // point via linear interpolation:
  13809. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  13810. double slope;
  13811. if (croppedData->at(1).x()-croppedData->at(0).x() != 0)
  13812. slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x());
  13813. else
  13814. slope = 0;
  13815. (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x()));
  13816. (*croppedData)[0].setX(staticData->first().x());
  13817. // crop upper bound:
  13818. if (staticData->last().x() > croppedData->last().x()) // other one must be cropped
  13819. qSwap(staticData, croppedData);
  13820. int highBound = findIndexAboveX(croppedData, staticData->last().x());
  13821. if (highBound == -1) return QPolygonF(); // key ranges have no overlap
  13822. croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
  13823. // set highest point of cropped data to fit exactly key position of last static data
  13824. // point via linear interpolation:
  13825. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  13826. int li = croppedData->size()-1; // last index
  13827. if (croppedData->at(li).x()-croppedData->at(li-1).x() != 0)
  13828. slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x());
  13829. else
  13830. slope = 0;
  13831. (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x()));
  13832. (*croppedData)[li].setX(staticData->last().x());
  13833. } else // mKeyAxis->orientation() == Qt::Vertical
  13834. {
  13835. // y is key
  13836. // similar to "x is key" but switched x,y. Further, lower/upper meaning is inverted compared to x,
  13837. // because in pixel coordinates, y increases from top to bottom, not bottom to top like data coordinate.
  13838. // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys:
  13839. if (staticData->first().y() < staticData->last().y())
  13840. {
  13841. int size = staticData->size();
  13842. for (int i=0; i<size/2; ++i)
  13843. qSwap((*staticData)[i], (*staticData)[size-1-i]);
  13844. }
  13845. if (croppedData->first().y() < croppedData->last().y())
  13846. {
  13847. int size = croppedData->size();
  13848. for (int i=0; i<size/2; ++i)
  13849. qSwap((*croppedData)[i], (*croppedData)[size-1-i]);
  13850. }
  13851. // crop lower bound:
  13852. if (staticData->first().y() > croppedData->first().y()) // other one must be cropped
  13853. qSwap(staticData, croppedData);
  13854. int lowBound = findIndexAboveY(croppedData, staticData->first().y());
  13855. if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
  13856. croppedData->remove(0, lowBound);
  13857. // set lowest point of cropped data to fit exactly key position of first static data
  13858. // point via linear interpolation:
  13859. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  13860. double slope;
  13861. if (croppedData->at(1).y()-croppedData->at(0).y() != 0) // avoid division by zero in step plots
  13862. slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y());
  13863. else
  13864. slope = 0;
  13865. (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y()));
  13866. (*croppedData)[0].setY(staticData->first().y());
  13867. // crop upper bound:
  13868. if (staticData->last().y() < croppedData->last().y()) // other one must be cropped
  13869. qSwap(staticData, croppedData);
  13870. int highBound = findIndexBelowY(croppedData, staticData->last().y());
  13871. if (highBound == -1) return QPolygonF(); // key ranges have no overlap
  13872. croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
  13873. // set highest point of cropped data to fit exactly key position of last static data
  13874. // point via linear interpolation:
  13875. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  13876. int li = croppedData->size()-1; // last index
  13877. if (croppedData->at(li).y()-croppedData->at(li-1).y() != 0) // avoid division by zero in step plots
  13878. slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y());
  13879. else
  13880. slope = 0;
  13881. (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y()));
  13882. (*croppedData)[li].setY(staticData->last().y());
  13883. }
  13884. // return joined:
  13885. for (int i=otherData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted
  13886. thisData << otherData.at(i);
  13887. return QPolygonF(thisData);
  13888. }
  13889. /*! \internal
  13890. Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in
  13891. \a data points are ordered ascending, as is the case when plotting with horizontal key axis.
  13892. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  13893. */
  13894. int QCPGraph::findIndexAboveX(const QVector<QPointF> *data, double x) const
  13895. {
  13896. for (int i=data->size()-1; i>=0; --i)
  13897. {
  13898. if (data->at(i).x() < x)
  13899. {
  13900. if (i<data->size()-1)
  13901. return i+1;
  13902. else
  13903. return data->size()-1;
  13904. }
  13905. }
  13906. return -1;
  13907. }
  13908. /*! \internal
  13909. Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in
  13910. \a data points are ordered ascending, as is the case when plotting with horizontal key axis.
  13911. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  13912. */
  13913. int QCPGraph::findIndexBelowX(const QVector<QPointF> *data, double x) const
  13914. {
  13915. for (int i=0; i<data->size(); ++i)
  13916. {
  13917. if (data->at(i).x() > x)
  13918. {
  13919. if (i>0)
  13920. return i-1;
  13921. else
  13922. return 0;
  13923. }
  13924. }
  13925. return -1;
  13926. }
  13927. /*! \internal
  13928. Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in
  13929. \a data points are ordered descending, as is the case when plotting with vertical key axis.
  13930. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  13931. */
  13932. int QCPGraph::findIndexAboveY(const QVector<QPointF> *data, double y) const
  13933. {
  13934. for (int i=0; i<data->size(); ++i)
  13935. {
  13936. if (data->at(i).y() < y)
  13937. {
  13938. if (i>0)
  13939. return i-1;
  13940. else
  13941. return 0;
  13942. }
  13943. }
  13944. return -1;
  13945. }
  13946. /*! \internal
  13947. Calculates the (minimum) distance (in pixels) the graph's representation has from the given \a
  13948. pixelPoint in pixels. This is used to determine whether the graph was clicked or not, e.g. in
  13949. \ref selectTest.
  13950. If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape
  13951. is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns
  13952. 500.
  13953. */
  13954. double QCPGraph::pointDistance(const QPointF &pixelPoint) const
  13955. {
  13956. if (mData->isEmpty())
  13957. {
  13958. qDebug() << Q_FUNC_INFO << "requested point distance on graph" << mName << "without data";
  13959. return 500;
  13960. }
  13961. if (mData->size() == 1)
  13962. {
  13963. QPointF dataPoint = coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value);
  13964. return QVector2D(dataPoint-pixelPoint).length();
  13965. }
  13966. if (mLineStyle == lsNone && mScatterStyle.isNone())
  13967. return 500;
  13968. // calculate minimum distances to graph representation:
  13969. if (mLineStyle == lsNone)
  13970. {
  13971. // no line displayed, only calculate distance to scatter points:
  13972. QVector<QCPData> *scatterData = new QVector<QCPData>;
  13973. getScatterPlotData(scatterData);
  13974. double minDistSqr = std::numeric_limits<double>::max();
  13975. QPointF ptA;
  13976. QPointF ptB = coordsToPixels(scatterData->at(0).key, scatterData->at(0).value); // getScatterPlotData returns in plot coordinates, so transform to pixels
  13977. for (int i=1; i<scatterData->size(); ++i)
  13978. {
  13979. ptA = ptB;
  13980. ptB = coordsToPixels(scatterData->at(i).key, scatterData->at(i).value);
  13981. double currentDistSqr = distSqrToLine(ptA, ptB, pixelPoint);
  13982. if (currentDistSqr < minDistSqr)
  13983. minDistSqr = currentDistSqr;
  13984. }
  13985. delete scatterData;
  13986. return sqrt(minDistSqr);
  13987. } else
  13988. {
  13989. // line displayed calculate distance to line segments:
  13990. QVector<QPointF> *lineData = new QVector<QPointF>;
  13991. getPlotData(lineData, 0); // unlike with getScatterPlotData we get pixel coordinates here
  13992. double minDistSqr = std::numeric_limits<double>::max();
  13993. if (mLineStyle == lsImpulse)
  13994. {
  13995. // impulse plot differs from other line styles in that the lineData points are only pairwise connected:
  13996. for (int i=0; i<lineData->size()-1; i+=2) // iterate pairs
  13997. {
  13998. double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint);
  13999. if (currentDistSqr < minDistSqr)
  14000. minDistSqr = currentDistSqr;
  14001. }
  14002. } else
  14003. {
  14004. // all other line plots (line and step) connect points directly:
  14005. for (int i=0; i<lineData->size()-1; ++i)
  14006. {
  14007. double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint);
  14008. if (currentDistSqr < minDistSqr)
  14009. minDistSqr = currentDistSqr;
  14010. }
  14011. }
  14012. delete lineData;
  14013. return sqrt(minDistSqr);
  14014. }
  14015. }
  14016. /*! \internal
  14017. Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in
  14018. \a data points are ordered descending, as is the case when plotting with vertical key axis (since
  14019. keys are ordered ascending).
  14020. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  14021. */
  14022. int QCPGraph::findIndexBelowY(const QVector<QPointF> *data, double y) const
  14023. {
  14024. for (int i=data->size()-1; i>=0; --i)
  14025. {
  14026. if (data->at(i).y() > y)
  14027. {
  14028. if (i<data->size()-1)
  14029. return i+1;
  14030. else
  14031. return data->size()-1;
  14032. }
  14033. }
  14034. return -1;
  14035. }
  14036. /* inherits documentation from base class */
  14037. QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain) const
  14038. {
  14039. // just call the specialized version which takes an additional argument whether error bars
  14040. // should also be taken into consideration for range calculation. We set this to true here.
  14041. return getKeyRange(foundRange, inSignDomain, true);
  14042. }
  14043. /* inherits documentation from base class */
  14044. QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain) const
  14045. {
  14046. // just call the specialized version which takes an additional argument whether error bars
  14047. // should also be taken into consideration for range calculation. We set this to true here.
  14048. return getValueRange(foundRange, inSignDomain, true);
  14049. }
  14050. /*! \overload
  14051. Allows to specify whether the error bars should be included in the range calculation.
  14052. \see getKeyRange(bool &foundRange, SignDomain inSignDomain)
  14053. */
  14054. QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const
  14055. {
  14056. QCPRange range;
  14057. bool haveLower = false;
  14058. bool haveUpper = false;
  14059. double current, currentErrorMinus, currentErrorPlus;
  14060. if (inSignDomain == sdBoth) // range may be anywhere
  14061. {
  14062. QCPDataMap::const_iterator it = mData->constBegin();
  14063. while (it != mData->constEnd())
  14064. {
  14065. current = it.value().key;
  14066. currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0);
  14067. currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0);
  14068. if (current-currentErrorMinus < range.lower || !haveLower)
  14069. {
  14070. range.lower = current-currentErrorMinus;
  14071. haveLower = true;
  14072. }
  14073. if (current+currentErrorPlus > range.upper || !haveUpper)
  14074. {
  14075. range.upper = current+currentErrorPlus;
  14076. haveUpper = true;
  14077. }
  14078. ++it;
  14079. }
  14080. } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain
  14081. {
  14082. QCPDataMap::const_iterator it = mData->constBegin();
  14083. while (it != mData->constEnd())
  14084. {
  14085. current = it.value().key;
  14086. currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0);
  14087. currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0);
  14088. if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0)
  14089. {
  14090. range.lower = current-currentErrorMinus;
  14091. haveLower = true;
  14092. }
  14093. if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0)
  14094. {
  14095. range.upper = current+currentErrorPlus;
  14096. haveUpper = true;
  14097. }
  14098. if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point.
  14099. {
  14100. if ((current < range.lower || !haveLower) && current < 0)
  14101. {
  14102. range.lower = current;
  14103. haveLower = true;
  14104. }
  14105. if ((current > range.upper || !haveUpper) && current < 0)
  14106. {
  14107. range.upper = current;
  14108. haveUpper = true;
  14109. }
  14110. }
  14111. ++it;
  14112. }
  14113. } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain
  14114. {
  14115. QCPDataMap::const_iterator it = mData->constBegin();
  14116. while (it != mData->constEnd())
  14117. {
  14118. current = it.value().key;
  14119. currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0);
  14120. currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0);
  14121. if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0)
  14122. {
  14123. range.lower = current-currentErrorMinus;
  14124. haveLower = true;
  14125. }
  14126. if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0)
  14127. {
  14128. range.upper = current+currentErrorPlus;
  14129. haveUpper = true;
  14130. }
  14131. if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point.
  14132. {
  14133. if ((current < range.lower || !haveLower) && current > 0)
  14134. {
  14135. range.lower = current;
  14136. haveLower = true;
  14137. }
  14138. if ((current > range.upper || !haveUpper) && current > 0)
  14139. {
  14140. range.upper = current;
  14141. haveUpper = true;
  14142. }
  14143. }
  14144. ++it;
  14145. }
  14146. }
  14147. foundRange = haveLower && haveUpper;
  14148. return range;
  14149. }
  14150. /*! \overload
  14151. Allows to specify whether the error bars should be included in the range calculation.
  14152. \see getValueRange(bool &foundRange, SignDomain inSignDomain)
  14153. */
  14154. QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const
  14155. {
  14156. QCPRange range;
  14157. bool haveLower = false;
  14158. bool haveUpper = false;
  14159. double current, currentErrorMinus, currentErrorPlus;
  14160. if (inSignDomain == sdBoth) // range may be anywhere
  14161. {
  14162. QCPDataMap::const_iterator it = mData->constBegin();
  14163. while (it != mData->constEnd())
  14164. {
  14165. current = it.value().value;
  14166. currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0);
  14167. currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0);
  14168. if (current-currentErrorMinus < range.lower || !haveLower)
  14169. {
  14170. range.lower = current-currentErrorMinus;
  14171. haveLower = true;
  14172. }
  14173. if (current+currentErrorPlus > range.upper || !haveUpper)
  14174. {
  14175. range.upper = current+currentErrorPlus;
  14176. haveUpper = true;
  14177. }
  14178. ++it;
  14179. }
  14180. } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain
  14181. {
  14182. QCPDataMap::const_iterator it = mData->constBegin();
  14183. while (it != mData->constEnd())
  14184. {
  14185. current = it.value().value;
  14186. currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0);
  14187. currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0);
  14188. if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0)
  14189. {
  14190. range.lower = current-currentErrorMinus;
  14191. haveLower = true;
  14192. }
  14193. if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0)
  14194. {
  14195. range.upper = current+currentErrorPlus;
  14196. haveUpper = true;
  14197. }
  14198. if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point.
  14199. {
  14200. if ((current < range.lower || !haveLower) && current < 0)
  14201. {
  14202. range.lower = current;
  14203. haveLower = true;
  14204. }
  14205. if ((current > range.upper || !haveUpper) && current < 0)
  14206. {
  14207. range.upper = current;
  14208. haveUpper = true;
  14209. }
  14210. }
  14211. ++it;
  14212. }
  14213. } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain
  14214. {
  14215. QCPDataMap::const_iterator it = mData->constBegin();
  14216. while (it != mData->constEnd())
  14217. {
  14218. current = it.value().value;
  14219. currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0);
  14220. currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0);
  14221. if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0)
  14222. {
  14223. range.lower = current-currentErrorMinus;
  14224. haveLower = true;
  14225. }
  14226. if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0)
  14227. {
  14228. range.upper = current+currentErrorPlus;
  14229. haveUpper = true;
  14230. }
  14231. if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point.
  14232. {
  14233. if ((current < range.lower || !haveLower) && current > 0)
  14234. {
  14235. range.lower = current;
  14236. haveLower = true;
  14237. }
  14238. if ((current > range.upper || !haveUpper) && current > 0)
  14239. {
  14240. range.upper = current;
  14241. haveUpper = true;
  14242. }
  14243. }
  14244. ++it;
  14245. }
  14246. }
  14247. foundRange = haveLower && haveUpper;
  14248. return range;
  14249. }
  14250. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14251. //////////////////// QCPCurveData
  14252. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14253. /*! \class QCPCurveData
  14254. \brief Holds the data of one single data point for QCPCurve.
  14255. The container for storing multiple data points is \ref QCPCurveDataMap.
  14256. The stored data is:
  14257. \li \a t: the free parameter of the curve at this curve point (cp. the mathematical vector <em>(x(t), y(t))</em>)
  14258. \li \a key: coordinate on the key axis of this curve point
  14259. \li \a value: coordinate on the value axis of this curve point
  14260. \see QCPCurveDataMap
  14261. */
  14262. /*!
  14263. Constructs a curve data point with t, key and value set to zero.
  14264. */
  14265. QCPCurveData::QCPCurveData() :
  14266. t(0),
  14267. key(0),
  14268. value(0)
  14269. {
  14270. }
  14271. /*!
  14272. Constructs a curve data point with the specified \a t, \a key and \a value.
  14273. */
  14274. QCPCurveData::QCPCurveData(double t, double key, double value) :
  14275. t(t),
  14276. key(key),
  14277. value(value)
  14278. {
  14279. }
  14280. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14281. //////////////////// QCPCurve
  14282. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14283. /*! \class QCPCurve
  14284. \brief A plottable representing a parametric curve in a plot.
  14285. \image html QCPCurve.png
  14286. Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate,
  14287. so their visual representation can have \a loops. This is realized by introducing a third
  14288. coordinate \a t, which defines the order of the points described by the other two coordinates \a
  14289. x and \a y.
  14290. To plot data, assign it with the \ref setData or \ref addData functions.
  14291. \section appearance Changing the appearance
  14292. The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush).
  14293. \section usage Usage
  14294. Like all data representing objects in QCustomPlot, the QCPCurve is a plottable (QCPAbstractPlottable). So
  14295. the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.)
  14296. Usually, you first create an instance:
  14297. \code
  14298. QCPCurve *newCurve = new QCPCurve(customPlot->xAxis, customPlot->yAxis);\endcode
  14299. add it to the customPlot with QCustomPlot::addPlottable:
  14300. \code
  14301. customPlot->addPlottable(newCurve);\endcode
  14302. and then modify the properties of the newly created plottable, e.g.:
  14303. \code
  14304. newCurve->setName("Fermat's Spiral");
  14305. newCurve->setData(tData, xData, yData);\endcode
  14306. */
  14307. /*!
  14308. Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  14309. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  14310. the same orientation. If either of these restrictions is violated, a corresponding message is
  14311. printed to the debug output (qDebug), the construction is not aborted, though.
  14312. The constructed QCPCurve can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
  14313. then takes ownership of the graph.
  14314. */
  14315. QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  14316. QCPAbstractPlottable(keyAxis, valueAxis)
  14317. {
  14318. mData = new QCPCurveDataMap;
  14319. mPen.setColor(Qt::blue);
  14320. mPen.setStyle(Qt::SolidLine);
  14321. mBrush.setColor(Qt::blue);
  14322. mBrush.setStyle(Qt::NoBrush);
  14323. mSelectedPen = mPen;
  14324. mSelectedPen.setWidthF(2.5);
  14325. mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen
  14326. mSelectedBrush = mBrush;
  14327. setScatterStyle(QCPScatterStyle());
  14328. setLineStyle(lsLine);
  14329. }
  14330. QCPCurve::~QCPCurve()
  14331. {
  14332. delete mData;
  14333. }
  14334. /*!
  14335. Replaces the current data with the provided \a data.
  14336. If \a copy is set to true, data points in \a data will only be copied. if false, the plottable
  14337. takes ownership of the passed data and replaces the internal data pointer with it. This is
  14338. significantly faster than copying for large datasets.
  14339. */
  14340. void QCPCurve::setData(QCPCurveDataMap *data, bool copy)
  14341. {
  14342. if (copy)
  14343. {
  14344. *mData = *data;
  14345. } else
  14346. {
  14347. delete mData;
  14348. mData = data;
  14349. }
  14350. }
  14351. /*! \overload
  14352. Replaces the current data with the provided points in \a t, \a key and \a value tuples. The
  14353. provided vectors should have equal length. Else, the number of added points will be the size of
  14354. the smallest vector.
  14355. */
  14356. void QCPCurve::setData(const QVector<double> &t, const QVector<double> &key, const QVector<double> &value)
  14357. {
  14358. mData->clear();
  14359. int n = t.size();
  14360. n = qMin(n, key.size());
  14361. n = qMin(n, value.size());
  14362. QCPCurveData newData;
  14363. for (int i=0; i<n; ++i)
  14364. {
  14365. newData.t = t[i];
  14366. newData.key = key[i];
  14367. newData.value = value[i];
  14368. mData->insertMulti(newData.t, newData);
  14369. }
  14370. }
  14371. /*! \overload
  14372. Replaces the current data with the provided \a key and \a value pairs. The t parameter
  14373. of each data point will be set to the integer index of the respective key/value pair.
  14374. */
  14375. void QCPCurve::setData(const QVector<double> &key, const QVector<double> &value)
  14376. {
  14377. mData->clear();
  14378. int n = key.size();
  14379. n = qMin(n, value.size());
  14380. QCPCurveData newData;
  14381. for (int i=0; i<n; ++i)
  14382. {
  14383. newData.t = i; // no t vector given, so we assign t the index of the key/value pair
  14384. newData.key = key[i];
  14385. newData.value = value[i];
  14386. mData->insertMulti(newData.t, newData);
  14387. }
  14388. }
  14389. /*!
  14390. Sets the visual appearance of single data points in the plot. If set to \ref
  14391. QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate
  14392. line style).
  14393. \see QCPScatterStyle, setLineStyle
  14394. */
  14395. void QCPCurve::setScatterStyle(const QCPScatterStyle &style)
  14396. {
  14397. mScatterStyle = style;
  14398. }
  14399. /*!
  14400. Sets how the single data points are connected in the plot or how they are represented visually
  14401. apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref
  14402. setScatterStyle to the desired scatter style.
  14403. \see setScatterStyle
  14404. */
  14405. void QCPCurve::setLineStyle(QCPCurve::LineStyle style)
  14406. {
  14407. mLineStyle = style;
  14408. }
  14409. /*!
  14410. Adds the provided data points in \a dataMap to the current data.
  14411. \see removeData
  14412. */
  14413. void QCPCurve::addData(const QCPCurveDataMap &dataMap)
  14414. {
  14415. mData->unite(dataMap);
  14416. }
  14417. /*! \overload
  14418. Adds the provided single data point in \a data to the current data.
  14419. \see removeData
  14420. */
  14421. void QCPCurve::addData(const QCPCurveData &data)
  14422. {
  14423. mData->insertMulti(data.t, data);
  14424. }
  14425. /*! \overload
  14426. Adds the provided single data point as \a t, \a key and \a value tuple to the current data
  14427. \see removeData
  14428. */
  14429. void QCPCurve::addData(double t, double key, double value)
  14430. {
  14431. QCPCurveData newData;
  14432. newData.t = t;
  14433. newData.key = key;
  14434. newData.value = value;
  14435. mData->insertMulti(newData.t, newData);
  14436. }
  14437. /*! \overload
  14438. Adds the provided single data point as \a key and \a value pair to the current data The t
  14439. parameter of the data point is set to the t of the last data point plus 1. If there is no last
  14440. data point, t will be set to 0.
  14441. \see removeData
  14442. */
  14443. void QCPCurve::addData(double key, double value)
  14444. {
  14445. QCPCurveData newData;
  14446. if (!mData->isEmpty())
  14447. newData.t = (mData->constEnd()-1).key()+1;
  14448. else
  14449. newData.t = 0;
  14450. newData.key = key;
  14451. newData.value = value;
  14452. mData->insertMulti(newData.t, newData);
  14453. }
  14454. /*! \overload
  14455. Adds the provided data points as \a t, \a key and \a value tuples to the current data.
  14456. \see removeData
  14457. */
  14458. void QCPCurve::addData(const QVector<double> &ts, const QVector<double> &keys, const QVector<double> &values)
  14459. {
  14460. int n = ts.size();
  14461. n = qMin(n, keys.size());
  14462. n = qMin(n, values.size());
  14463. QCPCurveData newData;
  14464. for (int i=0; i<n; ++i)
  14465. {
  14466. newData.t = ts[i];
  14467. newData.key = keys[i];
  14468. newData.value = values[i];
  14469. mData->insertMulti(newData.t, newData);
  14470. }
  14471. }
  14472. /*!
  14473. Removes all data points with curve parameter t smaller than \a t.
  14474. \see addData, clearData
  14475. */
  14476. void QCPCurve::removeDataBefore(double t)
  14477. {
  14478. QCPCurveDataMap::iterator it = mData->begin();
  14479. while (it != mData->end() && it.key() < t)
  14480. it = mData->erase(it);
  14481. }
  14482. /*!
  14483. Removes all data points with curve parameter t greater than \a t.
  14484. \see addData, clearData
  14485. */
  14486. void QCPCurve::removeDataAfter(double t)
  14487. {
  14488. if (mData->isEmpty()) return;
  14489. QCPCurveDataMap::iterator it = mData->upperBound(t);
  14490. while (it != mData->end())
  14491. it = mData->erase(it);
  14492. }
  14493. /*!
  14494. Removes all data points with curve parameter t between \a fromt and \a tot. if \a fromt is
  14495. greater or equal to \a tot, the function does nothing. To remove a single data point with known
  14496. t, use \ref removeData(double t).
  14497. \see addData, clearData
  14498. */
  14499. void QCPCurve::removeData(double fromt, double tot)
  14500. {
  14501. if (fromt >= tot || mData->isEmpty()) return;
  14502. QCPCurveDataMap::iterator it = mData->upperBound(fromt);
  14503. QCPCurveDataMap::iterator itEnd = mData->upperBound(tot);
  14504. while (it != itEnd)
  14505. it = mData->erase(it);
  14506. }
  14507. /*! \overload
  14508. Removes a single data point at curve parameter \a t. If the position is not known with absolute
  14509. precision, consider using \ref removeData(double fromt, double tot) with a small fuzziness
  14510. interval around the suspected position, depeding on the precision with which the curve parameter
  14511. is known.
  14512. \see addData, clearData
  14513. */
  14514. void QCPCurve::removeData(double t)
  14515. {
  14516. mData->remove(t);
  14517. }
  14518. /*!
  14519. Removes all data points.
  14520. \see removeData, removeDataAfter, removeDataBefore
  14521. */
  14522. void QCPCurve::clearData()
  14523. {
  14524. mData->clear();
  14525. }
  14526. /* inherits documentation from base class */
  14527. double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  14528. {
  14529. Q_UNUSED(details)
  14530. if ((onlySelectable && !mSelectable) || mData->isEmpty())
  14531. return -1;
  14532. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  14533. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
  14534. return pointDistance(pos);
  14535. else
  14536. return -1;
  14537. }
  14538. /* inherits documentation from base class */
  14539. void QCPCurve::draw(QCPPainter *painter)
  14540. {
  14541. if (mData->isEmpty()) return;
  14542. // allocate line vector:
  14543. QVector<QPointF> *lineData = new QVector<QPointF>;
  14544. // fill with curve data:
  14545. getCurveData(lineData);
  14546. // check data validity if flag set:
  14547. #ifdef QCUSTOMPLOT_CHECK_DATA
  14548. QCPCurveDataMap::const_iterator it;
  14549. for (it = mData->constBegin(); it != mData->constEnd(); ++it)
  14550. {
  14551. if (QCP::isInvalidData(it.value().t) ||
  14552. QCP::isInvalidData(it.value().key, it.value().value))
  14553. qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name();
  14554. }
  14555. #endif
  14556. // draw curve fill:
  14557. if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0)
  14558. {
  14559. applyFillAntialiasingHint(painter);
  14560. painter->setPen(Qt::NoPen);
  14561. painter->setBrush(mainBrush());
  14562. painter->drawPolygon(QPolygonF(*lineData));
  14563. }
  14564. // draw curve line:
  14565. if (mLineStyle != lsNone && mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)
  14566. {
  14567. applyDefaultAntialiasingHint(painter);
  14568. painter->setPen(mainPen());
  14569. painter->setBrush(Qt::NoBrush);
  14570. // if drawing solid line and not in PDF, use much faster line drawing instead of polyline:
  14571. if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) &&
  14572. painter->pen().style() == Qt::SolidLine &&
  14573. !painter->modes().testFlag(QCPPainter::pmVectorized) &&
  14574. !painter->modes().testFlag(QCPPainter::pmNoCaching))
  14575. {
  14576. for (int i=1; i<lineData->size(); ++i)
  14577. painter->drawLine(lineData->at(i-1), lineData->at(i));
  14578. } else
  14579. {
  14580. painter->drawPolyline(QPolygonF(*lineData));
  14581. }
  14582. }
  14583. // draw scatters:
  14584. if (!mScatterStyle.isNone())
  14585. drawScatterPlot(painter, lineData);
  14586. // free allocated line data:
  14587. delete lineData;
  14588. }
  14589. /* inherits documentation from base class */
  14590. void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  14591. {
  14592. // draw fill:
  14593. if (mBrush.style() != Qt::NoBrush)
  14594. {
  14595. applyFillAntialiasingHint(painter);
  14596. painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
  14597. }
  14598. // draw line vertically centered:
  14599. if (mLineStyle != lsNone)
  14600. {
  14601. applyDefaultAntialiasingHint(painter);
  14602. painter->setPen(mPen);
  14603. 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
  14604. }
  14605. // draw scatter symbol:
  14606. if (!mScatterStyle.isNone())
  14607. {
  14608. applyScattersAntialiasingHint(painter);
  14609. // scale scatter pixmap if it's too large to fit in legend icon rect:
  14610. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
  14611. {
  14612. QCPScatterStyle scaledStyle(mScatterStyle);
  14613. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  14614. scaledStyle.applyTo(painter, mPen);
  14615. scaledStyle.drawShape(painter, QRectF(rect).center());
  14616. } else
  14617. {
  14618. mScatterStyle.applyTo(painter, mPen);
  14619. mScatterStyle.drawShape(painter, QRectF(rect).center());
  14620. }
  14621. }
  14622. }
  14623. /*! \internal
  14624. Draws scatter symbols at every data point passed in \a pointData. scatter symbols are independent of
  14625. the line style and are always drawn if scatter shape is not \ref QCPScatterStyle::ssNone.
  14626. */
  14627. void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> *pointData) const
  14628. {
  14629. // draw scatter point symbols:
  14630. applyScattersAntialiasingHint(painter);
  14631. mScatterStyle.applyTo(painter, mPen);
  14632. for (int i=0; i<pointData->size(); ++i)
  14633. mScatterStyle.drawShape(painter, pointData->at(i));
  14634. }
  14635. /*! \internal
  14636. called by QCPCurve::draw to generate a point vector (pixels) which represents the line of the
  14637. curve. Line segments that aren't visible in the current axis rect are handled in an optimized
  14638. way.
  14639. */
  14640. void QCPCurve::getCurveData(QVector<QPointF> *lineData) const
  14641. {
  14642. /* Extended sides of axis rect R divide space into 9 regions:
  14643. 1__|_4_|__7
  14644. 2__|_R_|__8
  14645. 3 | 6 | 9
  14646. 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.
  14647. Curves outside R become straight lines closely outside of R which greatly reduces drawing time, yet keeps the look of lines and
  14648. fills inside R consistent.
  14649. The region R has index 5.
  14650. */
  14651. QCPAxis *keyAxis = mKeyAxis.data();
  14652. QCPAxis *valueAxis = mValueAxis.data();
  14653. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  14654. QRect axisRect = mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect();
  14655. lineData->reserve(mData->size());
  14656. QCPCurveDataMap::const_iterator it;
  14657. int lastRegion = 5;
  14658. int currentRegion = 5;
  14659. double RLeft = keyAxis->range().lower;
  14660. double RRight = keyAxis->range().upper;
  14661. double RBottom = valueAxis->range().lower;
  14662. double RTop = valueAxis->range().upper;
  14663. double x, y; // current key/value
  14664. bool addedLastAlready = true;
  14665. bool firstPoint = true; // first point must always be drawn, to make sure fill works correctly
  14666. for (it = mData->constBegin(); it != mData->constEnd(); ++it)
  14667. {
  14668. x = it.value().key;
  14669. y = it.value().value;
  14670. // determine current region:
  14671. if (x < RLeft) // region 123
  14672. {
  14673. if (y > RTop)
  14674. currentRegion = 1;
  14675. else if (y < RBottom)
  14676. currentRegion = 3;
  14677. else
  14678. currentRegion = 2;
  14679. } else if (x > RRight) // region 789
  14680. {
  14681. if (y > RTop)
  14682. currentRegion = 7;
  14683. else if (y < RBottom)
  14684. currentRegion = 9;
  14685. else
  14686. currentRegion = 8;
  14687. } else // region 456
  14688. {
  14689. if (y > RTop)
  14690. currentRegion = 4;
  14691. else if (y < RBottom)
  14692. currentRegion = 6;
  14693. else
  14694. currentRegion = 5;
  14695. }
  14696. /*
  14697. Watch out, the next part is very tricky. It modifies the curve such that it seems like the
  14698. whole thing is still drawn, but actually the points outside the axisRect are simplified
  14699. ("optimized") greatly. There are some subtle special cases when line segments are large and
  14700. thereby each subsequent point may be in a different region or even skip some.
  14701. */
  14702. // determine whether to keep current point:
  14703. if (currentRegion == 5 || (firstPoint && mBrush.style() != Qt::NoBrush)) // current is in R, add current and last if it wasn't added already
  14704. {
  14705. if (!addedLastAlready) // in case curve just entered R, make sure the last point outside R is also drawn correctly
  14706. lineData->append(coordsToPixels((it-1).value().key, (it-1).value().value)); // add last point to vector
  14707. 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)
  14708. {
  14709. if (!firstPoint) // because on firstPoint, currentRegion is 5 and addedLastAlready is true, although there is no last point
  14710. lineData->replace(lineData->size()-1, coordsToPixels((it-1).value().key, (it-1).value().value));
  14711. }
  14712. lineData->append(coordsToPixels(it.value().key, it.value().value)); // add current point to vector
  14713. addedLastAlready = true; // so in next iteration, we don't add this point twice
  14714. } else if (currentRegion != lastRegion) // changed region, add current and last if not added already
  14715. {
  14716. // using outsideCoordsToPixels instead of coorsToPixels for optimized point placement (places points just outside axisRect instead of potentially far away)
  14717. // 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
  14718. if (lastRegion == 5 || // coming from R
  14719. ((lastRegion==2 && currentRegion==4) || (lastRegion==4 && currentRegion==2)) || // skip top left diagonal
  14720. ((lastRegion==4 && currentRegion==8) || (lastRegion==8 && currentRegion==4)) || // skip top right diagonal
  14721. ((lastRegion==8 && currentRegion==6) || (lastRegion==6 && currentRegion==8)) || // skip bottom right diagonal
  14722. ((lastRegion==6 && currentRegion==2) || (lastRegion==2 && currentRegion==6)) // skip bottom left diagonal
  14723. )
  14724. {
  14725. // always add last point if not added already, original:
  14726. if (!addedLastAlready)
  14727. lineData->append(coordsToPixels((it-1).value().key, (it-1).value().value));
  14728. // add current point, original:
  14729. lineData->append(coordsToPixels(it.value().key, it.value().value));
  14730. } else // no special case that forbids optimized point placement, so do it:
  14731. {
  14732. // always add last point if not added already, optimized:
  14733. if (!addedLastAlready)
  14734. lineData->append(outsideCoordsToPixels((it-1).value().key, (it-1).value().value, currentRegion, axisRect));
  14735. // add current point, optimized:
  14736. lineData->append(outsideCoordsToPixels(it.value().key, it.value().value, currentRegion, axisRect));
  14737. }
  14738. addedLastAlready = true; // so that if next point enters 5, or crosses another region boundary, we don't add this point twice
  14739. } else // neither in R, nor crossed a region boundary, skip current point
  14740. {
  14741. addedLastAlready = false;
  14742. }
  14743. lastRegion = currentRegion;
  14744. firstPoint = false;
  14745. }
  14746. // 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:
  14747. if (lastRegion != 5 && mBrush.style() != Qt::NoBrush && !mData->isEmpty())
  14748. lineData->append(coordsToPixels((mData->constEnd()-1).value().key, (mData->constEnd()-1).value().value));
  14749. }
  14750. /*! \internal
  14751. Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a
  14752. pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in
  14753. \ref selectTest.
  14754. */
  14755. double QCPCurve::pointDistance(const QPointF &pixelPoint) const
  14756. {
  14757. if (mData->isEmpty())
  14758. {
  14759. qDebug() << Q_FUNC_INFO << "requested point distance on curve" << mName << "without data";
  14760. return 500;
  14761. }
  14762. if (mData->size() == 1)
  14763. {
  14764. QPointF dataPoint = coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value);
  14765. return QVector2D(dataPoint-pixelPoint).length();
  14766. }
  14767. // calculate minimum distance to line segments:
  14768. QVector<QPointF> *lineData = new QVector<QPointF>;
  14769. getCurveData(lineData);
  14770. double minDistSqr = std::numeric_limits<double>::max();
  14771. for (int i=0; i<lineData->size()-1; ++i)
  14772. {
  14773. double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint);
  14774. if (currentDistSqr < minDistSqr)
  14775. minDistSqr = currentDistSqr;
  14776. }
  14777. delete lineData;
  14778. return sqrt(minDistSqr);
  14779. }
  14780. /*! \internal
  14781. This is a specialized \ref coordsToPixels function for points that are outside the visible
  14782. axisRect and just crossing a boundary (since \ref getCurveData reduces non-visible curve segments
  14783. to those line segments that cross region boundaries, see documentation there). It only uses the
  14784. coordinate parallel to the region boundary of the axisRect. The other coordinate is picked just
  14785. outside the axisRect (how far is determined by the scatter size and the line width). Together
  14786. with the optimization in \ref getCurveData this improves performance for large curves (or zoomed
  14787. in ones) significantly while keeping the illusion the whole curve and its filling is still being
  14788. drawn for the viewer.
  14789. */
  14790. QPointF QCPCurve::outsideCoordsToPixels(double key, double value, int region, QRect axisRect) const
  14791. {
  14792. int margin = qCeil(qMax(mScatterStyle.size(), (double)mPen.widthF())) + 2;
  14793. QPointF result = coordsToPixels(key, value);
  14794. switch (region)
  14795. {
  14796. case 2: result.setX(axisRect.left()-margin); break; // left
  14797. case 8: result.setX(axisRect.right()+margin); break; // right
  14798. case 4: result.setY(axisRect.top()-margin); break; // top
  14799. case 6: result.setY(axisRect.bottom()+margin); break; // bottom
  14800. case 1: result.setX(axisRect.left()-margin);
  14801. result.setY(axisRect.top()-margin); break; // top left
  14802. case 7: result.setX(axisRect.right()+margin);
  14803. result.setY(axisRect.top()-margin); break; // top right
  14804. case 9: result.setX(axisRect.right()+margin);
  14805. result.setY(axisRect.bottom()+margin); break; // bottom right
  14806. case 3: result.setX(axisRect.left()-margin);
  14807. result.setY(axisRect.bottom()+margin); break; // bottom left
  14808. }
  14809. return result;
  14810. }
  14811. /* inherits documentation from base class */
  14812. QCPRange QCPCurve::getKeyRange(bool &foundRange, SignDomain inSignDomain) const
  14813. {
  14814. QCPRange range;
  14815. bool haveLower = false;
  14816. bool haveUpper = false;
  14817. double current;
  14818. QCPCurveDataMap::const_iterator it = mData->constBegin();
  14819. while (it != mData->constEnd())
  14820. {
  14821. current = it.value().key;
  14822. if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0))
  14823. {
  14824. if (current < range.lower || !haveLower)
  14825. {
  14826. range.lower = current;
  14827. haveLower = true;
  14828. }
  14829. if (current > range.upper || !haveUpper)
  14830. {
  14831. range.upper = current;
  14832. haveUpper = true;
  14833. }
  14834. }
  14835. ++it;
  14836. }
  14837. foundRange = haveLower && haveUpper;
  14838. return range;
  14839. }
  14840. /* inherits documentation from base class */
  14841. QCPRange QCPCurve::getValueRange(bool &foundRange, SignDomain inSignDomain) const
  14842. {
  14843. QCPRange range;
  14844. bool haveLower = false;
  14845. bool haveUpper = false;
  14846. double current;
  14847. QCPCurveDataMap::const_iterator it = mData->constBegin();
  14848. while (it != mData->constEnd())
  14849. {
  14850. current = it.value().value;
  14851. if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0))
  14852. {
  14853. if (current < range.lower || !haveLower)
  14854. {
  14855. range.lower = current;
  14856. haveLower = true;
  14857. }
  14858. if (current > range.upper || !haveUpper)
  14859. {
  14860. range.upper = current;
  14861. haveUpper = true;
  14862. }
  14863. }
  14864. ++it;
  14865. }
  14866. foundRange = haveLower && haveUpper;
  14867. return range;
  14868. }
  14869. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14870. //////////////////// QCPBarData
  14871. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14872. /*! \class QCPBarData
  14873. \brief Holds the data of one single data point (one bar) for QCPBars.
  14874. The container for storing multiple data points is \ref QCPBarDataMap.
  14875. The stored data is:
  14876. \li \a key: coordinate on the key axis of this bar
  14877. \li \a value: height coordinate on the value axis of this bar
  14878. \see QCPBarDataaMap
  14879. */
  14880. /*!
  14881. Constructs a bar data point with key and value set to zero.
  14882. */
  14883. QCPBarData::QCPBarData() :
  14884. key(0),
  14885. value(0)
  14886. {
  14887. }
  14888. /*!
  14889. Constructs a bar data point with the specified \a key and \a value.
  14890. */
  14891. QCPBarData::QCPBarData(double key, double value) :
  14892. key(key),
  14893. value(value)
  14894. {
  14895. }
  14896. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14897. //////////////////// QCPBars
  14898. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14899. /*! \class QCPBars
  14900. \brief A plottable representing a bar chart in a plot.
  14901. \image html QCPBars.png
  14902. To plot data, assign it with the \ref setData or \ref addData functions.
  14903. \section appearance Changing the appearance
  14904. The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush).
  14905. Bar charts are stackable. This means, Two QCPBars plottables can be placed on top of each other
  14906. (see \ref QCPBars::moveAbove). Then, when two bars are at the same key position, they will appear
  14907. stacked.
  14908. \section usage Usage
  14909. Like all data representing objects in QCustomPlot, the QCPBars is a plottable
  14910. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  14911. (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.)
  14912. Usually, you first create an instance:
  14913. \code
  14914. QCPBars *newBars = new QCPBars(customPlot->xAxis, customPlot->yAxis);\endcode
  14915. add it to the customPlot with QCustomPlot::addPlottable:
  14916. \code
  14917. customPlot->addPlottable(newBars);\endcode
  14918. and then modify the properties of the newly created plottable, e.g.:
  14919. \code
  14920. newBars->setName("Country population");
  14921. newBars->setData(xData, yData);\endcode
  14922. */
  14923. /*! \fn QCPBars *QCPBars::barBelow() const
  14924. Returns the bars plottable that is directly below this bars plottable.
  14925. If there is no such plottable, returns 0.
  14926. \see barAbove, moveBelow, moveAbove
  14927. */
  14928. /*! \fn QCPBars *QCPBars::barAbove() const
  14929. Returns the bars plottable that is directly above this bars plottable.
  14930. If there is no such plottable, returns 0.
  14931. \see barBelow, moveBelow, moveAbove
  14932. */
  14933. /*!
  14934. Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  14935. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  14936. the same orientation. If either of these restrictions is violated, a corresponding message is
  14937. printed to the debug output (qDebug), the construction is not aborted, though.
  14938. The constructed QCPBars can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
  14939. then takes ownership of the bar chart.
  14940. */
  14941. QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  14942. QCPAbstractPlottable(keyAxis, valueAxis)
  14943. {
  14944. mData = new QCPBarDataMap;
  14945. mPen.setColor(Qt::blue);
  14946. mPen.setStyle(Qt::SolidLine);
  14947. mBrush.setColor(QColor(40, 50, 255, 30));
  14948. mBrush.setStyle(Qt::SolidPattern);
  14949. mSelectedPen = mPen;
  14950. mSelectedPen.setWidthF(2.5);
  14951. mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen
  14952. mSelectedBrush = mBrush;
  14953. mWidth = 0.75;
  14954. }
  14955. QCPBars::~QCPBars()
  14956. {
  14957. if (mBarBelow || mBarAbove)
  14958. connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking
  14959. delete mData;
  14960. }
  14961. /*!
  14962. Sets the width of the bars in plot (key) coordinates.
  14963. */
  14964. void QCPBars::setWidth(double width)
  14965. {
  14966. mWidth = width;
  14967. }
  14968. /*!
  14969. Replaces the current data with the provided \a data.
  14970. If \a copy is set to true, data points in \a data will only be copied. if false, the plottable
  14971. takes ownership of the passed data and replaces the internal data pointer with it. This is
  14972. significantly faster than copying for large datasets.
  14973. */
  14974. void QCPBars::setData(QCPBarDataMap *data, bool copy)
  14975. {
  14976. if (copy)
  14977. {
  14978. *mData = *data;
  14979. } else
  14980. {
  14981. delete mData;
  14982. mData = data;
  14983. }
  14984. }
  14985. /*! \overload
  14986. Replaces the current data with the provided points in \a key and \a value tuples. The
  14987. provided vectors should have equal length. Else, the number of added points will be the size of
  14988. the smallest vector.
  14989. */
  14990. void QCPBars::setData(const QVector<double> &key, const QVector<double> &value)
  14991. {
  14992. mData->clear();
  14993. int n = key.size();
  14994. n = qMin(n, value.size());
  14995. QCPBarData newData;
  14996. for (int i=0; i<n; ++i)
  14997. {
  14998. newData.key = key[i];
  14999. newData.value = value[i];
  15000. mData->insertMulti(newData.key, newData);
  15001. }
  15002. }
  15003. /*!
  15004. Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear
  15005. below the bars of \a bars. The move target \a bars must use the same key and value axis as this
  15006. plottable.
  15007. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
  15008. has a bars object below itself, this bars object is inserted between the two. If this bars object
  15009. is already between two other bars, the two other bars will be stacked on top of each other after
  15010. the operation.
  15011. To remove this bars plottable from any stacking, set \a bars to 0.
  15012. \see moveBelow, barAbove, barBelow
  15013. */
  15014. void QCPBars::moveBelow(QCPBars *bars)
  15015. {
  15016. if (bars == this) return;
  15017. if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
  15018. {
  15019. qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
  15020. return;
  15021. }
  15022. // remove from stacking:
  15023. connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
  15024. // if new bar given, insert this bar below it:
  15025. if (bars)
  15026. {
  15027. if (bars->mBarBelow)
  15028. connectBars(bars->mBarBelow.data(), this);
  15029. connectBars(this, bars);
  15030. }
  15031. }
  15032. /*!
  15033. Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear
  15034. above the bars of \a bars. The move target \a bars must use the same key and value axis as this
  15035. plottable.
  15036. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
  15037. has a bars object below itself, this bars object is inserted between the two. If this bars object
  15038. is already between two other bars, the two other bars will be stacked on top of each other after
  15039. the operation.
  15040. To remove this bars plottable from any stacking, set \a bars to 0.
  15041. \see moveBelow, barBelow, barAbove
  15042. */
  15043. void QCPBars::moveAbove(QCPBars *bars)
  15044. {
  15045. if (bars == this) return;
  15046. if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
  15047. {
  15048. qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
  15049. return;
  15050. }
  15051. // remove from stacking:
  15052. connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
  15053. // if new bar given, insert this bar above it:
  15054. if (bars)
  15055. {
  15056. if (bars->mBarAbove)
  15057. connectBars(this, bars->mBarAbove.data());
  15058. connectBars(bars, this);
  15059. }
  15060. }
  15061. /*!
  15062. Adds the provided data points in \a dataMap to the current data.
  15063. \see removeData
  15064. */
  15065. void QCPBars::addData(const QCPBarDataMap &dataMap)
  15066. {
  15067. mData->unite(dataMap);
  15068. }
  15069. /*! \overload
  15070. Adds the provided single data point in \a data to the current data.
  15071. \see removeData
  15072. */
  15073. void QCPBars::addData(const QCPBarData &data)
  15074. {
  15075. mData->insertMulti(data.key, data);
  15076. }
  15077. /*! \overload
  15078. Adds the provided single data point as \a key and \a value tuple to the current data
  15079. \see removeData
  15080. */
  15081. void QCPBars::addData(double key, double value)
  15082. {
  15083. QCPBarData newData;
  15084. newData.key = key;
  15085. newData.value = value;
  15086. mData->insertMulti(newData.key, newData);
  15087. }
  15088. /*! \overload
  15089. Adds the provided data points as \a key and \a value tuples to the current data.
  15090. \see removeData
  15091. */
  15092. void QCPBars::addData(const QVector<double> &keys, const QVector<double> &values)
  15093. {
  15094. int n = keys.size();
  15095. n = qMin(n, values.size());
  15096. QCPBarData newData;
  15097. for (int i=0; i<n; ++i)
  15098. {
  15099. newData.key = keys[i];
  15100. newData.value = values[i];
  15101. mData->insertMulti(newData.key, newData);
  15102. }
  15103. }
  15104. /*!
  15105. Removes all data points with key smaller than \a key.
  15106. \see addData, clearData
  15107. */
  15108. void QCPBars::removeDataBefore(double key)
  15109. {
  15110. QCPBarDataMap::iterator it = mData->begin();
  15111. while (it != mData->end() && it.key() < key)
  15112. it = mData->erase(it);
  15113. }
  15114. /*!
  15115. Removes all data points with key greater than \a key.
  15116. \see addData, clearData
  15117. */
  15118. void QCPBars::removeDataAfter(double key)
  15119. {
  15120. if (mData->isEmpty()) return;
  15121. QCPBarDataMap::iterator it = mData->upperBound(key);
  15122. while (it != mData->end())
  15123. it = mData->erase(it);
  15124. }
  15125. /*!
  15126. Removes all data points with key between \a fromKey and \a toKey. if \a fromKey is
  15127. greater or equal to \a toKey, the function does nothing. To remove a single data point with known
  15128. key, use \ref removeData(double key).
  15129. \see addData, clearData
  15130. */
  15131. void QCPBars::removeData(double fromKey, double toKey)
  15132. {
  15133. if (fromKey >= toKey || mData->isEmpty()) return;
  15134. QCPBarDataMap::iterator it = mData->upperBound(fromKey);
  15135. QCPBarDataMap::iterator itEnd = mData->upperBound(toKey);
  15136. while (it != itEnd)
  15137. it = mData->erase(it);
  15138. }
  15139. /*! \overload
  15140. Removes a single data point at \a key. If the position is not known with absolute precision,
  15141. consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval
  15142. around the suspected position, depeding on the precision with which the key is known.
  15143. \see addData, clearData
  15144. */
  15145. void QCPBars::removeData(double key)
  15146. {
  15147. mData->remove(key);
  15148. }
  15149. /*!
  15150. Removes all data points.
  15151. \see removeData, removeDataAfter, removeDataBefore
  15152. */
  15153. void QCPBars::clearData()
  15154. {
  15155. mData->clear();
  15156. }
  15157. /* inherits documentation from base class */
  15158. double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  15159. {
  15160. Q_UNUSED(details)
  15161. if (onlySelectable && !mSelectable)
  15162. return -1;
  15163. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  15164. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
  15165. {
  15166. QCPBarDataMap::ConstIterator it;
  15167. double posKey, posValue;
  15168. pixelsToCoords(pos, posKey, posValue);
  15169. for (it = mData->constBegin(); it != mData->constEnd(); ++it)
  15170. {
  15171. double baseValue = getBaseValue(it.key(), it.value().value >=0);
  15172. QCPRange keyRange(it.key()-mWidth*0.5, it.key()+mWidth*0.5);
  15173. QCPRange valueRange(baseValue, baseValue+it.value().value);
  15174. if (keyRange.contains(posKey) && valueRange.contains(posValue))
  15175. return mParentPlot->selectionTolerance()*0.99;
  15176. }
  15177. }
  15178. return -1;
  15179. }
  15180. /* inherits documentation from base class */
  15181. void QCPBars::draw(QCPPainter *painter)
  15182. {
  15183. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  15184. if (mData->isEmpty()) return;
  15185. QCPBarDataMap::const_iterator it;
  15186. for (it = mData->constBegin(); it != mData->constEnd(); ++it)
  15187. {
  15188. // skip bar if not visible in key axis range:
  15189. if (it.key()+mWidth*0.5 < mKeyAxis.data()->range().lower || it.key()-mWidth*0.5 > mKeyAxis.data()->range().upper)
  15190. continue;
  15191. // check data validity if flag set:
  15192. #ifdef QCUSTOMPLOT_CHECK_DATA
  15193. if (QCP::isInvalidData(it.value().key, it.value().value))
  15194. qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "of drawn range invalid." << "Plottable name:" << name();
  15195. #endif
  15196. QPolygonF barPolygon = getBarPolygon(it.key(), it.value().value);
  15197. // draw bar fill:
  15198. if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0)
  15199. {
  15200. applyFillAntialiasingHint(painter);
  15201. painter->setPen(Qt::NoPen);
  15202. painter->setBrush(mainBrush());
  15203. painter->drawPolygon(barPolygon);
  15204. }
  15205. // draw bar line:
  15206. if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)
  15207. {
  15208. applyDefaultAntialiasingHint(painter);
  15209. painter->setPen(mainPen());
  15210. painter->setBrush(Qt::NoBrush);
  15211. painter->drawPolyline(barPolygon);
  15212. }
  15213. }
  15214. }
  15215. /* inherits documentation from base class */
  15216. void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  15217. {
  15218. // draw filled rect:
  15219. applyDefaultAntialiasingHint(painter);
  15220. painter->setBrush(mBrush);
  15221. painter->setPen(mPen);
  15222. QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
  15223. r.moveCenter(rect.center());
  15224. painter->drawRect(r);
  15225. }
  15226. /*! \internal
  15227. Returns the polygon of a single bar with \a key and \a value. The Polygon is open at the bottom
  15228. and shifted according to the bar stacking (see \ref moveAbove).
  15229. */
  15230. QPolygonF QCPBars::getBarPolygon(double key, double value) const
  15231. {
  15232. QPolygonF result;
  15233. double baseValue = getBaseValue(key, value >= 0);
  15234. result << coordsToPixels(key-mWidth*0.5, baseValue);
  15235. result << coordsToPixels(key-mWidth*0.5, baseValue+value);
  15236. result << coordsToPixels(key+mWidth*0.5, baseValue+value);
  15237. result << coordsToPixels(key+mWidth*0.5, baseValue);
  15238. return result;
  15239. }
  15240. /*! \internal
  15241. This function is called to find at which value to start drawing the base of a bar at \a key, when
  15242. it is stacked on top of another QCPBars (e.g. with \ref moveAbove).
  15243. positive and negative bars are separated per stack (positive are stacked above 0-value upwards,
  15244. negative are stacked below 0-value downwards). This can be indicated with \a positive. So if the
  15245. bar for which we need the base value is negative, set \a positive to false.
  15246. */
  15247. double QCPBars::getBaseValue(double key, bool positive) const
  15248. {
  15249. if (mBarBelow)
  15250. {
  15251. double max = 0;
  15252. // find bars of mBarBelow that are approximately at key and find largest one:
  15253. QCPBarDataMap::const_iterator it = mBarBelow.data()->mData->lowerBound(key-mWidth*0.1);
  15254. QCPBarDataMap::const_iterator itEnd = mBarBelow.data()->mData->upperBound(key+mWidth*0.1);
  15255. while (it != itEnd)
  15256. {
  15257. if ((positive && it.value().value > max) ||
  15258. (!positive && it.value().value < max))
  15259. max = it.value().value;
  15260. ++it;
  15261. }
  15262. // recurse down the bar-stack to find the total height:
  15263. return max + mBarBelow.data()->getBaseValue(key, positive);
  15264. } else
  15265. return 0;
  15266. }
  15267. /*! \internal
  15268. Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties.
  15269. The bar(s) currently below lower and upper will become disconnected to lower/upper.
  15270. If lower is zero, upper will be disconnected at the bottom.
  15271. If upper is zero, lower will be disconnected at the top.
  15272. */
  15273. void QCPBars::connectBars(QCPBars *lower, QCPBars *upper)
  15274. {
  15275. if (!lower && !upper) return;
  15276. if (!lower) // disconnect upper at bottom
  15277. {
  15278. // disconnect old bar below upper:
  15279. if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
  15280. upper->mBarBelow.data()->mBarAbove = 0;
  15281. upper->mBarBelow = 0;
  15282. } else if (!upper) // disconnect lower at top
  15283. {
  15284. // disconnect old bar above lower:
  15285. if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
  15286. lower->mBarAbove.data()->mBarBelow = 0;
  15287. lower->mBarAbove = 0;
  15288. } else // connect lower and upper
  15289. {
  15290. // disconnect old bar above lower:
  15291. if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
  15292. lower->mBarAbove.data()->mBarBelow = 0;
  15293. // disconnect old bar below upper:
  15294. if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
  15295. upper->mBarBelow.data()->mBarAbove = 0;
  15296. lower->mBarAbove = upper;
  15297. upper->mBarBelow = lower;
  15298. }
  15299. }
  15300. /* inherits documentation from base class */
  15301. QCPRange QCPBars::getKeyRange(bool &foundRange, SignDomain inSignDomain) const
  15302. {
  15303. QCPRange range;
  15304. bool haveLower = false;
  15305. bool haveUpper = false;
  15306. double current;
  15307. double barWidthHalf = mWidth*0.5;
  15308. QCPBarDataMap::const_iterator it = mData->constBegin();
  15309. while (it != mData->constEnd())
  15310. {
  15311. current = it.value().key;
  15312. if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current+barWidthHalf < 0) || (inSignDomain == sdPositive && current-barWidthHalf > 0))
  15313. {
  15314. if (current-barWidthHalf < range.lower || !haveLower)
  15315. {
  15316. range.lower = current-barWidthHalf;
  15317. haveLower = true;
  15318. }
  15319. if (current+barWidthHalf > range.upper || !haveUpper)
  15320. {
  15321. range.upper = current+barWidthHalf;
  15322. haveUpper = true;
  15323. }
  15324. }
  15325. ++it;
  15326. }
  15327. foundRange = haveLower && haveUpper;
  15328. return range;
  15329. }
  15330. /* inherits documentation from base class */
  15331. QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const
  15332. {
  15333. QCPRange range;
  15334. bool haveLower = true; // set to true, because 0 should always be visible in bar charts
  15335. bool haveUpper = true; // set to true, because 0 should always be visible in bar charts
  15336. double current;
  15337. QCPBarDataMap::const_iterator it = mData->constBegin();
  15338. while (it != mData->constEnd())
  15339. {
  15340. current = it.value().value + getBaseValue(it.value().key, it.value().value >= 0);
  15341. if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0))
  15342. {
  15343. if (current < range.lower || !haveLower)
  15344. {
  15345. range.lower = current;
  15346. haveLower = true;
  15347. }
  15348. if (current > range.upper || !haveUpper)
  15349. {
  15350. range.upper = current;
  15351. haveUpper = true;
  15352. }
  15353. }
  15354. ++it;
  15355. }
  15356. foundRange = true; // return true because bar charts always have the 0-line visible
  15357. return range;
  15358. }
  15359. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15360. //////////////////// QCPStatisticalBox
  15361. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15362. /*! \class QCPStatisticalBox
  15363. \brief A plottable representing a single statistical box in a plot.
  15364. \image html QCPStatisticalBox.png
  15365. To plot data, assign it with the individual parameter functions or use \ref setData to set all
  15366. parameters at once. The individual functions are:
  15367. \li \ref setMinimum
  15368. \li \ref setLowerQuartile
  15369. \li \ref setMedian
  15370. \li \ref setUpperQuartile
  15371. \li \ref setMaximum
  15372. Additionally you can define a list of outliers, drawn as scatter datapoints:
  15373. \li \ref setOutliers
  15374. \section appearance Changing the appearance
  15375. The appearance of the box itself is controlled via \ref setPen and \ref setBrush. You may change
  15376. the width of the box with \ref setWidth in plot coordinates (not pixels).
  15377. Analog functions exist for the minimum/maximum-whiskers: \ref setWhiskerPen, \ref
  15378. setWhiskerBarPen, \ref setWhiskerWidth. The whisker width is the width of the bar at the top
  15379. (maximum) and bottom (minimum).
  15380. The median indicator line has its own pen, \ref setMedianPen.
  15381. If the whisker backbone pen is changed, make sure to set the capStyle to Qt::FlatCap. Else, the
  15382. backbone line might exceed the whisker bars by a few pixels due to the pen cap being not
  15383. perfectly flat.
  15384. The Outlier data points are drawn as normal scatter points. Their look can be controlled with
  15385. \ref setOutlierStyle
  15386. \section usage Usage
  15387. Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable
  15388. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  15389. (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.)
  15390. Usually, you first create an instance:
  15391. \code
  15392. QCPStatisticalBox *newBox = new QCPStatisticalBox(customPlot->xAxis, customPlot->yAxis);\endcode
  15393. add it to the customPlot with QCustomPlot::addPlottable:
  15394. \code
  15395. customPlot->addPlottable(newBox);\endcode
  15396. and then modify the properties of the newly created plottable, e.g.:
  15397. \code
  15398. newBox->setName("Measurement Series 1");
  15399. newBox->setData(1, 3, 4, 5, 7);
  15400. newBox->setOutliers(QVector<double>() << 0.5 << 0.64 << 7.2 << 7.42);\endcode
  15401. */
  15402. /*!
  15403. Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its
  15404. value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and
  15405. not have the same orientation. If either of these restrictions is violated, a corresponding
  15406. message is printed to the debug output (qDebug), the construction is not aborted, though.
  15407. The constructed statistical box can be added to the plot with QCustomPlot::addPlottable,
  15408. QCustomPlot then takes ownership of the statistical box.
  15409. */
  15410. QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  15411. QCPAbstractPlottable(keyAxis, valueAxis),
  15412. mKey(0),
  15413. mMinimum(0),
  15414. mLowerQuartile(0),
  15415. mMedian(0),
  15416. mUpperQuartile(0),
  15417. mMaximum(0)
  15418. {
  15419. setOutlierStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, 6));
  15420. setWhiskerWidth(0.2);
  15421. setWidth(0.5);
  15422. setPen(QPen(Qt::black));
  15423. setSelectedPen(QPen(Qt::blue, 2.5));
  15424. setMedianPen(QPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap));
  15425. setWhiskerPen(QPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap));
  15426. setWhiskerBarPen(QPen(Qt::black));
  15427. setBrush(Qt::NoBrush);
  15428. setSelectedBrush(Qt::NoBrush);
  15429. }
  15430. /*!
  15431. Sets the key coordinate of the statistical box.
  15432. */
  15433. void QCPStatisticalBox::setKey(double key)
  15434. {
  15435. mKey = key;
  15436. }
  15437. /*!
  15438. Sets the parameter "minimum" of the statistical box plot. This is the position of the lower
  15439. whisker, typically the minimum measurement of the sample that's not considered an outlier.
  15440. \see setMaximum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth
  15441. */
  15442. void QCPStatisticalBox::setMinimum(double value)
  15443. {
  15444. mMinimum = value;
  15445. }
  15446. /*!
  15447. Sets the parameter "lower Quartile" of the statistical box plot. This is the lower end of the
  15448. box. The lower and the upper quartiles are the two statistical quartiles around the median of the
  15449. sample, they contain 50% of the sample data.
  15450. \see setUpperQuartile, setPen, setBrush, setWidth
  15451. */
  15452. void QCPStatisticalBox::setLowerQuartile(double value)
  15453. {
  15454. mLowerQuartile = value;
  15455. }
  15456. /*!
  15457. Sets the parameter "median" of the statistical box plot. This is the value of the median mark
  15458. inside the quartile box. The median separates the sample data in half (50% of the sample data is
  15459. below/above the median).
  15460. \see setMedianPen
  15461. */
  15462. void QCPStatisticalBox::setMedian(double value)
  15463. {
  15464. mMedian = value;
  15465. }
  15466. /*!
  15467. Sets the parameter "upper Quartile" of the statistical box plot. This is the upper end of the
  15468. box. The lower and the upper quartiles are the two statistical quartiles around the median of the
  15469. sample, they contain 50% of the sample data.
  15470. \see setLowerQuartile, setPen, setBrush, setWidth
  15471. */
  15472. void QCPStatisticalBox::setUpperQuartile(double value)
  15473. {
  15474. mUpperQuartile = value;
  15475. }
  15476. /*!
  15477. Sets the parameter "maximum" of the statistical box plot. This is the position of the upper
  15478. whisker, typically the maximum measurement of the sample that's not considered an outlier.
  15479. \see setMinimum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth
  15480. */
  15481. void QCPStatisticalBox::setMaximum(double value)
  15482. {
  15483. mMaximum = value;
  15484. }
  15485. /*!
  15486. Sets a vector of outlier values that will be drawn as scatters. Any data points in the sample
  15487. that are not within the whiskers (\ref setMinimum, \ref setMaximum) should be considered outliers
  15488. and displayed as such.
  15489. \see setOutlierStyle
  15490. */
  15491. void QCPStatisticalBox::setOutliers(const QVector<double> &values)
  15492. {
  15493. mOutliers = values;
  15494. }
  15495. /*!
  15496. Sets all parameters of the statistical box plot at once.
  15497. \see setKey, setMinimum, setLowerQuartile, setMedian, setUpperQuartile, setMaximum
  15498. */
  15499. void QCPStatisticalBox::setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum)
  15500. {
  15501. setKey(key);
  15502. setMinimum(minimum);
  15503. setLowerQuartile(lowerQuartile);
  15504. setMedian(median);
  15505. setUpperQuartile(upperQuartile);
  15506. setMaximum(maximum);
  15507. }
  15508. /*!
  15509. Sets the width of the box in key coordinates.
  15510. \see setWhiskerWidth
  15511. */
  15512. void QCPStatisticalBox::setWidth(double width)
  15513. {
  15514. mWidth = width;
  15515. }
  15516. /*!
  15517. Sets the width of the whiskers (\ref setMinimum, \ref setMaximum) in key coordinates.
  15518. \see setWidth
  15519. */
  15520. void QCPStatisticalBox::setWhiskerWidth(double width)
  15521. {
  15522. mWhiskerWidth = width;
  15523. }
  15524. /*!
  15525. Sets the pen used for drawing the whisker backbone (That's the line parallel to the value axis).
  15526. Make sure to set the \a pen capStyle to Qt::FlatCap to prevent the whisker backbone from reaching
  15527. a few pixels past the whisker bars, when using a non-zero pen width.
  15528. \see setWhiskerBarPen
  15529. */
  15530. void QCPStatisticalBox::setWhiskerPen(const QPen &pen)
  15531. {
  15532. mWhiskerPen = pen;
  15533. }
  15534. /*!
  15535. Sets the pen used for drawing the whisker bars (Those are the lines parallel to the key axis at
  15536. each end of the whisker backbone).
  15537. \see setWhiskerPen
  15538. */
  15539. void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen)
  15540. {
  15541. mWhiskerBarPen = pen;
  15542. }
  15543. /*!
  15544. Sets the pen used for drawing the median indicator line inside the statistical box.
  15545. */
  15546. void QCPStatisticalBox::setMedianPen(const QPen &pen)
  15547. {
  15548. mMedianPen = pen;
  15549. }
  15550. /*!
  15551. Sets the appearance of the outlier data points.
  15552. \see setOutliers
  15553. */
  15554. void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style)
  15555. {
  15556. mOutlierStyle = style;
  15557. }
  15558. /* inherits documentation from base class */
  15559. void QCPStatisticalBox::clearData()
  15560. {
  15561. setOutliers(QVector<double>());
  15562. setKey(0);
  15563. setMinimum(0);
  15564. setLowerQuartile(0);
  15565. setMedian(0);
  15566. setUpperQuartile(0);
  15567. setMaximum(0);
  15568. }
  15569. /* inherits documentation from base class */
  15570. double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  15571. {
  15572. Q_UNUSED(details)
  15573. if (onlySelectable && !mSelectable)
  15574. return -1;
  15575. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  15576. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
  15577. {
  15578. double posKey, posValue;
  15579. pixelsToCoords(pos, posKey, posValue);
  15580. // quartile box:
  15581. QCPRange keyRange(mKey-mWidth*0.5, mKey+mWidth*0.5);
  15582. QCPRange valueRange(mLowerQuartile, mUpperQuartile);
  15583. if (keyRange.contains(posKey) && valueRange.contains(posValue))
  15584. return mParentPlot->selectionTolerance()*0.99;
  15585. // min/max whiskers:
  15586. if (QCPRange(mMinimum, mMaximum).contains(posValue))
  15587. return qAbs(mKeyAxis.data()->coordToPixel(mKey)-mKeyAxis.data()->coordToPixel(posKey));
  15588. }
  15589. return -1;
  15590. }
  15591. /* inherits documentation from base class */
  15592. void QCPStatisticalBox::draw(QCPPainter *painter)
  15593. {
  15594. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  15595. // check data validity if flag set:
  15596. #ifdef QCUSTOMPLOT_CHECK_DATA
  15597. if (QCP::isInvalidData(mKey, mMedian) ||
  15598. QCP::isInvalidData(mLowerQuartile, mUpperQuartile) ||
  15599. QCP::isInvalidData(mMinimum, mMaximum))
  15600. qDebug() << Q_FUNC_INFO << "Data point at" << mKey << "of drawn range has invalid data." << "Plottable name:" << name();
  15601. for (int i=0; i<mOutliers.size(); ++i)
  15602. if (QCP::isInvalidData(mOutliers.at(i)))
  15603. qDebug() << Q_FUNC_INFO << "Data point outlier at" << mKey << "of drawn range invalid." << "Plottable name:" << name();
  15604. #endif
  15605. QRectF quartileBox;
  15606. drawQuartileBox(painter, &quartileBox);
  15607. painter->save();
  15608. painter->setClipRect(quartileBox, Qt::IntersectClip);
  15609. drawMedian(painter);
  15610. painter->restore();
  15611. drawWhiskers(painter);
  15612. drawOutliers(painter);
  15613. }
  15614. /* inherits documentation from base class */
  15615. void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  15616. {
  15617. // draw filled rect:
  15618. applyDefaultAntialiasingHint(painter);
  15619. painter->setPen(mPen);
  15620. painter->setBrush(mBrush);
  15621. QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
  15622. r.moveCenter(rect.center());
  15623. painter->drawRect(r);
  15624. }
  15625. /*! \internal
  15626. Draws the quartile box. \a box is an output parameter that returns the quartile box (in pixel
  15627. coordinates) which is used to set the clip rect of the painter before calling \ref drawMedian (so
  15628. the median doesn't draw outside the quartile box).
  15629. */
  15630. void QCPStatisticalBox::drawQuartileBox(QCPPainter *painter, QRectF *quartileBox) const
  15631. {
  15632. QRectF box;
  15633. box.setTopLeft(coordsToPixels(mKey-mWidth*0.5, mUpperQuartile));
  15634. box.setBottomRight(coordsToPixels(mKey+mWidth*0.5, mLowerQuartile));
  15635. applyDefaultAntialiasingHint(painter);
  15636. painter->setPen(mainPen());
  15637. painter->setBrush(mainBrush());
  15638. painter->drawRect(box);
  15639. if (quartileBox)
  15640. *quartileBox = box;
  15641. }
  15642. /*! \internal
  15643. Draws the median line inside the quartile box.
  15644. */
  15645. void QCPStatisticalBox::drawMedian(QCPPainter *painter) const
  15646. {
  15647. QLineF medianLine;
  15648. medianLine.setP1(coordsToPixels(mKey-mWidth*0.5, mMedian));
  15649. medianLine.setP2(coordsToPixels(mKey+mWidth*0.5, mMedian));
  15650. applyDefaultAntialiasingHint(painter);
  15651. painter->setPen(mMedianPen);
  15652. painter->drawLine(medianLine);
  15653. }
  15654. /*! \internal
  15655. Draws both whisker backbones and bars.
  15656. */
  15657. void QCPStatisticalBox::drawWhiskers(QCPPainter *painter) const
  15658. {
  15659. QLineF backboneMin, backboneMax, barMin, barMax;
  15660. backboneMax.setPoints(coordsToPixels(mKey, mUpperQuartile), coordsToPixels(mKey, mMaximum));
  15661. backboneMin.setPoints(coordsToPixels(mKey, mLowerQuartile), coordsToPixels(mKey, mMinimum));
  15662. barMax.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMaximum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMaximum));
  15663. barMin.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMinimum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMinimum));
  15664. applyErrorBarsAntialiasingHint(painter);
  15665. painter->setPen(mWhiskerPen);
  15666. painter->drawLine(backboneMin);
  15667. painter->drawLine(backboneMax);
  15668. painter->setPen(mWhiskerBarPen);
  15669. painter->drawLine(barMin);
  15670. painter->drawLine(barMax);
  15671. }
  15672. /*! \internal
  15673. Draws the outlier scatter points.
  15674. */
  15675. void QCPStatisticalBox::drawOutliers(QCPPainter *painter) const
  15676. {
  15677. applyScattersAntialiasingHint(painter);
  15678. mOutlierStyle.applyTo(painter, mPen);
  15679. for (int i=0; i<mOutliers.size(); ++i)
  15680. mOutlierStyle.drawShape(painter, coordsToPixels(mKey, mOutliers.at(i)));
  15681. }
  15682. /* inherits documentation from base class */
  15683. QCPRange QCPStatisticalBox::getKeyRange(bool &foundRange, SignDomain inSignDomain) const
  15684. {
  15685. foundRange = true;
  15686. if (inSignDomain == sdBoth)
  15687. {
  15688. return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5);
  15689. } else if (inSignDomain == sdNegative)
  15690. {
  15691. if (mKey+mWidth*0.5 < 0)
  15692. return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5);
  15693. else if (mKey < 0)
  15694. return QCPRange(mKey-mWidth*0.5, mKey);
  15695. else
  15696. {
  15697. foundRange = false;
  15698. return QCPRange();
  15699. }
  15700. } else if (inSignDomain == sdPositive)
  15701. {
  15702. if (mKey-mWidth*0.5 > 0)
  15703. return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5);
  15704. else if (mKey > 0)
  15705. return QCPRange(mKey, mKey+mWidth*0.5);
  15706. else
  15707. {
  15708. foundRange = false;
  15709. return QCPRange();
  15710. }
  15711. }
  15712. foundRange = false;
  15713. return QCPRange();
  15714. }
  15715. /* inherits documentation from base class */
  15716. QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, SignDomain inSignDomain) const
  15717. {
  15718. QVector<double> values; // values that must be considered (i.e. all outliers and the five box-parameters)
  15719. values.reserve(mOutliers.size() + 5);
  15720. values << mMaximum << mUpperQuartile << mMedian << mLowerQuartile << mMinimum;
  15721. values << mOutliers;
  15722. // go through values and find the ones in legal range:
  15723. bool haveUpper = false;
  15724. bool haveLower = false;
  15725. double upper = 0;
  15726. double lower = 0;
  15727. for (int i=0; i<values.size(); ++i)
  15728. {
  15729. if ((inSignDomain == sdNegative && values.at(i) < 0) ||
  15730. (inSignDomain == sdPositive && values.at(i) > 0) ||
  15731. (inSignDomain == sdBoth))
  15732. {
  15733. if (values.at(i) > upper || !haveUpper)
  15734. {
  15735. upper = values.at(i);
  15736. haveUpper = true;
  15737. }
  15738. if (values.at(i) < lower || !haveLower)
  15739. {
  15740. lower = values.at(i);
  15741. haveLower = true;
  15742. }
  15743. }
  15744. }
  15745. // return the bounds if we found some sensible values:
  15746. if (haveLower && haveUpper)
  15747. {
  15748. foundRange = true;
  15749. return QCPRange(lower, upper);
  15750. } else // might happen if all values are in other sign domain
  15751. {
  15752. foundRange = false;
  15753. return QCPRange();
  15754. }
  15755. }
  15756. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15757. //////////////////// QCPColorMapData
  15758. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15759. /*! \class QCPColorMapData
  15760. \brief Holds the two-dimensional data of a QCPColorMap plottable.
  15761. This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref
  15762. QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a
  15763. color, depending on the value.
  15764. The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize).
  15765. Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref
  15766. setKeyRange, \ref setValueRange).
  15767. The data cells can be accessed in two ways: They can be directly addressed by an integer index
  15768. with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot
  15769. coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are
  15770. provided by the functions \ref coordToCell and \ref cellToCoord.
  15771. This class also buffers the minimum and maximum values that are in the data set, to provide
  15772. QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value
  15773. that is greater than the current maximum increases this maximum to the new value. However,
  15774. setting the cell that currently holds the maximum value to a smaller value doesn't decrease the
  15775. maximum again, because finding the true new maximum would require going through the entire data
  15776. array, which might be time consuming. The same holds for the data minimum. This functionality is
  15777. given by \ref recalculateDataBounds, such that you can decide when it is sensible to find the
  15778. true current minimum and maximum. The method QCPColorMap::rescaleDataRange offers a convenience
  15779. parameter \a recalculateDataBounds which may be set to true to automatically call \ref
  15780. recalculateDataBounds internally.
  15781. */
  15782. /* start of documentation of inline functions */
  15783. /*! \fn bool QCPColorMapData::isEmpty() const
  15784. Returns whether this instance carries no data. This is equivalent to having a size where at least
  15785. one of the dimensions is 0 (see \ref setSize).
  15786. */
  15787. /* end of documentation of inline functions */
  15788. /*!
  15789. Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction
  15790. and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap
  15791. at the coordinates \a keyRange and \a valueRange.
  15792. \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange
  15793. */
  15794. QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) :
  15795. mKeySize(0),
  15796. mValueSize(0),
  15797. mKeyRange(keyRange),
  15798. mValueRange(valueRange),
  15799. mIsEmpty(true),
  15800. mData(0),
  15801. mDataModified(true)
  15802. {
  15803. setSize(keySize, valueSize);
  15804. fill(0);
  15805. }
  15806. QCPColorMapData::~QCPColorMapData()
  15807. {
  15808. if (mData)
  15809. delete[] mData;
  15810. }
  15811. /*!
  15812. Constructs a new QCPColorMapData instance copying the data and range of \a other.
  15813. */
  15814. QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) :
  15815. mKeySize(0),
  15816. mValueSize(0),
  15817. mIsEmpty(true),
  15818. mData(0),
  15819. mDataModified(true)
  15820. {
  15821. *this = other;
  15822. }
  15823. /*!
  15824. Overwrites this color map data instance with the data stored in \a other.
  15825. */
  15826. QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other)
  15827. {
  15828. if (&other != this)
  15829. {
  15830. const int keySize = other.keySize();
  15831. const int valueSize = other.valueSize();
  15832. setSize(keySize, valueSize);
  15833. setRange(other.keyRange(), other.valueRange());
  15834. if (!mIsEmpty)
  15835. memcpy(mData, other.mData, sizeof(mData[0])*keySize*valueSize);
  15836. mDataBounds = other.mDataBounds;
  15837. mDataModified = true;
  15838. }
  15839. return *this;
  15840. }
  15841. /* undocumented getter */
  15842. double QCPColorMapData::data(double key, double value)
  15843. {
  15844. int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5;
  15845. int valueCell = (1.0-(value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower))*(mValueSize-1)+0.5;
  15846. if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
  15847. return mData[valueCell*mKeySize + keyCell];
  15848. else
  15849. return 0;
  15850. }
  15851. /* undocumented getter */
  15852. double QCPColorMapData::cell(int keyIndex, int valueIndex)
  15853. {
  15854. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  15855. return mData[valueIndex*mKeySize + keyIndex];
  15856. else
  15857. return 0;
  15858. }
  15859. /*!
  15860. Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in
  15861. the value dimension.
  15862. The current data is discarded and the map cells are set to 0, unless the map had already the
  15863. requested size.
  15864. Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref
  15865. isEmpty returns true.
  15866. \see setRange, setKeySize, setValueSize
  15867. */
  15868. void QCPColorMapData::setSize(int keySize, int valueSize)
  15869. {
  15870. if (keySize != mKeySize || valueSize != mValueSize)
  15871. {
  15872. mKeySize = keySize;
  15873. mValueSize = valueSize;
  15874. if (mData)
  15875. delete[] mData;
  15876. mIsEmpty = mKeySize == 0 || mValueSize == 0;
  15877. if (!mIsEmpty)
  15878. {
  15879. #ifdef __EXCEPTIONS
  15880. try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message
  15881. #endif
  15882. mData = new double[mKeySize*mValueSize];
  15883. #ifdef __EXCEPTIONS
  15884. } catch (...) { mData = 0; }
  15885. #endif
  15886. if (mData)
  15887. fill(0);
  15888. else
  15889. qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize;
  15890. } else
  15891. mData = 0;
  15892. mDataModified = true;
  15893. }
  15894. }
  15895. /*!
  15896. Resizes the data array to have \a keySize cells in the key dimension.
  15897. The current data is discarded and the map cells are set to 0, unless the map had already the
  15898. requested size.
  15899. Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true.
  15900. \see setKeyRange, setSize, setValueSize
  15901. */
  15902. void QCPColorMapData::setKeySize(int keySize)
  15903. {
  15904. setSize(keySize, mValueSize);
  15905. }
  15906. /*!
  15907. Resizes the data array to have \a valueSize cells in the value dimension.
  15908. The current data is discarded and the map cells are set to 0, unless the map had already the
  15909. requested size.
  15910. Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true.
  15911. \see setValueRange, setSize, setKeySize
  15912. */
  15913. void QCPColorMapData::setValueSize(int valueSize)
  15914. {
  15915. setSize(mKeySize, valueSize);
  15916. }
  15917. /*!
  15918. Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area
  15919. covered by the color map in plot coordinates.
  15920. The outer cells will be centered on the range boundaries given to this function. For example, if
  15921. the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
  15922. be cells centered on the key coordinates 2, 2.5 and 3.
  15923. \see setSize
  15924. */
  15925. void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange)
  15926. {
  15927. setKeyRange(keyRange);
  15928. setValueRange(valueRange);
  15929. }
  15930. /*!
  15931. Sets the coordinate range the data shall be distributed over in the key dimension. Together with
  15932. the value range, This defines the rectangular area covered by the color map in plot coordinates.
  15933. The outer cells will be centered on the range boundaries given to this function. For example, if
  15934. the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
  15935. be cells centered on the key coordinates 2, 2.5 and 3.
  15936. \see setRange, setValueRange, setSize
  15937. */
  15938. void QCPColorMapData::setKeyRange(const QCPRange &keyRange)
  15939. {
  15940. mKeyRange = keyRange;
  15941. }
  15942. /*!
  15943. Sets the coordinate range the data shall be distributed over in the value dimension. Together with
  15944. the key range, This defines the rectangular area covered by the color map in plot coordinates.
  15945. The outer cells will be centered on the range boundaries given to this function. For example, if
  15946. the value size (\ref setValueSize) is 3 and \a valueRange is set to <tt>QCPRange(2, 3)</tt> there
  15947. will be cells centered on the value coordinates 2, 2.5 and 3.
  15948. \see setRange, setKeyRange, setSize
  15949. */
  15950. void QCPColorMapData::setValueRange(const QCPRange &valueRange)
  15951. {
  15952. mValueRange = valueRange;
  15953. }
  15954. /*!
  15955. Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a
  15956. z.
  15957. \see setCell, setRange
  15958. */
  15959. void QCPColorMapData::setData(double key, double value, double z)
  15960. {
  15961. int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5;
  15962. int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5;
  15963. if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
  15964. {
  15965. mData[valueCell*mKeySize + keyCell] = z;
  15966. if (z < mDataBounds.lower)
  15967. mDataBounds.lower = z;
  15968. if (z > mDataBounds.upper)
  15969. mDataBounds.upper = z;
  15970. mDataModified = true;
  15971. }
  15972. }
  15973. /*!
  15974. Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices
  15975. enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see
  15976. \ref setSize).
  15977. In the standard plot configuration (horizontal key axis and vertical value axis, both not
  15978. range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with
  15979. indices (keySize-1, valueSize-1) is in the top right corner of the color map.
  15980. \see setData, setSize
  15981. */
  15982. void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z)
  15983. {
  15984. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  15985. {
  15986. mData[valueIndex*mKeySize + keyIndex] = z;
  15987. if (z < mDataBounds.lower)
  15988. mDataBounds.lower = z;
  15989. if (z > mDataBounds.upper)
  15990. mDataBounds.upper = z;
  15991. mDataModified = true;
  15992. }
  15993. }
  15994. /*!
  15995. Goes through the data and updates the buffered minimum and maximum data values.
  15996. Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange
  15997. and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten
  15998. with a smaller or larger value respectively, since the buffered maximum/minimum values have been
  15999. updated the last time. Why this is the case is explained in the class description (\ref
  16000. QCPColorMapData).
  16001. Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a
  16002. recalculateDataBounds for convenience. Setting this to true will call this method for you, before
  16003. doing the rescale.
  16004. */
  16005. void QCPColorMapData::recalculateDataBounds()
  16006. {
  16007. if (mKeySize > 0 && mValueSize > 0)
  16008. {
  16009. double minHeight = mData[0];
  16010. double maxHeight = mData[0];
  16011. const int dataCount = mValueSize*mKeySize;
  16012. for (int i=0; i<dataCount; ++i)
  16013. {
  16014. if (mData[i] > maxHeight)
  16015. maxHeight = mData[i];
  16016. if (mData[i] < minHeight)
  16017. minHeight = mData[i];
  16018. }
  16019. mDataBounds.lower = minHeight;
  16020. mDataBounds.upper = maxHeight;
  16021. }
  16022. }
  16023. /*!
  16024. Frees the internal data memory.
  16025. This is equivalent to calling \ref setSize "setSize(0, 0)".
  16026. */
  16027. void QCPColorMapData::clear()
  16028. {
  16029. setSize(0, 0);
  16030. }
  16031. /*!
  16032. Sets all cells to the value \a z.
  16033. */
  16034. void QCPColorMapData::fill(double z)
  16035. {
  16036. const int dataCount = mValueSize*mKeySize;
  16037. for (int i=0; i<dataCount; ++i)
  16038. mData[i] = z;
  16039. mDataBounds = QCPRange(z, z);
  16040. }
  16041. /*!
  16042. Transforms plot coordinates given by \a key and \a value to cell indices of this QCPColorMapData
  16043. instance. The resulting cell indices are returned via the output parameters \a keyIndex and \a
  16044. valueIndex.
  16045. The retrieved key/value cell indices can then be used for example with \ref setCell.
  16046. If you are only interested in a key or value index, you may pass 0 as \a valueIndex or \a
  16047. keyIndex.
  16048. \see cellToCoord, QCPAxis::coordToPixel
  16049. */
  16050. void QCPColorMapData::coordToCell(double key, double value, int *keyIndex, int *valueIndex) const
  16051. {
  16052. if (keyIndex)
  16053. *keyIndex = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5;
  16054. if (valueIndex)
  16055. *valueIndex = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5;
  16056. }
  16057. /*!
  16058. Transforms cell indices given by \a keyIndex and \a valueIndex to cell indices of this QCPColorMapData
  16059. instance. The resulting coordinates are returned via the output parameters \a key and \a
  16060. value.
  16061. If you are only interested in a key or value coordinate, you may pass 0 as \a key or \a
  16062. value.
  16063. \see coordToCell, QCPAxis::pixelToCoord
  16064. */
  16065. void QCPColorMapData::cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const
  16066. {
  16067. if (key)
  16068. *key = keyIndex/(double)(mKeySize-1)*(mKeyRange.upper-mKeyRange.lower)+mKeyRange.lower;
  16069. if (value)
  16070. *value = valueIndex/(double)(mValueSize-1)*(mValueRange.upper-mValueRange.lower)+mValueRange.lower;
  16071. }
  16072. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16073. //////////////////// QCPColorMap
  16074. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16075. /*! \class QCPColorMap
  16076. \brief A plottable representing a two-dimensional color map in a plot.
  16077. \image html QCPColorMap.png
  16078. The data is stored in the class \ref QCPColorMapData, which can be accessed via the data()
  16079. method.
  16080. A color map has three dimensions to represent a data point: The \a key dimension, the \a value
  16081. dimension and the \a data dimension. As with other plottables such as graphs, \a key and \a value
  16082. correspond to two orthogonal axes on the QCustomPlot surface that you specify in the QColorMap
  16083. constructor. The \a data dimension however is encoded as the color of the point at (\a key, \a
  16084. value).
  16085. Set the number of points (or \a cells) in the key/value dimension via \ref
  16086. QCPColorMapData::setSize. The plot coordinate range over which these points will be displayed is
  16087. specified via \ref QCPColorMapData::setRange. The first cell will be centered on the lower range
  16088. boundary and the last cell will be centered on the upper range boundary. The data can be set by
  16089. either accessing the cells directly with QCPColorMapData::setCell or by addressing the cells via
  16090. their plot coordinates with \ref QCPColorMapData::setData. If possible, you should prefer
  16091. setCell, since it doesn't need to do any coordinate transformation and thus performs a bit
  16092. better.
  16093. The cell with index (0, 0) is at the bottom left, if the color map uses normal (i.e. not reversed)
  16094. key and value axes.
  16095. To show the user which colors correspond to which \a data values, a \ref QCPColorScale is
  16096. typically placed to the right of the axis rect. See the documentation there for details on how to
  16097. add and use a color scale.
  16098. \section appearance Changing the appearance
  16099. The central part of the appearance is the color gradient, which can be specified via \ref
  16100. setGradient. See the documentation of \ref QCPColorGradient for details on configuring a color
  16101. gradient.
  16102. The \a data range that is mapped to the colors of the gradient can be specified with \ref
  16103. setDataRange. To make the data range encompass the whole data set minimum to maximum, call \ref
  16104. rescaleDataRange.
  16105. \section usage Usage
  16106. Like all data representing objects in QCustomPlot, the QCPColorMap is a plottable
  16107. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  16108. (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.)
  16109. Usually, you first create an instance:
  16110. \code
  16111. QCPColorMap *colorMap = new QCPColorMap(customPlot->xAxis, customPlot->yAxis);\endcode
  16112. add it to the customPlot with QCustomPlot::addPlottable:
  16113. \code
  16114. customPlot->addPlottable(colorMap);\endcode
  16115. and then modify the properties of the newly created color map, e.g.:
  16116. \code
  16117. colorMap->data()->setSize(50, 50);
  16118. colorMap->data()->setRange(QCPRange(0, 2), QCPRange(0, 2));
  16119. for (int x=0; x<50; ++x)
  16120. for (int y=0; y<50; ++y)
  16121. colorMap->data()->setCell(x, y, qCos(x/10.0)+qSin(y/10.0));
  16122. colorMap->setGradient(QCPColorGradient::gpPolar);
  16123. colorMap->rescaleDataRange(true);
  16124. customPlot->rescaleAxes();
  16125. customPlot->replot();
  16126. \endcode
  16127. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  16128. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  16129. you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
  16130. determine the cell index. Rather directly access the cell index with \ref
  16131. QCPColorMapData::setCell.
  16132. */
  16133. /* start documentation of inline functions */
  16134. /*! \fn QCPColorMapData *QCPColorMap::data() const
  16135. Returns a pointer to the internal data storage of type \ref QCPColorMapData. Access this to
  16136. modify data points (cells) and the color map key/value range.
  16137. \see setData
  16138. */
  16139. /* end documentation of inline functions */
  16140. /* start documentation of signals */
  16141. /*! \fn void QCPColorMap::dataRangeChanged(QCPRange newRange);
  16142. This signal is emitted when the data range changes.
  16143. \see setDataRange
  16144. */
  16145. /*! \fn void QCPColorMap::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
  16146. This signal is emitted when the data scale type changes.
  16147. \see setDataScaleType
  16148. */
  16149. /*! \fn void QCPColorMap::gradientChanged(QCPColorGradient newGradient);
  16150. This signal is emitted when the gradient changes.
  16151. \see setGradient
  16152. */
  16153. /* end documentation of signals */
  16154. /*!
  16155. Constructs a color map with the specified \a keyAxis and \a valueAxis.
  16156. The constructed QCPColorMap can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
  16157. then takes ownership of the color map.
  16158. */
  16159. QCPColorMap::QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  16160. QCPAbstractPlottable(keyAxis, valueAxis),
  16161. mDataScaleType(QCPAxis::stLinear),
  16162. mMapData(new QCPColorMapData(10, 10, QCPRange(0, 5), QCPRange(0, 5))),
  16163. mInterpolate(true),
  16164. mTightBoundary(false),
  16165. mMapImageInvalidated(true)
  16166. {
  16167. }
  16168. QCPColorMap::~QCPColorMap()
  16169. {
  16170. delete mMapData;
  16171. }
  16172. /*!
  16173. Replaces the current \ref data with the provided \a data.
  16174. If \a copy is set to true, the \a data object will only be copied. if false, the color map
  16175. takes ownership of the passed data and replaces the internal data pointer with it. This is
  16176. significantly faster than copying for large datasets.
  16177. */
  16178. void QCPColorMap::setData(QCPColorMapData *data, bool copy)
  16179. {
  16180. if (copy)
  16181. {
  16182. *mMapData = *data;
  16183. } else
  16184. {
  16185. delete mMapData;
  16186. mMapData = data;
  16187. }
  16188. mMapImageInvalidated = true;
  16189. }
  16190. /*!
  16191. Sets the data range of this color map to \a dataRange. The data range defines which data values
  16192. are mapped to the color gradient.
  16193. To make the data range span the full range of the data set, use \ref rescaleDataRange.
  16194. \see QCPColorScale::setDataRange
  16195. */
  16196. void QCPColorMap::setDataRange(const QCPRange &dataRange)
  16197. {
  16198. if (!QCPRange::validRange(dataRange)) return;
  16199. if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
  16200. {
  16201. if (mDataScaleType == QCPAxis::stLogarithmic)
  16202. mDataRange = dataRange.sanitizedForLogScale();
  16203. else
  16204. mDataRange = dataRange.sanitizedForLinScale();
  16205. mMapImageInvalidated = true;
  16206. emit dataRangeChanged(mDataRange);
  16207. }
  16208. }
  16209. /*!
  16210. Sets whether the data is correlated with the color gradient linearly or logarithmically.
  16211. \see QCPColorScale::setDataScaleType
  16212. */
  16213. void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType)
  16214. {
  16215. if (mDataScaleType != scaleType)
  16216. {
  16217. mDataScaleType = scaleType;
  16218. mMapImageInvalidated = true;
  16219. emit dataScaleTypeChanged(mDataScaleType);
  16220. if (mDataScaleType == QCPAxis::stLogarithmic)
  16221. setDataRange(mDataRange.sanitizedForLogScale());
  16222. }
  16223. }
  16224. /*!
  16225. Sets the color gradient that is used to represent the data. For more details on how to create an
  16226. own gradient or use one of the preset gradients, see \ref QCPColorGradient.
  16227. The colors defined by the gradient will be used to represent data values in the currently set
  16228. data range, see \ref setDataRange. Data points that are outside this data range will either be
  16229. colored uniformly with the respective gradient boundary color, or the gradient will repeat,
  16230. depending on \ref QCPColorGradient::setPeriodic.
  16231. \see QCPColorScale::setGradient
  16232. */
  16233. void QCPColorMap::setGradient(const QCPColorGradient &gradient)
  16234. {
  16235. if (mGradient != gradient)
  16236. {
  16237. mGradient = gradient;
  16238. mMapImageInvalidated = true;
  16239. emit gradientChanged(mGradient);
  16240. }
  16241. }
  16242. /*!
  16243. Sets whether the color map image shall use bicubic interpolation when displaying the color map
  16244. shrinked or expanded, and not at a 1:1 pixel-to-data scale.
  16245. \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled"
  16246. */
  16247. void QCPColorMap::setInterpolate(bool enabled)
  16248. {
  16249. mInterpolate = enabled;
  16250. }
  16251. /*!
  16252. Sets whether the outer most data rows and columns are clipped to the specified key and value
  16253. range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange).
  16254. if \a enabled is set to false, the data points at the border of the color map are drawn with the
  16255. same width and height as all other data points. Since the data points are represented by
  16256. rectangles of one color centered on the data coordinate, this means that the shown color map
  16257. extends by half a data point over the specified key/value range in each direction.
  16258. \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled"
  16259. */
  16260. void QCPColorMap::setTightBoundary(bool enabled)
  16261. {
  16262. mTightBoundary = enabled;
  16263. }
  16264. /*!
  16265. Associates the color scale \a colorScale with this color map.
  16266. This means that both the color scale and the color map synchronize their gradient, data range and
  16267. data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps
  16268. can be associated with one single color scale. This causes the color maps to also synchronize
  16269. those properties, via the mutual color scale.
  16270. This function causes the color map to adopt the current color gradient, data range and data scale
  16271. type of \a colorScale. After this call, you may change these properties at either the color map
  16272. or the color scale, and the setting will be applied to both.
  16273. Pass 0 as \a colorScale to disconnect the color scale from this color map again.
  16274. */
  16275. void QCPColorMap::setColorScale(QCPColorScale *colorScale)
  16276. {
  16277. if (mColorScale) // unconnect signals from old color scale
  16278. {
  16279. disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
  16280. disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
  16281. disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
  16282. disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  16283. disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
  16284. disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  16285. }
  16286. mColorScale = colorScale;
  16287. if (mColorScale) // connect signals to new color scale
  16288. {
  16289. setGradient(mColorScale.data()->gradient());
  16290. setDataRange(mColorScale.data()->dataRange());
  16291. setDataScaleType(mColorScale.data()->dataScaleType());
  16292. connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
  16293. connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
  16294. connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
  16295. connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  16296. connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
  16297. connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  16298. }
  16299. }
  16300. /*!
  16301. Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the
  16302. current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods,
  16303. only for the third data dimension of the color map.
  16304. The minimum and maximum values of the data set are buffered in the internal QCPColorMapData
  16305. instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref
  16306. QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For
  16307. performance reasons, however, they are only updated in an expanding fashion. So the buffered
  16308. maximum can only increase and the buffered minimum can only decrease. In consequence, changes to
  16309. the data that actually lower the maximum of the data set (by overwriting the cell holding the
  16310. current maximum with a smaller value), aren't recognized and the buffered maximum overestimates
  16311. the true maximum of the data set. The same happens for the buffered minimum. To recalculate the
  16312. true minimum and maximum by explicitly looking at each cell, the method
  16313. QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a
  16314. recalculateDataBounds calls this method before setting the data range to the buffered minimum and
  16315. maximum.
  16316. \see setDataRange
  16317. */
  16318. void QCPColorMap::rescaleDataRange(bool recalculateDataBounds)
  16319. {
  16320. if (recalculateDataBounds)
  16321. mMapData->recalculateDataBounds();
  16322. setDataRange(mMapData->dataBounds());
  16323. }
  16324. /*!
  16325. Takes the current appearance of the color map and updates the legend icon, which is used to
  16326. represent this color map in the legend (see \ref QCPLegend).
  16327. The \a transformMode specifies whether the rescaling is done by a faster, low quality image
  16328. scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm
  16329. (Qt::SmoothTransformation).
  16330. The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to
  16331. the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured
  16332. legend icon size, the thumb will be rescaled during drawing of the legend item.
  16333. \see setDataRange
  16334. */
  16335. void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize)
  16336. {
  16337. if (mMapImage.isNull() && !data()->isEmpty())
  16338. updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet)
  16339. if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again
  16340. {
  16341. bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
  16342. bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
  16343. mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode);
  16344. }
  16345. }
  16346. /*!
  16347. Clears the colormap data by calling \ref QCPColorMapData::clear() on the internal data. This also
  16348. resizes the map to 0x0 cells.
  16349. */
  16350. void QCPColorMap::clearData()
  16351. {
  16352. mMapData->clear();
  16353. }
  16354. /* inherits documentation from base class */
  16355. double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  16356. {
  16357. Q_UNUSED(details)
  16358. if (onlySelectable && !mSelectable)
  16359. return -1;
  16360. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  16361. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
  16362. {
  16363. double posKey, posValue;
  16364. pixelsToCoords(pos, posKey, posValue);
  16365. if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue))
  16366. return mParentPlot->selectionTolerance()*0.99;
  16367. }
  16368. return -1;
  16369. }
  16370. /*! \internal
  16371. Updates the internal map image buffer by going through the internal \ref QCPColorMapData and
  16372. turning the data values into color pixels with \ref QCPColorGradient::colorize.
  16373. This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image
  16374. has been invalidated for a different reason (e.g. a change of the data range with \ref
  16375. setDataRange).
  16376. */
  16377. void QCPColorMap::updateMapImage()
  16378. {
  16379. QCPAxis *keyAxis = mKeyAxis.data();
  16380. if (!keyAxis) return;
  16381. // resize mMapImage to correct dimensions, according to key/value axes orientation:
  16382. if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.size().width() != mMapData->keySize() || mMapImage.size().height() != mMapData->valueSize()))
  16383. mMapImage = QImage(QSize(mMapData->keySize(), mMapData->valueSize()), QImage::Format_RGB32);
  16384. else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.size().width() != mMapData->valueSize() || mMapImage.size().height() != mMapData->keySize()))
  16385. mMapImage = QImage(QSize(mMapData->valueSize(), mMapData->keySize()), QImage::Format_RGB32);
  16386. const int keySize = mMapData->keySize();
  16387. const int valueSize = mMapData->valueSize();
  16388. const double *rawData = mMapData->mData;
  16389. if (keyAxis->orientation() == Qt::Horizontal)
  16390. {
  16391. const int lineCount = valueSize;
  16392. const int rowCount = keySize;
  16393. for (int line=0; line<lineCount; ++line)
  16394. {
  16395. 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)
  16396. mGradient.colorize(rawData+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic);
  16397. }
  16398. } else // keyAxis->orientation() == Qt::Vertical
  16399. {
  16400. const int lineCount = keySize;
  16401. const int rowCount = valueSize;
  16402. for (int line=0; line<lineCount; ++line)
  16403. {
  16404. 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)
  16405. mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic);
  16406. }
  16407. }
  16408. mMapData->mDataModified = false;
  16409. mMapImageInvalidated = false;
  16410. }
  16411. /* inherits documentation from base class */
  16412. void QCPColorMap::draw(QCPPainter *painter)
  16413. {
  16414. if (mMapData->isEmpty()) return;
  16415. if (!mKeyAxis || !mValueAxis) return;
  16416. applyDefaultAntialiasingHint(painter);
  16417. if (mMapData->mDataModified || mMapImageInvalidated)
  16418. updateMapImage();
  16419. double halfSampleKey = 0;
  16420. double halfSampleValue = 0;
  16421. if (mMapData->keySize() > 1)
  16422. halfSampleKey = 0.5*mMapData->keyRange().size()/(double)(mMapData->keySize()-1);
  16423. if (mMapData->valueSize() > 1)
  16424. halfSampleValue = 0.5*mMapData->valueRange().size()/(double)(mMapData->valueSize()-1);
  16425. QRectF imageRect(coordsToPixels(mMapData->keyRange().lower-halfSampleKey, mMapData->valueRange().lower-halfSampleValue),
  16426. coordsToPixels(mMapData->keyRange().upper+halfSampleKey, mMapData->valueRange().upper+halfSampleValue));
  16427. imageRect = imageRect.normalized();
  16428. bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
  16429. bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
  16430. bool smoothBackup = painter->renderHints().testFlag(QPainter::SmoothPixmapTransform);
  16431. painter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate);
  16432. QRegion clipBackup;
  16433. if (mTightBoundary)
  16434. {
  16435. clipBackup = painter->clipRegion();
  16436. painter->setClipRect(QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
  16437. coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(), Qt::IntersectClip);
  16438. }
  16439. painter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY));
  16440. if (mTightBoundary)
  16441. painter->setClipRegion(clipBackup);
  16442. painter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup);
  16443. }
  16444. /* inherits documentation from base class */
  16445. void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  16446. {
  16447. applyDefaultAntialiasingHint(painter);
  16448. // draw map thumbnail:
  16449. if (!mLegendIcon.isNull())
  16450. {
  16451. QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation);
  16452. QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height());
  16453. iconRect.moveCenter(rect.center());
  16454. painter->drawPixmap(iconRect.topLeft(), scaledIcon);
  16455. }
  16456. /*
  16457. // draw frame:
  16458. painter->setBrush(Qt::NoBrush);
  16459. painter->setPen(Qt::black);
  16460. painter->drawRect(rect.adjusted(1, 1, 0, 0));
  16461. */
  16462. }
  16463. /* inherits documentation from base class */
  16464. QCPRange QCPColorMap::getKeyRange(bool &foundRange, SignDomain inSignDomain) const
  16465. {
  16466. foundRange = true;
  16467. QCPRange result = mMapData->keyRange();
  16468. result.normalize();
  16469. if (inSignDomain == QCPAbstractPlottable::sdPositive)
  16470. {
  16471. if (result.lower <= 0 && result.upper > 0)
  16472. result.lower = result.upper*1e-3;
  16473. else if (result.lower <= 0 && result.upper <= 0)
  16474. foundRange = false;
  16475. } else if (inSignDomain == QCPAbstractPlottable::sdNegative)
  16476. {
  16477. if (result.upper >= 0 && result.lower < 0)
  16478. result.upper = result.lower*1e-3;
  16479. else if (result.upper >= 0 && result.lower >= 0)
  16480. foundRange = false;
  16481. }
  16482. return result;
  16483. }
  16484. /* inherits documentation from base class */
  16485. QCPRange QCPColorMap::getValueRange(bool &foundRange, SignDomain inSignDomain) const
  16486. {
  16487. foundRange = true;
  16488. QCPRange result = mMapData->valueRange();
  16489. result.normalize();
  16490. if (inSignDomain == QCPAbstractPlottable::sdPositive)
  16491. {
  16492. if (result.lower <= 0 && result.upper > 0)
  16493. result.lower = result.upper*1e-3;
  16494. else if (result.lower <= 0 && result.upper <= 0)
  16495. foundRange = false;
  16496. } else if (inSignDomain == QCPAbstractPlottable::sdNegative)
  16497. {
  16498. if (result.upper >= 0 && result.lower < 0)
  16499. result.upper = result.lower*1e-3;
  16500. else if (result.upper >= 0 && result.lower >= 0)
  16501. foundRange = false;
  16502. }
  16503. return result;
  16504. }
  16505. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16506. //////////////////// QCPItemStraightLine
  16507. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16508. /*! \class QCPItemStraightLine
  16509. \brief A straight line that spans infinitely in both directions
  16510. \image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid blue discs are positions."
  16511. It has two positions, \a point1 and \a point2, which define the straight line.
  16512. */
  16513. /*!
  16514. Creates a straight line item and sets default values.
  16515. The constructed item can be added to the plot with QCustomPlot::addItem.
  16516. */
  16517. QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) :
  16518. QCPAbstractItem(parentPlot),
  16519. point1(createPosition("point1")),
  16520. point2(createPosition("point2"))
  16521. {
  16522. point1->setCoords(0, 0);
  16523. point2->setCoords(1, 1);
  16524. setPen(QPen(Qt::black));
  16525. setSelectedPen(QPen(Qt::blue,2));
  16526. }
  16527. QCPItemStraightLine::~QCPItemStraightLine()
  16528. {
  16529. }
  16530. /*!
  16531. Sets the pen that will be used to draw the line
  16532. \see setSelectedPen
  16533. */
  16534. void QCPItemStraightLine::setPen(const QPen &pen)
  16535. {
  16536. mPen = pen;
  16537. }
  16538. /*!
  16539. Sets the pen that will be used to draw the line when selected
  16540. \see setPen, setSelected
  16541. */
  16542. void QCPItemStraightLine::setSelectedPen(const QPen &pen)
  16543. {
  16544. mSelectedPen = pen;
  16545. }
  16546. /* inherits documentation from base class */
  16547. double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  16548. {
  16549. Q_UNUSED(details)
  16550. if (onlySelectable && !mSelectable)
  16551. return -1;
  16552. return distToStraightLine(QVector2D(point1->pixelPoint()), QVector2D(point2->pixelPoint()-point1->pixelPoint()), QVector2D(pos));
  16553. }
  16554. /* inherits documentation from base class */
  16555. void QCPItemStraightLine::draw(QCPPainter *painter)
  16556. {
  16557. QVector2D start(point1->pixelPoint());
  16558. QVector2D end(point2->pixelPoint());
  16559. // get visible segment of straight line inside clipRect:
  16560. double clipPad = mainPen().widthF();
  16561. QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
  16562. // paint visible segment, if existent:
  16563. if (!line.isNull())
  16564. {
  16565. painter->setPen(mainPen());
  16566. painter->drawLine(line);
  16567. }
  16568. }
  16569. /*! \internal
  16570. finds the shortest distance of \a point to the straight line defined by the base point \a
  16571. base and the direction vector \a vec.
  16572. This is a helper function for \ref selectTest.
  16573. */
  16574. double QCPItemStraightLine::distToStraightLine(const QVector2D &base, const QVector2D &vec, const QVector2D &point) const
  16575. {
  16576. return qAbs((base.y()-point.y())*vec.x()-(base.x()-point.x())*vec.y())/vec.length();
  16577. }
  16578. /*! \internal
  16579. Returns the section of the straight line defined by \a base and direction vector \a
  16580. vec, that is visible in the specified \a rect.
  16581. This is a helper function for \ref draw.
  16582. */
  16583. QLineF QCPItemStraightLine::getRectClippedStraightLine(const QVector2D &base, const QVector2D &vec, const QRect &rect) const
  16584. {
  16585. double bx, by;
  16586. double gamma;
  16587. QLineF result;
  16588. if (vec.x() == 0 && vec.y() == 0)
  16589. return result;
  16590. if (qFuzzyIsNull(vec.x())) // line is vertical
  16591. {
  16592. // check top of rect:
  16593. bx = rect.left();
  16594. by = rect.top();
  16595. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  16596. if (gamma >= 0 && gamma <= rect.width())
  16597. result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical
  16598. } else if (qFuzzyIsNull(vec.y())) // line is horizontal
  16599. {
  16600. // check left of rect:
  16601. bx = rect.left();
  16602. by = rect.top();
  16603. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  16604. if (gamma >= 0 && gamma <= rect.height())
  16605. result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal
  16606. } else // line is skewed
  16607. {
  16608. QList<QVector2D> pointVectors;
  16609. // check top of rect:
  16610. bx = rect.left();
  16611. by = rect.top();
  16612. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  16613. if (gamma >= 0 && gamma <= rect.width())
  16614. pointVectors.append(QVector2D(bx+gamma, by));
  16615. // check bottom of rect:
  16616. bx = rect.left();
  16617. by = rect.bottom();
  16618. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  16619. if (gamma >= 0 && gamma <= rect.width())
  16620. pointVectors.append(QVector2D(bx+gamma, by));
  16621. // check left of rect:
  16622. bx = rect.left();
  16623. by = rect.top();
  16624. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  16625. if (gamma >= 0 && gamma <= rect.height())
  16626. pointVectors.append(QVector2D(bx, by+gamma));
  16627. // check right of rect:
  16628. bx = rect.right();
  16629. by = rect.top();
  16630. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  16631. if (gamma >= 0 && gamma <= rect.height())
  16632. pointVectors.append(QVector2D(bx, by+gamma));
  16633. // evaluate points:
  16634. if (pointVectors.size() == 2)
  16635. {
  16636. result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
  16637. } else if (pointVectors.size() > 2)
  16638. {
  16639. // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
  16640. double distSqrMax = 0;
  16641. QVector2D pv1, pv2;
  16642. for (int i=0; i<pointVectors.size()-1; ++i)
  16643. {
  16644. for (int k=i+1; k<pointVectors.size(); ++k)
  16645. {
  16646. double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
  16647. if (distSqr > distSqrMax)
  16648. {
  16649. pv1 = pointVectors.at(i);
  16650. pv2 = pointVectors.at(k);
  16651. distSqrMax = distSqr;
  16652. }
  16653. }
  16654. }
  16655. result.setPoints(pv1.toPointF(), pv2.toPointF());
  16656. }
  16657. }
  16658. return result;
  16659. }
  16660. /*! \internal
  16661. Returns the pen that should be used for drawing lines. Returns mPen when the
  16662. item is not selected and mSelectedPen when it is.
  16663. */
  16664. QPen QCPItemStraightLine::mainPen() const
  16665. {
  16666. return mSelected ? mSelectedPen : mPen;
  16667. }
  16668. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16669. //////////////////// QCPItemLine
  16670. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16671. /*! \class QCPItemLine
  16672. \brief A line from one point to another
  16673. \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions."
  16674. It has two positions, \a start and \a end, which define the end points of the line.
  16675. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow.
  16676. */
  16677. /*!
  16678. Creates a line item and sets default values.
  16679. The constructed item can be added to the plot with QCustomPlot::addItem.
  16680. */
  16681. QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) :
  16682. QCPAbstractItem(parentPlot),
  16683. start(createPosition("start")),
  16684. end(createPosition("end"))
  16685. {
  16686. start->setCoords(0, 0);
  16687. end->setCoords(1, 1);
  16688. setPen(QPen(Qt::black));
  16689. setSelectedPen(QPen(Qt::blue,2));
  16690. }
  16691. QCPItemLine::~QCPItemLine()
  16692. {
  16693. }
  16694. /*!
  16695. Sets the pen that will be used to draw the line
  16696. \see setSelectedPen
  16697. */
  16698. void QCPItemLine::setPen(const QPen &pen)
  16699. {
  16700. mPen = pen;
  16701. }
  16702. /*!
  16703. Sets the pen that will be used to draw the line when selected
  16704. \see setPen, setSelected
  16705. */
  16706. void QCPItemLine::setSelectedPen(const QPen &pen)
  16707. {
  16708. mSelectedPen = pen;
  16709. }
  16710. /*!
  16711. Sets the line ending style of the head. The head corresponds to the \a end position.
  16712. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  16713. a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
  16714. \see setTail
  16715. */
  16716. void QCPItemLine::setHead(const QCPLineEnding &head)
  16717. {
  16718. mHead = head;
  16719. }
  16720. /*!
  16721. Sets the line ending style of the tail. The tail corresponds to the \a start position.
  16722. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  16723. a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
  16724. \see setHead
  16725. */
  16726. void QCPItemLine::setTail(const QCPLineEnding &tail)
  16727. {
  16728. mTail = tail;
  16729. }
  16730. /* inherits documentation from base class */
  16731. double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  16732. {
  16733. Q_UNUSED(details)
  16734. if (onlySelectable && !mSelectable)
  16735. return -1;
  16736. return qSqrt(distSqrToLine(start->pixelPoint(), end->pixelPoint(), pos));
  16737. }
  16738. /* inherits documentation from base class */
  16739. void QCPItemLine::draw(QCPPainter *painter)
  16740. {
  16741. QVector2D startVec(start->pixelPoint());
  16742. QVector2D endVec(end->pixelPoint());
  16743. if (startVec.toPoint() == endVec.toPoint())
  16744. return;
  16745. // get visible segment of straight line inside clipRect:
  16746. double clipPad = qMax(mHead.boundingDistance(), mTail.boundingDistance());
  16747. clipPad = qMax(clipPad, (double)mainPen().widthF());
  16748. QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
  16749. // paint visible segment, if existent:
  16750. if (!line.isNull())
  16751. {
  16752. painter->setPen(mainPen());
  16753. painter->drawLine(line);
  16754. painter->setBrush(Qt::SolidPattern);
  16755. if (mTail.style() != QCPLineEnding::esNone)
  16756. mTail.draw(painter, startVec, startVec-endVec);
  16757. if (mHead.style() != QCPLineEnding::esNone)
  16758. mHead.draw(painter, endVec, endVec-startVec);
  16759. }
  16760. }
  16761. /*! \internal
  16762. Returns the section of the line defined by \a start and \a end, that is visible in the specified
  16763. \a rect.
  16764. This is a helper function for \ref draw.
  16765. */
  16766. QLineF QCPItemLine::getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const
  16767. {
  16768. bool containsStart = rect.contains(start.x(), start.y());
  16769. bool containsEnd = rect.contains(end.x(), end.y());
  16770. if (containsStart && containsEnd)
  16771. return QLineF(start.toPointF(), end.toPointF());
  16772. QVector2D base = start;
  16773. QVector2D vec = end-start;
  16774. double bx, by;
  16775. double gamma, mu;
  16776. QLineF result;
  16777. QList<QVector2D> pointVectors;
  16778. if (!qFuzzyIsNull(vec.y())) // line is not horizontal
  16779. {
  16780. // check top of rect:
  16781. bx = rect.left();
  16782. by = rect.top();
  16783. mu = (by-base.y())/vec.y();
  16784. if (mu >= 0 && mu <= 1)
  16785. {
  16786. gamma = base.x()-bx + mu*vec.x();
  16787. if (gamma >= 0 && gamma <= rect.width())
  16788. pointVectors.append(QVector2D(bx+gamma, by));
  16789. }
  16790. // check bottom of rect:
  16791. bx = rect.left();
  16792. by = rect.bottom();
  16793. mu = (by-base.y())/vec.y();
  16794. if (mu >= 0 && mu <= 1)
  16795. {
  16796. gamma = base.x()-bx + mu*vec.x();
  16797. if (gamma >= 0 && gamma <= rect.width())
  16798. pointVectors.append(QVector2D(bx+gamma, by));
  16799. }
  16800. }
  16801. if (!qFuzzyIsNull(vec.x())) // line is not vertical
  16802. {
  16803. // check left of rect:
  16804. bx = rect.left();
  16805. by = rect.top();
  16806. mu = (bx-base.x())/vec.x();
  16807. if (mu >= 0 && mu <= 1)
  16808. {
  16809. gamma = base.y()-by + mu*vec.y();
  16810. if (gamma >= 0 && gamma <= rect.height())
  16811. pointVectors.append(QVector2D(bx, by+gamma));
  16812. }
  16813. // check right of rect:
  16814. bx = rect.right();
  16815. by = rect.top();
  16816. mu = (bx-base.x())/vec.x();
  16817. if (mu >= 0 && mu <= 1)
  16818. {
  16819. gamma = base.y()-by + mu*vec.y();
  16820. if (gamma >= 0 && gamma <= rect.height())
  16821. pointVectors.append(QVector2D(bx, by+gamma));
  16822. }
  16823. }
  16824. if (containsStart)
  16825. pointVectors.append(start);
  16826. if (containsEnd)
  16827. pointVectors.append(end);
  16828. // evaluate points:
  16829. if (pointVectors.size() == 2)
  16830. {
  16831. result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
  16832. } else if (pointVectors.size() > 2)
  16833. {
  16834. // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
  16835. double distSqrMax = 0;
  16836. QVector2D pv1, pv2;
  16837. for (int i=0; i<pointVectors.size()-1; ++i)
  16838. {
  16839. for (int k=i+1; k<pointVectors.size(); ++k)
  16840. {
  16841. double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
  16842. if (distSqr > distSqrMax)
  16843. {
  16844. pv1 = pointVectors.at(i);
  16845. pv2 = pointVectors.at(k);
  16846. distSqrMax = distSqr;
  16847. }
  16848. }
  16849. }
  16850. result.setPoints(pv1.toPointF(), pv2.toPointF());
  16851. }
  16852. return result;
  16853. }
  16854. /*! \internal
  16855. Returns the pen that should be used for drawing lines. Returns mPen when the
  16856. item is not selected and mSelectedPen when it is.
  16857. */
  16858. QPen QCPItemLine::mainPen() const
  16859. {
  16860. return mSelected ? mSelectedPen : mPen;
  16861. }
  16862. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16863. //////////////////// QCPItemCurve
  16864. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16865. /*! \class QCPItemCurve
  16866. \brief A curved line from one point to another
  16867. \image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are positions."
  16868. It has four positions, \a start and \a end, which define the end points of the line, and two
  16869. control points which define the direction the line exits from the start and the direction from
  16870. which it approaches the end: \a startDir and \a endDir.
  16871. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an
  16872. arrow.
  16873. Often it is desirable for the control points to stay at fixed relative positions to the start/end
  16874. point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start,
  16875. and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir.
  16876. */
  16877. /*!
  16878. Creates a curve item and sets default values.
  16879. The constructed item can be added to the plot with QCustomPlot::addItem.
  16880. */
  16881. QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) :
  16882. QCPAbstractItem(parentPlot),
  16883. start(createPosition("start")),
  16884. startDir(createPosition("startDir")),
  16885. endDir(createPosition("endDir")),
  16886. end(createPosition("end"))
  16887. {
  16888. start->setCoords(0, 0);
  16889. startDir->setCoords(0.5, 0);
  16890. endDir->setCoords(0, 0.5);
  16891. end->setCoords(1, 1);
  16892. setPen(QPen(Qt::black));
  16893. setSelectedPen(QPen(Qt::blue,2));
  16894. }
  16895. QCPItemCurve::~QCPItemCurve()
  16896. {
  16897. }
  16898. /*!
  16899. Sets the pen that will be used to draw the line
  16900. \see setSelectedPen
  16901. */
  16902. void QCPItemCurve::setPen(const QPen &pen)
  16903. {
  16904. mPen = pen;
  16905. }
  16906. /*!
  16907. Sets the pen that will be used to draw the line when selected
  16908. \see setPen, setSelected
  16909. */
  16910. void QCPItemCurve::setSelectedPen(const QPen &pen)
  16911. {
  16912. mSelectedPen = pen;
  16913. }
  16914. /*!
  16915. Sets the line ending style of the head. The head corresponds to the \a end position.
  16916. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  16917. a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
  16918. \see setTail
  16919. */
  16920. void QCPItemCurve::setHead(const QCPLineEnding &head)
  16921. {
  16922. mHead = head;
  16923. }
  16924. /*!
  16925. Sets the line ending style of the tail. The tail corresponds to the \a start position.
  16926. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  16927. a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
  16928. \see setHead
  16929. */
  16930. void QCPItemCurve::setTail(const QCPLineEnding &tail)
  16931. {
  16932. mTail = tail;
  16933. }
  16934. /* inherits documentation from base class */
  16935. double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  16936. {
  16937. Q_UNUSED(details)
  16938. if (onlySelectable && !mSelectable)
  16939. return -1;
  16940. QPointF startVec(start->pixelPoint());
  16941. QPointF startDirVec(startDir->pixelPoint());
  16942. QPointF endDirVec(endDir->pixelPoint());
  16943. QPointF endVec(end->pixelPoint());
  16944. QPainterPath cubicPath(startVec);
  16945. cubicPath.cubicTo(startDirVec, endDirVec, endVec);
  16946. QPolygonF polygon = cubicPath.toSubpathPolygons().first();
  16947. double minDistSqr = std::numeric_limits<double>::max();
  16948. for (int i=1; i<polygon.size(); ++i)
  16949. {
  16950. double distSqr = distSqrToLine(polygon.at(i-1), polygon.at(i), pos);
  16951. if (distSqr < minDistSqr)
  16952. minDistSqr = distSqr;
  16953. }
  16954. return qSqrt(minDistSqr);
  16955. }
  16956. /* inherits documentation from base class */
  16957. void QCPItemCurve::draw(QCPPainter *painter)
  16958. {
  16959. QPointF startVec(start->pixelPoint());
  16960. QPointF startDirVec(startDir->pixelPoint());
  16961. QPointF endDirVec(endDir->pixelPoint());
  16962. QPointF endVec(end->pixelPoint());
  16963. if (QVector2D(endVec-startVec).length() > 1e10f) // too large curves cause crash
  16964. return;
  16965. QPainterPath cubicPath(startVec);
  16966. cubicPath.cubicTo(startDirVec, endDirVec, endVec);
  16967. // paint visible segment, if existent:
  16968. QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
  16969. QRect cubicRect = cubicPath.controlPointRect().toRect();
  16970. if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position
  16971. cubicRect.adjust(0, 0, 1, 1);
  16972. if (clip.intersects(cubicRect))
  16973. {
  16974. painter->setPen(mainPen());
  16975. painter->drawPath(cubicPath);
  16976. painter->setBrush(Qt::SolidPattern);
  16977. if (mTail.style() != QCPLineEnding::esNone)
  16978. mTail.draw(painter, QVector2D(startVec), M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI);
  16979. if (mHead.style() != QCPLineEnding::esNone)
  16980. mHead.draw(painter, QVector2D(endVec), -cubicPath.angleAtPercent(1)/180.0*M_PI);
  16981. }
  16982. }
  16983. /*! \internal
  16984. Returns the pen that should be used for drawing lines. Returns mPen when the
  16985. item is not selected and mSelectedPen when it is.
  16986. */
  16987. QPen QCPItemCurve::mainPen() const
  16988. {
  16989. return mSelected ? mSelectedPen : mPen;
  16990. }
  16991. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16992. //////////////////// QCPItemRect
  16993. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16994. /*! \class QCPItemRect
  16995. \brief A rectangle
  16996. \image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions."
  16997. It has two positions, \a topLeft and \a bottomRight, which define the rectangle.
  16998. */
  16999. /*!
  17000. Creates a rectangle item and sets default values.
  17001. The constructed item can be added to the plot with QCustomPlot::addItem.
  17002. */
  17003. QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) :
  17004. QCPAbstractItem(parentPlot),
  17005. topLeft(createPosition("topLeft")),
  17006. bottomRight(createPosition("bottomRight")),
  17007. top(createAnchor("top", aiTop)),
  17008. topRight(createAnchor("topRight", aiTopRight)),
  17009. right(createAnchor("right", aiRight)),
  17010. bottom(createAnchor("bottom", aiBottom)),
  17011. bottomLeft(createAnchor("bottomLeft", aiBottomLeft)),
  17012. left(createAnchor("left", aiLeft))
  17013. {
  17014. topLeft->setCoords(0, 1);
  17015. bottomRight->setCoords(1, 0);
  17016. setPen(QPen(Qt::black));
  17017. setSelectedPen(QPen(Qt::blue,2));
  17018. setBrush(Qt::NoBrush);
  17019. setSelectedBrush(Qt::NoBrush);
  17020. }
  17021. QCPItemRect::~QCPItemRect()
  17022. {
  17023. }
  17024. /*!
  17025. Sets the pen that will be used to draw the line of the rectangle
  17026. \see setSelectedPen, setBrush
  17027. */
  17028. void QCPItemRect::setPen(const QPen &pen)
  17029. {
  17030. mPen = pen;
  17031. }
  17032. /*!
  17033. Sets the pen that will be used to draw the line of the rectangle when selected
  17034. \see setPen, setSelected
  17035. */
  17036. void QCPItemRect::setSelectedPen(const QPen &pen)
  17037. {
  17038. mSelectedPen = pen;
  17039. }
  17040. /*!
  17041. Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to
  17042. Qt::NoBrush.
  17043. \see setSelectedBrush, setPen
  17044. */
  17045. void QCPItemRect::setBrush(const QBrush &brush)
  17046. {
  17047. mBrush = brush;
  17048. }
  17049. /*!
  17050. Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a
  17051. brush to Qt::NoBrush.
  17052. \see setBrush
  17053. */
  17054. void QCPItemRect::setSelectedBrush(const QBrush &brush)
  17055. {
  17056. mSelectedBrush = brush;
  17057. }
  17058. /* inherits documentation from base class */
  17059. double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  17060. {
  17061. Q_UNUSED(details)
  17062. if (onlySelectable && !mSelectable)
  17063. return -1;
  17064. QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()).normalized();
  17065. bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
  17066. return rectSelectTest(rect, pos, filledRect);
  17067. }
  17068. /* inherits documentation from base class */
  17069. void QCPItemRect::draw(QCPPainter *painter)
  17070. {
  17071. QPointF p1 = topLeft->pixelPoint();
  17072. QPointF p2 = bottomRight->pixelPoint();
  17073. if (p1.toPoint() == p2.toPoint())
  17074. return;
  17075. QRectF rect = QRectF(p1, p2).normalized();
  17076. double clipPad = mainPen().widthF();
  17077. QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  17078. if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect
  17079. {
  17080. painter->setPen(mainPen());
  17081. painter->setBrush(mainBrush());
  17082. painter->drawRect(rect);
  17083. }
  17084. }
  17085. /* inherits documentation from base class */
  17086. QPointF QCPItemRect::anchorPixelPoint(int anchorId) const
  17087. {
  17088. QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint());
  17089. switch (anchorId)
  17090. {
  17091. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  17092. case aiTopRight: return rect.topRight();
  17093. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  17094. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  17095. case aiBottomLeft: return rect.bottomLeft();
  17096. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
  17097. }
  17098. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  17099. return QPointF();
  17100. }
  17101. /*! \internal
  17102. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  17103. and mSelectedPen when it is.
  17104. */
  17105. QPen QCPItemRect::mainPen() const
  17106. {
  17107. return mSelected ? mSelectedPen : mPen;
  17108. }
  17109. /*! \internal
  17110. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  17111. is not selected and mSelectedBrush when it is.
  17112. */
  17113. QBrush QCPItemRect::mainBrush() const
  17114. {
  17115. return mSelected ? mSelectedBrush : mBrush;
  17116. }
  17117. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17118. //////////////////// QCPItemText
  17119. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17120. /*! \class QCPItemText
  17121. \brief A text label
  17122. \image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions."
  17123. Its position is defined by the member \a position and the setting of \ref setPositionAlignment.
  17124. The latter controls which part of the text rect shall be aligned with \a position.
  17125. The text alignment itself (i.e. left, center, right) can be controlled with \ref
  17126. setTextAlignment.
  17127. The text may be rotated around the \a position point with \ref setRotation.
  17128. */
  17129. /*!
  17130. Creates a text item and sets default values.
  17131. The constructed item can be added to the plot with QCustomPlot::addItem.
  17132. */
  17133. QCPItemText::QCPItemText(QCustomPlot *parentPlot) :
  17134. QCPAbstractItem(parentPlot),
  17135. position(createPosition("position")),
  17136. topLeft(createAnchor("topLeft", aiTopLeft)),
  17137. top(createAnchor("top", aiTop)),
  17138. topRight(createAnchor("topRight", aiTopRight)),
  17139. right(createAnchor("right", aiRight)),
  17140. bottomRight(createAnchor("bottomRight", aiBottomRight)),
  17141. bottom(createAnchor("bottom", aiBottom)),
  17142. bottomLeft(createAnchor("bottomLeft", aiBottomLeft)),
  17143. left(createAnchor("left", aiLeft))
  17144. {
  17145. position->setCoords(0, 0);
  17146. setRotation(0);
  17147. setTextAlignment(Qt::AlignTop|Qt::AlignHCenter);
  17148. setPositionAlignment(Qt::AlignCenter);
  17149. setText("text");
  17150. setPen(Qt::NoPen);
  17151. setSelectedPen(Qt::NoPen);
  17152. setBrush(Qt::NoBrush);
  17153. setSelectedBrush(Qt::NoBrush);
  17154. setColor(Qt::black);
  17155. setSelectedColor(Qt::blue);
  17156. }
  17157. QCPItemText::~QCPItemText()
  17158. {
  17159. }
  17160. /*!
  17161. Sets the color of the text.
  17162. */
  17163. void QCPItemText::setColor(const QColor &color)
  17164. {
  17165. mColor = color;
  17166. }
  17167. /*!
  17168. Sets the color of the text that will be used when the item is selected.
  17169. */
  17170. void QCPItemText::setSelectedColor(const QColor &color)
  17171. {
  17172. mSelectedColor = color;
  17173. }
  17174. /*!
  17175. Sets the pen that will be used do draw a rectangular border around the text. To disable the
  17176. border, set \a pen to Qt::NoPen.
  17177. \see setSelectedPen, setBrush, setPadding
  17178. */
  17179. void QCPItemText::setPen(const QPen &pen)
  17180. {
  17181. mPen = pen;
  17182. }
  17183. /*!
  17184. Sets the pen that will be used do draw a rectangular border around the text, when the item is
  17185. selected. To disable the border, set \a pen to Qt::NoPen.
  17186. \see setPen
  17187. */
  17188. void QCPItemText::setSelectedPen(const QPen &pen)
  17189. {
  17190. mSelectedPen = pen;
  17191. }
  17192. /*!
  17193. Sets the brush that will be used do fill the background of the text. To disable the
  17194. background, set \a brush to Qt::NoBrush.
  17195. \see setSelectedBrush, setPen, setPadding
  17196. */
  17197. void QCPItemText::setBrush(const QBrush &brush)
  17198. {
  17199. mBrush = brush;
  17200. }
  17201. /*!
  17202. Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the
  17203. background, set \a brush to Qt::NoBrush.
  17204. \see setBrush
  17205. */
  17206. void QCPItemText::setSelectedBrush(const QBrush &brush)
  17207. {
  17208. mSelectedBrush = brush;
  17209. }
  17210. /*!
  17211. Sets the font of the text.
  17212. \see setSelectedFont, setColor
  17213. */
  17214. void QCPItemText::setFont(const QFont &font)
  17215. {
  17216. mFont = font;
  17217. }
  17218. /*!
  17219. Sets the font of the text that will be used when the item is selected.
  17220. \see setFont
  17221. */
  17222. void QCPItemText::setSelectedFont(const QFont &font)
  17223. {
  17224. mSelectedFont = font;
  17225. }
  17226. /*!
  17227. Sets the text that will be displayed. Multi-line texts are supported by inserting a line break
  17228. character, e.g. '\n'.
  17229. \see setFont, setColor, setTextAlignment
  17230. */
  17231. void QCPItemText::setText(const QString &text)
  17232. {
  17233. mText = text;
  17234. }
  17235. /*!
  17236. Sets which point of the text rect shall be aligned with \a position.
  17237. Examples:
  17238. \li If \a alignment is <tt>Qt::AlignHCenter | Qt::AlignTop</tt>, the text will be positioned such
  17239. that the top of the text rect will be horizontally centered on \a position.
  17240. \li If \a alignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt>, \a position will indicate the
  17241. bottom left corner of the text rect.
  17242. If you want to control the alignment of (multi-lined) text within the text rect, use \ref
  17243. setTextAlignment.
  17244. */
  17245. void QCPItemText::setPositionAlignment(Qt::Alignment alignment)
  17246. {
  17247. mPositionAlignment = alignment;
  17248. }
  17249. /*!
  17250. Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or Qt::AlignRight).
  17251. */
  17252. void QCPItemText::setTextAlignment(Qt::Alignment alignment)
  17253. {
  17254. mTextAlignment = alignment;
  17255. }
  17256. /*!
  17257. Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated
  17258. around \a position.
  17259. */
  17260. void QCPItemText::setRotation(double degrees)
  17261. {
  17262. mRotation = degrees;
  17263. }
  17264. /*!
  17265. Sets the distance between the border of the text rectangle and the text. The appearance (and
  17266. visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush.
  17267. */
  17268. void QCPItemText::setPadding(const QMargins &padding)
  17269. {
  17270. mPadding = padding;
  17271. }
  17272. /* inherits documentation from base class */
  17273. double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  17274. {
  17275. Q_UNUSED(details)
  17276. if (onlySelectable && !mSelectable)
  17277. return -1;
  17278. // The rect may be rotated, so we transform the actual clicked pos to the rotated
  17279. // coordinate system, so we can use the normal rectSelectTest function for non-rotated rects:
  17280. QPointF positionPixels(position->pixelPoint());
  17281. QTransform inputTransform;
  17282. inputTransform.translate(positionPixels.x(), positionPixels.y());
  17283. inputTransform.rotate(-mRotation);
  17284. inputTransform.translate(-positionPixels.x(), -positionPixels.y());
  17285. QPointF rotatedPos = inputTransform.map(pos);
  17286. QFontMetrics fontMetrics(mFont);
  17287. QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  17288. QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  17289. QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment);
  17290. textBoxRect.moveTopLeft(textPos.toPoint());
  17291. return rectSelectTest(textBoxRect, rotatedPos, true);
  17292. }
  17293. /* inherits documentation from base class */
  17294. void QCPItemText::draw(QCPPainter *painter)
  17295. {
  17296. QPointF pos(position->pixelPoint());
  17297. QTransform transform = painter->transform();
  17298. transform.translate(pos.x(), pos.y());
  17299. if (!qFuzzyIsNull(mRotation))
  17300. transform.rotate(mRotation);
  17301. painter->setFont(mainFont());
  17302. QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  17303. QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  17304. QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
  17305. textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top()));
  17306. textBoxRect.moveTopLeft(textPos.toPoint());
  17307. double clipPad = mainPen().widthF();
  17308. QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  17309. if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect())))
  17310. {
  17311. painter->setTransform(transform);
  17312. if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) ||
  17313. (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0))
  17314. {
  17315. painter->setPen(mainPen());
  17316. painter->setBrush(mainBrush());
  17317. painter->drawRect(textBoxRect);
  17318. }
  17319. painter->setBrush(Qt::NoBrush);
  17320. painter->setPen(QPen(mainColor()));
  17321. painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText);
  17322. }
  17323. }
  17324. /* inherits documentation from base class */
  17325. QPointF QCPItemText::anchorPixelPoint(int anchorId) const
  17326. {
  17327. // get actual rect points (pretty much copied from draw function):
  17328. QPointF pos(position->pixelPoint());
  17329. QTransform transform;
  17330. transform.translate(pos.x(), pos.y());
  17331. if (!qFuzzyIsNull(mRotation))
  17332. transform.rotate(mRotation);
  17333. QFontMetrics fontMetrics(mainFont());
  17334. QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  17335. QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  17336. QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
  17337. textBoxRect.moveTopLeft(textPos.toPoint());
  17338. QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect));
  17339. switch (anchorId)
  17340. {
  17341. case aiTopLeft: return rectPoly.at(0);
  17342. case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5;
  17343. case aiTopRight: return rectPoly.at(1);
  17344. case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5;
  17345. case aiBottomRight: return rectPoly.at(2);
  17346. case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5;
  17347. case aiBottomLeft: return rectPoly.at(3);
  17348. case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5;
  17349. }
  17350. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  17351. return QPointF();
  17352. }
  17353. /*! \internal
  17354. Returns the point that must be given to the QPainter::drawText function (which expects the top
  17355. left point of the text rect), according to the position \a pos, the text bounding box \a rect and
  17356. the requested \a positionAlignment.
  17357. For example, if \a positionAlignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt> the returned point
  17358. will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally
  17359. drawn at that point, the lower left corner of the resulting text rect is at \a pos.
  17360. */
  17361. QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const
  17362. {
  17363. if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop))
  17364. return pos;
  17365. QPointF result = pos; // start at top left
  17366. if (positionAlignment.testFlag(Qt::AlignHCenter))
  17367. result.rx() -= rect.width()/2.0;
  17368. else if (positionAlignment.testFlag(Qt::AlignRight))
  17369. result.rx() -= rect.width();
  17370. if (positionAlignment.testFlag(Qt::AlignVCenter))
  17371. result.ry() -= rect.height()/2.0;
  17372. else if (positionAlignment.testFlag(Qt::AlignBottom))
  17373. result.ry() -= rect.height();
  17374. return result;
  17375. }
  17376. /*! \internal
  17377. Returns the font that should be used for drawing text. Returns mFont when the item is not selected
  17378. and mSelectedFont when it is.
  17379. */
  17380. QFont QCPItemText::mainFont() const
  17381. {
  17382. return mSelected ? mSelectedFont : mFont;
  17383. }
  17384. /*! \internal
  17385. Returns the color that should be used for drawing text. Returns mColor when the item is not
  17386. selected and mSelectedColor when it is.
  17387. */
  17388. QColor QCPItemText::mainColor() const
  17389. {
  17390. return mSelected ? mSelectedColor : mColor;
  17391. }
  17392. /*! \internal
  17393. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  17394. and mSelectedPen when it is.
  17395. */
  17396. QPen QCPItemText::mainPen() const
  17397. {
  17398. return mSelected ? mSelectedPen : mPen;
  17399. }
  17400. /*! \internal
  17401. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  17402. is not selected and mSelectedBrush when it is.
  17403. */
  17404. QBrush QCPItemText::mainBrush() const
  17405. {
  17406. return mSelected ? mSelectedBrush : mBrush;
  17407. }
  17408. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17409. //////////////////// QCPItemEllipse
  17410. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17411. /*! \class QCPItemEllipse
  17412. \brief An ellipse
  17413. \image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions."
  17414. It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be drawn in.
  17415. */
  17416. /*!
  17417. Creates an ellipse item and sets default values.
  17418. The constructed item can be added to the plot with QCustomPlot::addItem.
  17419. */
  17420. QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) :
  17421. QCPAbstractItem(parentPlot),
  17422. topLeft(createPosition("topLeft")),
  17423. bottomRight(createPosition("bottomRight")),
  17424. topLeftRim(createAnchor("topLeftRim", aiTopLeftRim)),
  17425. top(createAnchor("top", aiTop)),
  17426. topRightRim(createAnchor("topRightRim", aiTopRightRim)),
  17427. right(createAnchor("right", aiRight)),
  17428. bottomRightRim(createAnchor("bottomRightRim", aiBottomRightRim)),
  17429. bottom(createAnchor("bottom", aiBottom)),
  17430. bottomLeftRim(createAnchor("bottomLeftRim", aiBottomLeftRim)),
  17431. left(createAnchor("left", aiLeft)),
  17432. center(createAnchor("center", aiCenter))
  17433. {
  17434. topLeft->setCoords(0, 1);
  17435. bottomRight->setCoords(1, 0);
  17436. setPen(QPen(Qt::black));
  17437. setSelectedPen(QPen(Qt::blue, 2));
  17438. setBrush(Qt::NoBrush);
  17439. setSelectedBrush(Qt::NoBrush);
  17440. }
  17441. QCPItemEllipse::~QCPItemEllipse()
  17442. {
  17443. }
  17444. /*!
  17445. Sets the pen that will be used to draw the line of the ellipse
  17446. \see setSelectedPen, setBrush
  17447. */
  17448. void QCPItemEllipse::setPen(const QPen &pen)
  17449. {
  17450. mPen = pen;
  17451. }
  17452. /*!
  17453. Sets the pen that will be used to draw the line of the ellipse when selected
  17454. \see setPen, setSelected
  17455. */
  17456. void QCPItemEllipse::setSelectedPen(const QPen &pen)
  17457. {
  17458. mSelectedPen = pen;
  17459. }
  17460. /*!
  17461. Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to
  17462. Qt::NoBrush.
  17463. \see setSelectedBrush, setPen
  17464. */
  17465. void QCPItemEllipse::setBrush(const QBrush &brush)
  17466. {
  17467. mBrush = brush;
  17468. }
  17469. /*!
  17470. Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a
  17471. brush to Qt::NoBrush.
  17472. \see setBrush
  17473. */
  17474. void QCPItemEllipse::setSelectedBrush(const QBrush &brush)
  17475. {
  17476. mSelectedBrush = brush;
  17477. }
  17478. /* inherits documentation from base class */
  17479. double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  17480. {
  17481. Q_UNUSED(details)
  17482. if (onlySelectable && !mSelectable)
  17483. return -1;
  17484. double result = -1;
  17485. QPointF p1 = topLeft->pixelPoint();
  17486. QPointF p2 = bottomRight->pixelPoint();
  17487. QPointF center((p1+p2)/2.0);
  17488. double a = qAbs(p1.x()-p2.x())/2.0;
  17489. double b = qAbs(p1.y()-p2.y())/2.0;
  17490. double x = pos.x()-center.x();
  17491. double y = pos.y()-center.y();
  17492. // distance to border:
  17493. double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b));
  17494. result = qAbs(c-1)*qSqrt(x*x+y*y);
  17495. // filled ellipse, allow click inside to count as hit:
  17496. if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
  17497. {
  17498. if (x*x/(a*a) + y*y/(b*b) <= 1)
  17499. result = mParentPlot->selectionTolerance()*0.99;
  17500. }
  17501. return result;
  17502. }
  17503. /* inherits documentation from base class */
  17504. void QCPItemEllipse::draw(QCPPainter *painter)
  17505. {
  17506. QPointF p1 = topLeft->pixelPoint();
  17507. QPointF p2 = bottomRight->pixelPoint();
  17508. if (p1.toPoint() == p2.toPoint())
  17509. return;
  17510. QRectF ellipseRect = QRectF(p1, p2).normalized();
  17511. QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
  17512. if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect
  17513. {
  17514. painter->setPen(mainPen());
  17515. painter->setBrush(mainBrush());
  17516. #ifdef __EXCEPTIONS
  17517. try // drawEllipse sometimes throws exceptions if ellipse is too big
  17518. {
  17519. #endif
  17520. painter->drawEllipse(ellipseRect);
  17521. #ifdef __EXCEPTIONS
  17522. } catch (...)
  17523. {
  17524. qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible";
  17525. setVisible(false);
  17526. }
  17527. #endif
  17528. }
  17529. }
  17530. /* inherits documentation from base class */
  17531. QPointF QCPItemEllipse::anchorPixelPoint(int anchorId) const
  17532. {
  17533. QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint());
  17534. switch (anchorId)
  17535. {
  17536. case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2);
  17537. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  17538. case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2);
  17539. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  17540. case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2);
  17541. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  17542. case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2);
  17543. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
  17544. case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5;
  17545. }
  17546. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  17547. return QPointF();
  17548. }
  17549. /*! \internal
  17550. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  17551. and mSelectedPen when it is.
  17552. */
  17553. QPen QCPItemEllipse::mainPen() const
  17554. {
  17555. return mSelected ? mSelectedPen : mPen;
  17556. }
  17557. /*! \internal
  17558. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  17559. is not selected and mSelectedBrush when it is.
  17560. */
  17561. QBrush QCPItemEllipse::mainBrush() const
  17562. {
  17563. return mSelected ? mSelectedBrush : mBrush;
  17564. }
  17565. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17566. //////////////////// QCPItemPixmap
  17567. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17568. /*! \class QCPItemPixmap
  17569. \brief An arbitrary pixmap
  17570. \image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions."
  17571. It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will
  17572. be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to
  17573. fit the rectangle or be drawn aligned to the topLeft position.
  17574. If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown
  17575. on the right side of the example image), the pixmap will be flipped in the respective
  17576. orientations.
  17577. */
  17578. /*!
  17579. Creates a rectangle item and sets default values.
  17580. The constructed item can be added to the plot with QCustomPlot::addItem.
  17581. */
  17582. QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) :
  17583. QCPAbstractItem(parentPlot),
  17584. topLeft(createPosition("topLeft")),
  17585. bottomRight(createPosition("bottomRight")),
  17586. top(createAnchor("top", aiTop)),
  17587. topRight(createAnchor("topRight", aiTopRight)),
  17588. right(createAnchor("right", aiRight)),
  17589. bottom(createAnchor("bottom", aiBottom)),
  17590. bottomLeft(createAnchor("bottomLeft", aiBottomLeft)),
  17591. left(createAnchor("left", aiLeft))
  17592. {
  17593. topLeft->setCoords(0, 1);
  17594. bottomRight->setCoords(1, 0);
  17595. setPen(Qt::NoPen);
  17596. setSelectedPen(QPen(Qt::blue));
  17597. setScaled(false, Qt::KeepAspectRatio);
  17598. }
  17599. QCPItemPixmap::~QCPItemPixmap()
  17600. {
  17601. }
  17602. /*!
  17603. Sets the pixmap that will be displayed.
  17604. */
  17605. void QCPItemPixmap::setPixmap(const QPixmap &pixmap)
  17606. {
  17607. mPixmap = pixmap;
  17608. if (mPixmap.isNull())
  17609. qDebug() << Q_FUNC_INFO << "pixmap is null";
  17610. }
  17611. /*!
  17612. Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a
  17613. bottomRight positions.
  17614. */
  17615. void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode)
  17616. {
  17617. mScaled = scaled;
  17618. mAspectRatioMode = aspectRatioMode;
  17619. updateScaledPixmap();
  17620. }
  17621. /*!
  17622. Sets the pen that will be used to draw a border around the pixmap.
  17623. \see setSelectedPen, setBrush
  17624. */
  17625. void QCPItemPixmap::setPen(const QPen &pen)
  17626. {
  17627. mPen = pen;
  17628. }
  17629. /*!
  17630. Sets the pen that will be used to draw a border around the pixmap when selected
  17631. \see setPen, setSelected
  17632. */
  17633. void QCPItemPixmap::setSelectedPen(const QPen &pen)
  17634. {
  17635. mSelectedPen = pen;
  17636. }
  17637. /* inherits documentation from base class */
  17638. double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  17639. {
  17640. Q_UNUSED(details)
  17641. if (onlySelectable && !mSelectable)
  17642. return -1;
  17643. return rectSelectTest(getFinalRect(), pos, true);
  17644. }
  17645. /* inherits documentation from base class */
  17646. void QCPItemPixmap::draw(QCPPainter *painter)
  17647. {
  17648. bool flipHorz = false;
  17649. bool flipVert = false;
  17650. QRect rect = getFinalRect(&flipHorz, &flipVert);
  17651. double clipPad = mainPen().style() == Qt::NoPen ? 0 : mainPen().widthF();
  17652. QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  17653. if (boundingRect.intersects(clipRect()))
  17654. {
  17655. updateScaledPixmap(rect, flipHorz, flipVert);
  17656. painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap);
  17657. QPen pen = mainPen();
  17658. if (pen.style() != Qt::NoPen)
  17659. {
  17660. painter->setPen(pen);
  17661. painter->setBrush(Qt::NoBrush);
  17662. painter->drawRect(rect);
  17663. }
  17664. }
  17665. }
  17666. /* inherits documentation from base class */
  17667. QPointF QCPItemPixmap::anchorPixelPoint(int anchorId) const
  17668. {
  17669. bool flipHorz;
  17670. bool flipVert;
  17671. QRect rect = getFinalRect(&flipHorz, &flipVert);
  17672. // we actually want denormal rects (negative width/height) here, so restore
  17673. // the flipped state:
  17674. if (flipHorz)
  17675. rect.adjust(rect.width(), 0, -rect.width(), 0);
  17676. if (flipVert)
  17677. rect.adjust(0, rect.height(), 0, -rect.height());
  17678. switch (anchorId)
  17679. {
  17680. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  17681. case aiTopRight: return rect.topRight();
  17682. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  17683. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  17684. case aiBottomLeft: return rect.bottomLeft();
  17685. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;;
  17686. }
  17687. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  17688. return QPointF();
  17689. }
  17690. /*! \internal
  17691. Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The
  17692. parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped
  17693. horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a
  17694. bottomRight.)
  17695. This function only creates the scaled pixmap when the buffered pixmap has a different size than
  17696. the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does
  17697. not cause expensive rescaling every time.
  17698. If scaling is disabled, sets mScaledPixmap to a null QPixmap.
  17699. */
  17700. void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert)
  17701. {
  17702. if (mPixmap.isNull())
  17703. return;
  17704. if (mScaled)
  17705. {
  17706. if (finalRect.isNull())
  17707. finalRect = getFinalRect(&flipHorz, &flipVert);
  17708. if (finalRect.size() != mScaledPixmap.size())
  17709. {
  17710. mScaledPixmap = mPixmap.scaled(finalRect.size(), mAspectRatioMode, Qt::SmoothTransformation);
  17711. if (flipHorz || flipVert)
  17712. mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert));
  17713. }
  17714. } else if (!mScaledPixmap.isNull())
  17715. mScaledPixmap = QPixmap();
  17716. }
  17717. /*! \internal
  17718. Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions
  17719. and scaling settings.
  17720. The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn
  17721. flipped horizontally or vertically in the returned rect. (The returned rect itself is always
  17722. normalized, i.e. the top left corner of the rect is actually further to the top/left than the
  17723. bottom right corner). This is the case when the item position \a topLeft is further to the
  17724. bottom/right than \a bottomRight.
  17725. If scaling is disabled, returns a rect with size of the original pixmap and the top left corner
  17726. aligned with the item position \a topLeft. The position \a bottomRight is ignored.
  17727. */
  17728. QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const
  17729. {
  17730. QRect result;
  17731. bool flipHorz = false;
  17732. bool flipVert = false;
  17733. QPoint p1 = topLeft->pixelPoint().toPoint();
  17734. QPoint p2 = bottomRight->pixelPoint().toPoint();
  17735. if (p1 == p2)
  17736. return QRect(p1, QSize(0, 0));
  17737. if (mScaled)
  17738. {
  17739. QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y());
  17740. QPoint topLeft = p1;
  17741. if (newSize.width() < 0)
  17742. {
  17743. flipHorz = true;
  17744. newSize.rwidth() *= -1;
  17745. topLeft.setX(p2.x());
  17746. }
  17747. if (newSize.height() < 0)
  17748. {
  17749. flipVert = true;
  17750. newSize.rheight() *= -1;
  17751. topLeft.setY(p2.y());
  17752. }
  17753. QSize scaledSize = mPixmap.size();
  17754. scaledSize.scale(newSize, mAspectRatioMode);
  17755. result = QRect(topLeft, scaledSize);
  17756. } else
  17757. {
  17758. result = QRect(p1, mPixmap.size());
  17759. }
  17760. if (flippedHorz)
  17761. *flippedHorz = flipHorz;
  17762. if (flippedVert)
  17763. *flippedVert = flipVert;
  17764. return result;
  17765. }
  17766. /*! \internal
  17767. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  17768. and mSelectedPen when it is.
  17769. */
  17770. QPen QCPItemPixmap::mainPen() const
  17771. {
  17772. return mSelected ? mSelectedPen : mPen;
  17773. }
  17774. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17775. //////////////////// QCPItemTracer
  17776. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17777. /*! \class QCPItemTracer
  17778. \brief Item that sticks to QCPGraph data points
  17779. \image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs are positions."
  17780. The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt
  17781. the coordinate axes of the graph and update its \a position to be on the graph's data. This means
  17782. the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a
  17783. QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a
  17784. position will have no effect because they will be overriden in the next redraw (this is when the
  17785. coordinate update happens).
  17786. If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will
  17787. stay at the corresponding end of the graph.
  17788. With \ref setInterpolating you may specify whether the tracer may only stay exactly on data
  17789. points or whether it interpolates data points linearly, if given a key that lies between two data
  17790. points of the graph.
  17791. The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer
  17792. have no own visual appearance (set the style to \ref tsNone), and just connect other item
  17793. positions to the tracer \a position (used as an anchor) via \ref
  17794. QCPItemPosition::setParentAnchor.
  17795. \note The tracer position is only automatically updated upon redraws. So when the data of the
  17796. graph changes and immediately afterwards (without a redraw) the a position coordinates of the
  17797. tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref
  17798. updatePosition must be called manually, prior to reading the tracer coordinates.
  17799. */
  17800. /*!
  17801. Creates a tracer item and sets default values.
  17802. The constructed item can be added to the plot with QCustomPlot::addItem.
  17803. */
  17804. QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) :
  17805. QCPAbstractItem(parentPlot),
  17806. position(createPosition("position")),
  17807. mGraph(0)
  17808. {
  17809. position->setCoords(0, 0);
  17810. setBrush(Qt::NoBrush);
  17811. setSelectedBrush(Qt::NoBrush);
  17812. setPen(QPen(Qt::black));
  17813. setSelectedPen(QPen(Qt::blue, 2));
  17814. setStyle(tsCrosshair);
  17815. setSize(6);
  17816. setInterpolating(false);
  17817. setGraphKey(0);
  17818. }
  17819. QCPItemTracer::~QCPItemTracer()
  17820. {
  17821. }
  17822. /*!
  17823. Sets the pen that will be used to draw the line of the tracer
  17824. \see setSelectedPen, setBrush
  17825. */
  17826. void QCPItemTracer::setPen(const QPen &pen)
  17827. {
  17828. mPen = pen;
  17829. }
  17830. /*!
  17831. Sets the pen that will be used to draw the line of the tracer when selected
  17832. \see setPen, setSelected
  17833. */
  17834. void QCPItemTracer::setSelectedPen(const QPen &pen)
  17835. {
  17836. mSelectedPen = pen;
  17837. }
  17838. /*!
  17839. Sets the brush that will be used to draw any fills of the tracer
  17840. \see setSelectedBrush, setPen
  17841. */
  17842. void QCPItemTracer::setBrush(const QBrush &brush)
  17843. {
  17844. mBrush = brush;
  17845. }
  17846. /*!
  17847. Sets the brush that will be used to draw any fills of the tracer, when selected.
  17848. \see setBrush, setSelected
  17849. */
  17850. void QCPItemTracer::setSelectedBrush(const QBrush &brush)
  17851. {
  17852. mSelectedBrush = brush;
  17853. }
  17854. /*!
  17855. Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare
  17856. does, \ref tsCrosshair does not).
  17857. */
  17858. void QCPItemTracer::setSize(double size)
  17859. {
  17860. mSize = size;
  17861. }
  17862. /*!
  17863. Sets the style/visual appearance of the tracer.
  17864. If you only want to use the tracer \a position as an anchor for other items, set \a style to
  17865. \ref tsNone.
  17866. */
  17867. void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style)
  17868. {
  17869. mStyle = style;
  17870. }
  17871. /*!
  17872. Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type
  17873. QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph.
  17874. To free the tracer from any graph, set \a graph to 0. The tracer \a position can then be placed
  17875. freely like any other item position. This is the state the tracer will assume when its graph gets
  17876. deleted while still attached to it.
  17877. \see setGraphKey
  17878. */
  17879. void QCPItemTracer::setGraph(QCPGraph *graph)
  17880. {
  17881. if (graph)
  17882. {
  17883. if (graph->parentPlot() == mParentPlot)
  17884. {
  17885. position->setType(QCPItemPosition::ptPlotCoords);
  17886. position->setAxes(graph->keyAxis(), graph->valueAxis());
  17887. mGraph = graph;
  17888. updatePosition();
  17889. } else
  17890. qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item";
  17891. } else
  17892. {
  17893. mGraph = 0;
  17894. }
  17895. }
  17896. /*!
  17897. Sets the key of the graph's data point the tracer will be positioned at. This is the only free
  17898. coordinate of a tracer when attached to a graph.
  17899. Depending on \ref setInterpolating, the tracer will be either positioned on the data point
  17900. closest to \a key, or will stay exactly at \a key and interpolate the value linearly.
  17901. \see setGraph, setInterpolating
  17902. */
  17903. void QCPItemTracer::setGraphKey(double key)
  17904. {
  17905. mGraphKey = key;
  17906. }
  17907. /*!
  17908. Sets whether the value of the graph's data points shall be interpolated, when positioning the
  17909. tracer.
  17910. If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on
  17911. the data point of the graph which is closest to the key, but which is not necessarily exactly
  17912. there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and
  17913. the appropriate value will be interpolated from the graph's data points linearly.
  17914. \see setGraph, setGraphKey
  17915. */
  17916. void QCPItemTracer::setInterpolating(bool enabled)
  17917. {
  17918. mInterpolating = enabled;
  17919. }
  17920. /* inherits documentation from base class */
  17921. double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  17922. {
  17923. Q_UNUSED(details)
  17924. if (onlySelectable && !mSelectable)
  17925. return -1;
  17926. QPointF center(position->pixelPoint());
  17927. double w = mSize/2.0;
  17928. QRect clip = clipRect();
  17929. switch (mStyle)
  17930. {
  17931. case tsNone: return -1;
  17932. case tsPlus:
  17933. {
  17934. if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  17935. return qSqrt(qMin(distSqrToLine(center+QPointF(-w, 0), center+QPointF(w, 0), pos),
  17936. distSqrToLine(center+QPointF(0, -w), center+QPointF(0, w), pos)));
  17937. break;
  17938. }
  17939. case tsCrosshair:
  17940. {
  17941. return qSqrt(qMin(distSqrToLine(QPointF(clip.left(), center.y()), QPointF(clip.right(), center.y()), pos),
  17942. distSqrToLine(QPointF(center.x(), clip.top()), QPointF(center.x(), clip.bottom()), pos)));
  17943. }
  17944. case tsCircle:
  17945. {
  17946. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  17947. {
  17948. // distance to border:
  17949. double centerDist = QVector2D(center-pos).length();
  17950. double circleLine = w;
  17951. double result = qAbs(centerDist-circleLine);
  17952. // filled ellipse, allow click inside to count as hit:
  17953. if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
  17954. {
  17955. if (centerDist <= circleLine)
  17956. result = mParentPlot->selectionTolerance()*0.99;
  17957. }
  17958. return result;
  17959. }
  17960. break;
  17961. }
  17962. case tsSquare:
  17963. {
  17964. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  17965. {
  17966. QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w));
  17967. bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
  17968. return rectSelectTest(rect, pos, filledRect);
  17969. }
  17970. break;
  17971. }
  17972. }
  17973. return -1;
  17974. }
  17975. /* inherits documentation from base class */
  17976. void QCPItemTracer::draw(QCPPainter *painter)
  17977. {
  17978. updatePosition();
  17979. if (mStyle == tsNone)
  17980. return;
  17981. painter->setPen(mainPen());
  17982. painter->setBrush(mainBrush());
  17983. QPointF center(position->pixelPoint());
  17984. double w = mSize/2.0;
  17985. QRect clip = clipRect();
  17986. switch (mStyle)
  17987. {
  17988. case tsNone: return;
  17989. case tsPlus:
  17990. {
  17991. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  17992. {
  17993. painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0)));
  17994. painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w)));
  17995. }
  17996. break;
  17997. }
  17998. case tsCrosshair:
  17999. {
  18000. if (center.y() > clip.top() && center.y() < clip.bottom())
  18001. painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y()));
  18002. if (center.x() > clip.left() && center.x() < clip.right())
  18003. painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom()));
  18004. break;
  18005. }
  18006. case tsCircle:
  18007. {
  18008. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  18009. painter->drawEllipse(center, w, w);
  18010. break;
  18011. }
  18012. case tsSquare:
  18013. {
  18014. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  18015. painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w)));
  18016. break;
  18017. }
  18018. }
  18019. }
  18020. /*!
  18021. If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a
  18022. position to reside on the graph data, depending on the configured key (\ref setGraphKey).
  18023. It is called automatically on every redraw and normally doesn't need to be called manually. One
  18024. exception is when you want to read the tracer coordinates via \a position and are not sure that
  18025. the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw.
  18026. In that situation, call this function before accessing \a position, to make sure you don't get
  18027. out-of-date coordinates.
  18028. If there is no graph set on this tracer, this function does nothing.
  18029. */
  18030. void QCPItemTracer::updatePosition()
  18031. {
  18032. if (mGraph)
  18033. {
  18034. if (mParentPlot->hasPlottable(mGraph))
  18035. {
  18036. if (mGraph->data()->size() > 1)
  18037. {
  18038. QCPDataMap::const_iterator first = mGraph->data()->constBegin();
  18039. QCPDataMap::const_iterator last = mGraph->data()->constEnd()-1;
  18040. if (mGraphKey < first.key())
  18041. position->setCoords(first.key(), first.value().value);
  18042. else if (mGraphKey > last.key())
  18043. position->setCoords(last.key(), last.value().value);
  18044. else
  18045. {
  18046. QCPDataMap::const_iterator it = mGraph->data()->lowerBound(mGraphKey);
  18047. if (it != first) // mGraphKey is somewhere between iterators
  18048. {
  18049. QCPDataMap::const_iterator prevIt = it-1;
  18050. if (mInterpolating)
  18051. {
  18052. // interpolate between iterators around mGraphKey:
  18053. double slope = 0;
  18054. if (!qFuzzyCompare((double)it.key(), (double)prevIt.key()))
  18055. slope = (it.value().value-prevIt.value().value)/(it.key()-prevIt.key());
  18056. position->setCoords(mGraphKey, (mGraphKey-prevIt.key())*slope+prevIt.value().value);
  18057. } else
  18058. {
  18059. // find iterator with key closest to mGraphKey:
  18060. if (mGraphKey < (prevIt.key()+it.key())*0.5)
  18061. it = prevIt;
  18062. position->setCoords(it.key(), it.value().value);
  18063. }
  18064. } else // mGraphKey is exactly on first iterator
  18065. position->setCoords(it.key(), it.value().value);
  18066. }
  18067. } else if (mGraph->data()->size() == 1)
  18068. {
  18069. QCPDataMap::const_iterator it = mGraph->data()->constBegin();
  18070. position->setCoords(it.key(), it.value().value);
  18071. } else
  18072. qDebug() << Q_FUNC_INFO << "graph has no data";
  18073. } else
  18074. qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)";
  18075. }
  18076. }
  18077. /*! \internal
  18078. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  18079. and mSelectedPen when it is.
  18080. */
  18081. QPen QCPItemTracer::mainPen() const
  18082. {
  18083. return mSelected ? mSelectedPen : mPen;
  18084. }
  18085. /*! \internal
  18086. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  18087. is not selected and mSelectedBrush when it is.
  18088. */
  18089. QBrush QCPItemTracer::mainBrush() const
  18090. {
  18091. return mSelected ? mSelectedBrush : mBrush;
  18092. }
  18093. ////////////////////////////////////////////////////////////////////////////////////////////////////
  18094. //////////////////// QCPItemBracket
  18095. ////////////////////////////////////////////////////////////////////////////////////////////////////
  18096. /*! \class QCPItemBracket
  18097. \brief A bracket for referencing/highlighting certain parts in the plot.
  18098. \image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs are positions."
  18099. It has two positions, \a left and \a right, which define the span of the bracket. If \a left is
  18100. actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the
  18101. example image.
  18102. The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket
  18103. stretches away from the embraced span, can be controlled with \ref setLength.
  18104. \image html QCPItemBracket-length.png
  18105. <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
  18106. bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
  18107. It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine
  18108. or QCPItemCurve) or a text label (QCPItemText), to the bracket.
  18109. */
  18110. /*!
  18111. Creates a bracket item and sets default values.
  18112. The constructed item can be added to the plot with QCustomPlot::addItem.
  18113. */
  18114. QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) :
  18115. QCPAbstractItem(parentPlot),
  18116. left(createPosition("left")),
  18117. right(createPosition("right")),
  18118. center(createAnchor("center", aiCenter))
  18119. {
  18120. left->setCoords(0, 0);
  18121. right->setCoords(1, 1);
  18122. setPen(QPen(Qt::black));
  18123. setSelectedPen(QPen(Qt::blue, 2));
  18124. setLength(8);
  18125. setStyle(bsCalligraphic);
  18126. }
  18127. QCPItemBracket::~QCPItemBracket()
  18128. {
  18129. }
  18130. /*!
  18131. Sets the pen that will be used to draw the bracket.
  18132. Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the
  18133. stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use
  18134. \ref setLength, which has a similar effect.
  18135. \see setSelectedPen
  18136. */
  18137. void QCPItemBracket::setPen(const QPen &pen)
  18138. {
  18139. mPen = pen;
  18140. }
  18141. /*!
  18142. Sets the pen that will be used to draw the bracket when selected
  18143. \see setPen, setSelected
  18144. */
  18145. void QCPItemBracket::setSelectedPen(const QPen &pen)
  18146. {
  18147. mSelectedPen = pen;
  18148. }
  18149. /*!
  18150. Sets the \a length in pixels how far the bracket extends in the direction towards the embraced
  18151. span of the bracket (i.e. perpendicular to the <i>left</i>-<i>right</i>-direction)
  18152. \image html QCPItemBracket-length.png
  18153. <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
  18154. bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
  18155. */
  18156. void QCPItemBracket::setLength(double length)
  18157. {
  18158. mLength = length;
  18159. }
  18160. /*!
  18161. Sets the style of the bracket, i.e. the shape/visual appearance.
  18162. \see setPen
  18163. */
  18164. void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style)
  18165. {
  18166. mStyle = style;
  18167. }
  18168. /* inherits documentation from base class */
  18169. double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  18170. {
  18171. Q_UNUSED(details)
  18172. if (onlySelectable && !mSelectable)
  18173. return -1;
  18174. QVector2D leftVec(left->pixelPoint());
  18175. QVector2D rightVec(right->pixelPoint());
  18176. if (leftVec.toPoint() == rightVec.toPoint())
  18177. return -1;
  18178. QVector2D widthVec = (rightVec-leftVec)*0.5f;
  18179. QVector2D lengthVec(-widthVec.y(), widthVec.x());
  18180. lengthVec = lengthVec.normalized()*mLength;
  18181. QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec;
  18182. return qSqrt(distSqrToLine((centerVec-widthVec).toPointF(), (centerVec+widthVec).toPointF(), pos));
  18183. }
  18184. /* inherits documentation from base class */
  18185. void QCPItemBracket::draw(QCPPainter *painter)
  18186. {
  18187. QVector2D leftVec(left->pixelPoint());
  18188. QVector2D rightVec(right->pixelPoint());
  18189. if (leftVec.toPoint() == rightVec.toPoint())
  18190. return;
  18191. QVector2D widthVec = (rightVec-leftVec)*0.5f;
  18192. QVector2D lengthVec(-widthVec.y(), widthVec.x());
  18193. lengthVec = lengthVec.normalized()*mLength;
  18194. QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec;
  18195. QPolygon boundingPoly;
  18196. boundingPoly << leftVec.toPoint() << rightVec.toPoint()
  18197. << (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint();
  18198. QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
  18199. if (clip.intersects(boundingPoly.boundingRect()))
  18200. {
  18201. painter->setPen(mainPen());
  18202. switch (mStyle)
  18203. {
  18204. case bsSquare:
  18205. {
  18206. painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF());
  18207. painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
  18208. painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  18209. break;
  18210. }
  18211. case bsRound:
  18212. {
  18213. painter->setBrush(Qt::NoBrush);
  18214. QPainterPath path;
  18215. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  18216. path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF());
  18217. path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  18218. painter->drawPath(path);
  18219. break;
  18220. }
  18221. case bsCurly:
  18222. {
  18223. painter->setBrush(Qt::NoBrush);
  18224. QPainterPath path;
  18225. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  18226. path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+lengthVec).toPointF(), centerVec.toPointF());
  18227. path.cubicTo((centerVec-0.4f*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  18228. painter->drawPath(path);
  18229. break;
  18230. }
  18231. case bsCalligraphic:
  18232. {
  18233. painter->setPen(Qt::NoPen);
  18234. painter->setBrush(QBrush(mainPen().color()));
  18235. QPainterPath path;
  18236. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  18237. path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+0.8f*lengthVec).toPointF(), centerVec.toPointF());
  18238. path.cubicTo((centerVec-0.4f*widthVec+0.8f*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  18239. path.cubicTo((centerVec-widthVec-lengthVec*0.5f).toPointF(), (centerVec-0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+lengthVec*0.2f).toPointF());
  18240. path.cubicTo((centerVec+0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5f).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
  18241. painter->drawPath(path);
  18242. break;
  18243. }
  18244. }
  18245. }
  18246. }
  18247. /* inherits documentation from base class */
  18248. QPointF QCPItemBracket::anchorPixelPoint(int anchorId) const
  18249. {
  18250. QVector2D leftVec(left->pixelPoint());
  18251. QVector2D rightVec(right->pixelPoint());
  18252. if (leftVec.toPoint() == rightVec.toPoint())
  18253. return leftVec.toPointF();
  18254. QVector2D widthVec = (rightVec-leftVec)*0.5f;
  18255. QVector2D lengthVec(-widthVec.y(), widthVec.x());
  18256. lengthVec = lengthVec.normalized()*mLength;
  18257. QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec;
  18258. switch (anchorId)
  18259. {
  18260. case aiCenter:
  18261. return centerVec.toPointF();
  18262. }
  18263. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  18264. return QPointF();
  18265. }
  18266. /*! \internal
  18267. Returns the pen that should be used for drawing lines. Returns mPen when the
  18268. item is not selected and mSelectedPen when it is.
  18269. */
  18270. QPen QCPItemBracket::mainPen() const
  18271. {
  18272. return mSelected ? mSelectedPen : mPen;
  18273. }