Tải bản đầy đủ - 0 (trang)
Chapter 19. Look and Feel Customization

Chapter 19. Look and Feel Customization

Tải bản đầy đủ - 0trang

creatingcustomwidgets.Inthischapter,wewillreviewthelast

twoapproaches.Wewillpresenttwocustomstyles:theCandy

style,specifiedasastylesheet,andtheBronzestyle,

implementedasaQStylesubclass(seeFigure19.1).Tokeep

theexamplestoamanageablesize,bothstylesfocusona

carefullychosensubsetofQt'swidgets.

Figure19.1.Thecustomstylespresentedinthischapter

[Viewfullsizeimage]



UsingQtStyleSheets

QtstylesheetsarestronglyinspiredbyCSSbutadaptedto

workonwidgets.Astylesheetconsistsofstylerulesthataffect

therenderingofawidget.Theserulesarespecifiedasplain

text.Sincestylesheetsareparsedatrun-time,wecaneasily

experimentwithdifferentdesignsbyspecifyingastylesheetfor

aQtapplicationusingthe-stylesheetfile.qsscommandlineoption,byusingQtDesigner'sstylesheeteditor,orby

embeddingaQTextEditinsideourapplicationduring

development.

StylesheetsareappliedontopofthecurrentlyactiveQStyle

(e.g.,QWindowsVistaStyleorQPlastiqueStyle).[*]Because

creatingstylesheetsdoesn'tinvolveanysubclassing,theyare

idealforminorcustomizationstoexistingwidgets.Forexample,



supposewewanttouseyellowasthebackgroundcolorofall

QLineEditsinanapplication.Thiscouldbeaccomplishedusing

thefollowingstylesheet:

[*]StylesheetsarenotsupportedforQMacStyleinQt4.3.Itisexpectedthat



thiswillbeaddressedinafuturerelease.



QLineEdit{

background-color:yellow;

}



InCSS-speak,QLineEditiscalledaselector,backgroundcolorisanattribute,andyellowisavalue.

Forthiskindofcustomization,usingstylesheetsproducesmore

reliableresultsthanfiddlingwiththewidget'spalette.Thisis

becauseaQPalette'sentries(Base,Button,Highlight,etc.)

areuseddifferentlybydifferentstyles.Forexample,

QWindowsStyleusestheBasepaletteentrytofillthe

backgroundofaread-onlycombobox,whereas

QPlastiqueStyleusestheButtonentryforthispurpose.

Furthermore,certainstylesusehard-codedimagestorender

certainelements,by-passingthepaletteentirely.Incontrast,

stylesheetsguaranteethatnomatterwhichQStyleisactive,

thecolorsspecifiedwillbetheonesused.

QApplication::setStyleSheet()setsastylesheetforthe

entireapplication:



qApp->setStyleSheet("QLineEdit{background-color:yellow;}");



Wecanalsosetastylesheetonawidgetanditschildrenusing

QWidget::setStyleSheet().Forexample:



dialog->setStyleSheet("QLineEdit{background-color:yellow;}"



IfwesetthestylesheetdirectlyonaQLineEdit,wecanomit

boththeQLineEditselectorandthebraces:

lineEdit->setStyleSheet("background-color:yellow;");



Sofar,wehavesetonlyasinglepropertyonasingleclassof

widget.Inpractice,stylerulesareoftencombined.For

example,thefollowingrulesetstheforegroundandbackground

colorsofsixwidgetclassesandtheirsubclasses:



QCheckBox,QComboBox,QLineEdit,QListView,QRadioButton,QSpin

color:#050505;

background-color:yellow;

}



Colorscanbespecifiedbyname,byanHTML-stylestringin

#RRGGBBformat,orbyanRGBorRGBAvalue:

QLineEdit{

color:rgb(0,88,152);

background-color:rgba(97%,80%,9%,50%);

}



Whenusingcolornames,wecanuseanynamethatis

recognizedbytheQColor::setNamedColor()function.For

RGB,wemustspecifyared,agreen,andabluecomponent,

eachonascaleof0to255or0%to100%.RGBAadditionally

letsusspecifyanalphavalueasthefourthcomponentofthe

color,whichcorrespondstothecolor'sopacity.Insteadofa

uniformcolor,wecanalsospecifyapaletteentryoragradient:

QLineEdit{



color:palette(Base);

background-color:qlineargradient(x1:0,y1:0,x2:1,y2:

stop:0white,stop:0.4

stop:1green);

}



ThethreetypesofgradientsdescribedinChapter8(p.184)are

availableasqlineargradient(),qradialgradient(),and

qconicalgradient().Thesyntaxisexplainedinthestylesheet

referencedocumentation.

Usingthebackground-imageproperty,wecanspecifyanimage

forthebackground:

QLineEdit{

color:rgb(0,88,152);

background-image:url(:/images/yellow-bg.png);

}



Bydefault,thebackgroundimageisrootedinthetop-left

cornerofthewidget(excludinganymarginspecifiedusing

margin)andisrepeatedhorizontallyandverticallytofillthe

entirewidget.Thiscanbeconfiguredusingthebackgroundpositionandbackground-repeatattributes.Forexample:

QLineEdit{

background-image:url(:/images/yellow-bg.png);

background-position:topright;

background-repeat:repeat-y;

}



Ifwespecifybothabackgroundimageandabackgroundcolor,

thebackgroundcolorwillshinethroughthesemi-transparent



areasoftheimage.

Sofar,alloftheselectorswehaveusedhavebeenclassnames.

Thereareseveralotherselectorsthatwecanuse;theyare

listedinFigure19.2.Forexample,ifwewanttousespecific

foregroundcolorsforOKandCancelbuttons,wecanwrite

Figure19.2.Stylesheetselectors

Selector



Example



MatchedWidgets



Universal



*



Anywidget



Type



QDial



Instancesofagivenclass,including

subclasses



Class



.QDial



Instancesofagivenclass,excluding

subclasses



ID



QDial#ageDial Widgetswiththegivenobjectname



Qtproperty QDial[y="0"]

Child



QFrame>

QDial



Descendant QFrameQDial



Widgetswithcertainpropertiessetto

givenvalues

Widgetsthataredirectchildrenofthe

givenwidgets

Widgetsthataredescendantsofthegiven

widgets



QPushButton[text="OK"]{

color:green;

}

QPushButton[text="Cancel"]{

color:red;

}



ThisselectorsyntaxworksforanyQtproperty,althoughwe



mustbearinmindthatstylesheetsdon'tnoticewhena

propertychangesbehindtheirback.Selectorscanalsobe

combinedinvariousways;forexample,toselectall

QPushButtonscalled"okButton"whosexandypropertiesare0

andthataredirectchildrenofaQFramecalled"frame",wecan

write

QFrame#frame>QPushButton[x="0"][y="0"]#okButton{

...

}



Inanapplicationthatpresentslargeformswithlotsofline

editorsandcomboboxes,suchasthoseusedbyvarious

bureaucracies,itiscommontouseayellowbackgroundcolor

formandatoryfields.Let'ssupposethatwewanttoapplythis

conventiontoourapplication.First,wewouldstartwiththis

stylesheet:

*[mandatoryField="true"]{

background-color:yellow;

}



AlthoughthereisnomandatoryFieldpropertydefined

anywhereinQt,wecaneasilycreateonebycalling

QObject::setProperty().StartingwithQt4.2,settingthe

valueofanon-existentpropertydynamicallycreatesthat

property.Forexample:

nameLineEdit->setProperty("mandatoryField",true);

genderComboBox->setProperty("mandatoryField",true);

ageSpinBox->setProperty("mandatoryField",true);



Stylesheetsarenotonlyusefulforcontrollingcolors.Theyalso



letusperformvariousadjustmentstothesizeandpositionof

widgetelements.Forexample,thefollowingrulescanbeused

toincreasethesizeofcheckboxesandradiobuttonindicatorsto

20x20pixels,andensurethatthereare8pixelsbetweenthe

indicatorandtheassociatedtext:

QCheckBox::indicator,QRadioButton::indicator{

width:20px;

height:20px;

}

QCheckBox,QRadioButton{

spacing:8px;

}



Noticetheselectorsyntaxforthefirstrule.Hadwewrittenonly

QCheckBoxinsteadofQCheckBox::indicator,wewouldhave

specifiedthedimensionsoftheentirewidgetinsteadofthoseof

theindicator.ThefirstruleisillustratedinFigure19.3.

Figure19.3.SettingaQCheckBox'sindicatorsize



Subcontrolssuchas::indicatorcanbestyledinmuchthe

samewayaswidgets.Figure19.4listssomeofthesubcontrols

supportedbyQt.

Figure19.4.Themostcommoncustomizable



Figure19.4.Themostcommoncustomizable

subcontrols

Subcontrol



Description



::indicator



Acheckbox,radiobutton,checkablemenu

item,orcheckablegroupbox'sindicator



::menuindicator



Apushbutton'smenuindicator



::item



Amenu,menubar,orstatusbaritem



::up-button



Aspinboxorscrollbar'supbutton



::down-button



Aspinboxorscrollbar'sdownbutton



::up-arrow



Aspinbox,scrollbar,orheaderview'sup

arrow



::down-arrow



Aspinbox,scrollbar,headerview,or

combobox'sdownarrow



::drop-down



Acombobox'sdrop-downarrow



::title



Agroupbox'stitle



Inadditiontosubcontrols,astylesheetcanrefertospecific

widgetstates.Forexample,wemaywanttorenderthe

checkbox'stextinwhitewhenthemousehoversoveritby

specifyingthe:hoverstate:

QCheckBox:hover{

color:white;

}



Statesaresignifiedbyusingasinglecolon,whereas

subcontrolsaresignifiedbyusingtwocolons.Wecanlist

severalstatesoneafteranother,eachseparatedbyacolon.In

suchcases,therulewillapplyonlywhenthewidgetisinallthe



specifiedstates.Forexample,thefollowingruleisappliedonly

ifthemouseishoveringoveracheckedcheckbox:

QCheckBox:checked:hover{

color:white;

}



Ifwewanttheruletoapplywhenanyofthestatesistrue,we

canusemultipleselectors,usingcommastoseparatethem:

QCheckBox:hover,QCheckBox:checked{

color:white;

}



Logicalnegationisachievedbyusinganexclamationmark:

QCheckBox:!checked{

color:blue;

}



Statescanbecombinedwithsubcontrols:

QComboBox::drop-down:hover{

image:url(:/images/downarrow_bright.png);

}



Figure19.5liststhestylesheetstatesthatareavailable.

Figure19.5.Someofthewidgetstates

accessibletostylesheets

State

:disabled



Description

Thewidgetisdisabled



:enabled



Thewidgetisenabled



:focus



Thewidgethasinputfocus



:hover



Themouseishoveringoverthewidget



:pressed



Thewidgetisbeingpressedusingthe

mouse



:checked



Thebuttonischecked



:unchecked



Thebuttonisunchecked



:indeterminate Thebuttonispartiallychecked

:open



Thewidgetisinanopenorexpanded

state



:closed



Thewidgetisinaclosedorcollapsed

state



:on



Thewidgetis"on"



:off



Thewidgetis"off"



Stylesheetscanalsobeusedtogetherwithothertechniquesto

performmorecomplexcustomizations.Forexample,suppose

wewanttopositionatiny"erase"buttoninsideaQLineEdit's

frame,totherightoftheQLineEdit'stext.Thisinvolves

creatinganEraseButtonclass,andplacingitontopofthe

QLineEdit(e.g.,usinglayouts),butalsoreservingsomespace

forthebutton,sothatthetyped-intextcannotcollidewiththe

erasebutton.DoingthisbysubclassingQStylewouldbe

inconvenient,becausewewouldhavetosubclasseverystylein

Qtthatmightbeusedbytheapplication(QWindowsVistaStyle,

QPlastiqueStyle,etc.).Usingstylesheets,thefollowingrule

doesthetrick:

QLineEdit{



padding:0px15px0px0px;

}



Thepaddingpropertyletsusspecifythetop,right,bottom,and

leftpaddingofthewidget.Thepaddingisinsertedbetweenthe

QLineEdit'stextanditsframe.Forconvenience,CSSalso

definespadding-top,padding-right,padding-bottom,and

padding-left,forwhenwewanttosetonlyonepaddingvalue.

Forexample:

QLineEdit{

padding-right:15px;

}



LikemostQtwidgetsthatarecustomizableusingstylesheets,

QLineEditsupportstheboxmodeldepictedinFigure19.6.This

modelspecifiesfourrectanglesthataffectthelayoutand

renderingofastyledwidget:

1. Thecontentsrectangleistheinnermostrectangle.Thisis

wheretheactualcontentsofthewidget(e.g.,thetextor

image)ispainted.

2. Thepaddingrectangleenclosesthecontentsrectangle.It

takesintoaccountanypaddingspecifiedusingthepadding

property.

3. Theborderrectangleenclosesthepaddingrectangle.It

reservesspacefortheborder.

4. Themarginrectangleistheoutermostrectangle.It

enclosestheborderrectangleandtakesintoaccountany

specifiedmargin.

Figure19.6.TheCSSboxmodel



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 19. Look and Feel Customization

Tải bản đầy đủ ngay(0 tr)

×