Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Home
Help
Recent changes
Contributor Help Pages
Tasks and Tools
Modify a page
Add new content
Page elements
Typographical guidelines
More markup help
Translator Help Pages
Get a Translator Account
Languages represented
Translation Workflow
Translate a Page
Off-line Translation
Translation Statistics
More Help pages
Search
Search
English
Log in
Personal tools
Log in
Export translations
Translate
English
Language statistics
Message group statistics
Export
Tools
Tools
move to sidebar
hide
Actions
Language statistics
Message group statistics
Export
General
Special pages
Printable version
Settings
Group
Category:Phonon
Contribute/List of KDE Modules
Development
Development/FAQs/General FAQ
Development/FAQs/Technical FAQ
Development/KDevelop-PG-Qt Introduction
Development/Tools
Development/Tutorials
Development/Tutorials/CommandLineArguments
Development/Tutorials/Common Programming Mistakes
Development/Tutorials/First program
Development/Tutorials/First program/KDE4
Development/Tutorials/First program/KF5
Development/Tutorials/KDE3/Qt Designer and KDevelop 3.0 for Beginners
Development/Tutorials/Metadata/Nepomuk/TipsAndTricks
Development/Tutorials/Physical Simulation
Development/Tutorials/Qt4 Ruby Tutorial
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 01
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 04
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 05
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 06
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 07
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 08
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 09
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 10
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 11
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 12
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 13
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 14
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 2
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 3
Development/Tutorials/Saving and loading
Development/Tutorials/Setting Up
Development/Tutorials/Using Actions
Development/Tutorials/Using KXmlGuiWindow
Documentation Primer
Edit Markup
Getting Started
Help:Contents
Help:Contribute
How To Convert a UserBase Manual to Docbook
KDE Frameworks
KDE Frameworks/Getting Started
KDE TechBase:About
KDE TechBase:Contributors
KDE TechBase:General disclaimer
KDE TechBase:Privacy policy
Off-line Translation
Projects/Calligra/Plugin Tutorials
Toolbox
Translate a Page
Translation Workflow
Typographical Guidelines
User:Neverendingo
Welcome to KDE TechBase
Language
aa - Afar
ab - Abkhazian
abs - Ambonese Malay
ace - Achinese
acm - Iraqi Arabic
ady - Adyghe
ady-cyrl - Adyghe (Cyrillic script)
aeb - Tunisian Arabic
aeb-arab - Tunisian Arabic (Arabic script)
aeb-latn - Tunisian Arabic (Latin script)
af - Afrikaans
aln - Gheg Albanian
alt - Southern Altai
am - Amharic
ami - Amis
an - Aragonese
ang - Old English
ann - Obolo
anp - Angika
ar - Arabic
arc - Aramaic
arn - Mapuche
arq - Algerian Arabic
ary - Moroccan Arabic
arz - Egyptian Arabic
as - Assamese
ase - American Sign Language
ast - Asturian
atj - Atikamekw
av - Avaric
avk - Kotava
awa - Awadhi
ay - Aymara
az - Azerbaijani
azb - South Azerbaijani
ba - Bashkir
ban - Balinese
ban-bali - Balinese (Balinese script)
bar - Bavarian
bbc - Batak Toba
bbc-latn - Batak Toba (Latin script)
bcc - Southern Balochi
bci - Baoulé
bcl - Central Bikol
bdr - West Coast Bajau
be - Belarusian
be-tarask - Belarusian (Taraškievica orthography)
bew - Betawi
bg - Bulgarian
bgn - Western Balochi
bh - Bhojpuri
bho - Bhojpuri
bi - Bislama
bjn - Banjar
blk - Pa'O
bm - Bambara
bn - Bangla
bo - Tibetan
bpy - Bishnupriya
bqi - Bakhtiari
br - Breton
brh - Brahui
bs - Bosnian
btm - Batak Mandailing
bto - Iriga Bicolano
bug - Buginese
bxr - Russia Buriat
ca - Catalan
cbk-zam - Chavacano
cdo - Min Dong Chinese
ce - Chechen
ceb - Cebuano
ch - Chamorro
cho - Choctaw
chr - Cherokee
chy - Cheyenne
ckb - Central Kurdish
co - Corsican
cps - Capiznon
cpx - Pu-Xian Min
cpx-hans - Pu-Xian Min (Simplified Han script)
cpx-hant - Pu-Xian Min (Traditional Han script)
cpx-latn - Pu-Xian Min (Latin script)
cr - Cree
crh - Crimean Tatar
crh-cyrl - Crimean Tatar (Cyrillic script)
crh-latn - Crimean Tatar (Latin script)
crh-ro - Crimean Tatar (Romania)
cs - Czech
csb - Kashubian
cu - Church Slavic
cv - Chuvash
cy - Welsh
da - Danish
dag - Dagbani
de - German
de-at - Austrian German
de-ch - Swiss High German
de-formal - German (formal address)
dga - Dagaare
din - Dinka
diq - Zazaki
dsb - Lower Sorbian
dtp - Central Dusun
dty - Doteli
dv - Divehi
dz - Dzongkha
ee - Ewe
egl - Emilian
el - Greek
eml - Emiliano-Romagnolo
en - English
en-ca - Canadian English
en-gb - British English
eo - Esperanto
es - Spanish
es-419 - Latin American Spanish
es-formal - Spanish (formal address)
et - Estonian
eu - Basque
ext - Extremaduran
fa - Persian
fat - Fanti
ff - Fula
fi - Finnish
fit - Tornedalen Finnish
fj - Fijian
fo - Faroese
fon - Fon
fr - French
frc - Cajun French
frp - Arpitan
frr - Northern Frisian
fur - Friulian
fy - Western Frisian
ga - Irish
gaa - Ga
gag - Gagauz
gan - Gan Chinese
gan-hans - Gan (Simplified)
gan-hant - Gan (Traditional)
gcr - Guianan Creole
gd - Scottish Gaelic
gl - Galician
gld - Nanai
glk - Gilaki
gn - Guarani
gom - Goan Konkani
gom-deva - Goan Konkani (Devanagari script)
gom-latn - Goan Konkani (Latin script)
gor - Gorontalo
got - Gothic
gpe - Ghanaian Pidgin
grc - Ancient Greek
gsw - Alemannic
gu - Gujarati
guc - Wayuu
gur - Frafra
guw - Gun
gv - Manx
ha - Hausa
hak - Hakka Chinese
haw - Hawaiian
he - Hebrew
hi - Hindi
hif - Fiji Hindi
hif-latn - Fiji Hindi (Latin script)
hil - Hiligaynon
hno - Northern Hindko
ho - Hiri Motu
hr - Croatian
hrx - Hunsrik
hsb - Upper Sorbian
hsn - Xiang Chinese
ht - Haitian Creole
hu - Hungarian
hu-formal - Hungarian (formal address)
hy - Armenian
hyw - Western Armenian
hz - Herero
ia - Interlingua
id - Indonesian
ie - Interlingue
ig - Igbo
igl - Igala
ii - Sichuan Yi
ik - Inupiaq
ike-cans - Eastern Canadian (Aboriginal syllabics)
ike-latn - Eastern Canadian (Latin script)
ilo - Iloko
inh - Ingush
io - Ido
is - Icelandic
it - Italian
iu - Inuktitut
ja - Japanese
jam - Jamaican Creole English
jbo - Lojban
jut - Jutish
jv - Javanese
ka - Georgian
kaa - Kara-Kalpak
kab - Kabyle
kai - Karekare
kbd - Kabardian
kbd-cyrl - Kabardian (Cyrillic script)
kbp - Kabiye
kcg - Tyap
kea - Kabuverdianu
kg - Kongo
khw - Khowar
ki - Kikuyu
kiu - Kirmanjki
kj - Kuanyama
kjh - Khakas
kjp - Eastern Pwo
kk - Kazakh
kk-arab - Kazakh (Arabic script)
kk-cn - Kazakh (China)
kk-cyrl - Kazakh (Cyrillic script)
kk-kz - Kazakh (Kazakhstan)
kk-latn - Kazakh (Latin script)
kk-tr - Kazakh (Turkey)
kl - Kalaallisut
km - Khmer
kn - Kannada
ko - Korean
ko-kp - Korean (North Korea)
koi - Komi-Permyak
kr - Kanuri
krc - Karachay-Balkar
kri - Krio
krj - Kinaray-a
krl - Karelian
ks - Kashmiri
ks-arab - Kashmiri (Arabic script)
ks-deva - Kashmiri (Devanagari script)
ksh - Colognian
ksw - S'gaw Karen
ku - Kurdish
ku-arab - Kurdish (Arabic script)
ku-latn - Kurdish (Latin script)
kum - Kumyk
kus - Kʋsaal
kv - Komi
kw - Cornish
ky - Kyrgyz
la - Latin
lad - Ladino
lb - Luxembourgish
lbe - Lak
lez - Lezghian
lfn - Lingua Franca Nova
lg - Ganda
li - Limburgish
lij - Ligurian
liv - Livonian
lki - Laki
lld - Ladin
lmo - Lombard
ln - Lingala
lo - Lao
loz - Lozi
lrc - Northern Luri
lt - Lithuanian
ltg - Latgalian
lus - Mizo
luz - Southern Luri
lv - Latvian
lzh - Literary Chinese
lzz - Laz
mad - Madurese
mag - Magahi
mai - Maithili
map-bms - Basa Banyumasan
mdf - Moksha
mg - Malagasy
mh - Marshallese
mhr - Eastern Mari
mi - Māori
min - Minangkabau
mk - Macedonian
ml - Malayalam
mn - Mongolian
mnc - Manchu
mnc-latn - Manchu (Latin script)
mnc-mong - Manchu (Mongolian script)
mni - Manipuri
mnw - Mon
mo - Moldovan
mos - Mossi
mr - Marathi
mrh - Mara
mrj - Western Mari
ms - Malay
ms-arab - Malay (Jawi script)
mt - Maltese
mus - Muscogee
mwl - Mirandese
my - Burmese
myv - Erzya
mzn - Mazanderani
na - Nauru
nah - Nāhuatl
nan - Min Nan Chinese
nap - Neapolitan
nb - Norwegian Bokmål
nds - Low German
nds-nl - Low Saxon
ne - Nepali
new - Newari
ng - Ndonga
nia - Nias
niu - Niuean
nl - Dutch
nl-informal - Dutch (informal address)
nmz - Nawdm
nn - Norwegian Nynorsk
no - Norwegian
nod - Northern Thai
nog - Nogai
nov - Novial
nqo - N’Ko
nrm - Norman
nso - Northern Sotho
nv - Navajo
ny - Nyanja
nyn - Nyankole
nys - Nyungar
oc - Occitan
ojb - Northwestern Ojibwa
olo - Livvi-Karelian
om - Oromo
or - Odia
os - Ossetic
pa - Punjabi
pag - Pangasinan
pam - Pampanga
pap - Papiamento
pcd - Picard
pcm - Nigerian Pidgin
pdc - Pennsylvania German
pdt - Plautdietsch
pfl - Palatine German
pi - Pali
pih - Norfuk / Pitkern
pl - Polish
pms - Piedmontese
pnb - Western Punjabi
pnt - Pontic
prg - Prussian
ps - Pashto
pt - Portuguese
pt-br - Brazilian Portuguese
pwn - Paiwan
qu - Quechua
qug - Chimborazo Highland Quichua
rgn - Romagnol
rif - Riffian
rki - Arakanese
rm - Romansh
rmc - Carpathian Romani
rmy - Vlax Romani
rn - Rundi
ro - Romanian
roa-tara - Tarantino
rsk - Pannonian Rusyn
ru - Russian
rue - Rusyn
rup - Aromanian
ruq - Megleno-Romanian
ruq-cyrl - Megleno-Romanian (Cyrillic script)
ruq-latn - Megleno-Romanian (Latin script)
rw - Kinyarwanda
ryu - Okinawan
sa - Sanskrit
sah - Yakut
sat - Santali
sc - Sardinian
scn - Sicilian
sco - Scots
sd - Sindhi
sdc - Sassarese Sardinian
sdh - Southern Kurdish
se - Northern Sami
se-fi - Northern Sami (Finland)
se-no - Northern Sami (Norway)
se-se - Northern Sami (Sweden)
sei - Seri
ses - Koyraboro Senni
sg - Sango
sgs - Samogitian
sh - Serbo-Croatian
sh-cyrl - Serbo-Croatian (Cyrillic script)
sh-latn - Serbo-Croatian (Latin script)
shi - Tachelhit
shi-latn - Tachelhit (Latin script)
shi-tfng - Tachelhit (Tifinagh script)
shn - Shan
shy - Shawiya
shy-latn - Shawiya (Latin script)
si - Sinhala
simple - Simple English
sjd - Kildin Sami
sje - Pite Sami
sk - Slovak
skr - Saraiki
skr-arab - Saraiki (Arabic script)
sl - Slovenian
sli - Lower Silesian
sm - Samoan
sma - Southern Sami
smn - Inari Sami
sms - Skolt Sami
sn - Shona
so - Somali
sq - Albanian
sr - Serbian
sr-ec - српски (ћирилица)
sr-el - srpski (latinica)
srn - Sranan Tongo
sro - Campidanese Sardinian
ss - Swati
st - Southern Sotho
stq - Saterland Frisian
sty - Siberian Tatar
su - Sundanese
sv - Swedish
sw - Swahili
syl - Sylheti
szl - Silesian
szy - Sakizaya
ta - Tamil
tay - Tayal
tcy - Tulu
tdd - Tai Nuea
te - Telugu
tet - Tetum
tg - Tajik
tg-cyrl - Tajik (Cyrillic script)
tg-latn - Tajik (Latin script)
th - Thai
ti - Tigrinya
tk - Turkmen
tl - Tagalog
tly - Talysh
tly-cyrl - Talysh (Cyrillic script)
tn - Tswana
to - Tongan
tok - Toki Pona
tpi - Tok Pisin
tr - Turkish
tru - Turoyo
trv - Taroko
ts - Tsonga
tt - Tatar
tt-cyrl - Tatar (Cyrillic script)
tt-latn - Tatar (Latin script)
tum - Tumbuka
tw - Twi
ty - Tahitian
tyv - Tuvinian
tzm - Central Atlas Tamazight
udm - Udmurt
ug - Uyghur
ug-arab - Uyghur (Arabic script)
ug-latn - Uyghur (Latin script)
uk - Ukrainian
ur - Urdu
uz - Uzbek
uz-cyrl - Uzbek (Cyrillic script)
uz-latn - Uzbek (Latin script)
ve - Venda
vec - Venetian
vep - Veps
vi - Vietnamese
vls - West Flemish
vmf - Main-Franconian
vmw - Makhuwa
vo - Volapük
vot - Votic
vro - Võro
wa - Walloon
wal - Wolaytta
war - Waray
wls - Wallisian
wo - Wolof
wuu - Wu Chinese
wuu-hans - Wu Chinese (Simplified)
wuu-hant - Wu Chinese (Traditional)
xal - Kalmyk
xh - Xhosa
xmf - Mingrelian
xsy - Saisiyat
yi - Yiddish
yo - Yoruba
yrl - Nheengatu
yue - Cantonese
yue-hans - Cantonese (Simplified)
yue-hant - Cantonese (Traditional)
za - Zhuang
zea - Zeelandic
zgh - Standard Moroccan Tamazight
zh - Chinese
zh-cn - Chinese (China)
zh-hans - Simplified Chinese
zh-hant - Traditional Chinese
zh-hk - Chinese (Hong Kong)
zh-mo - Chinese (Macau)
zh-my - Chinese (Malaysia)
zh-sg - Chinese (Singapore)
zh-tw - Chinese (Taiwan)
zu - Zulu
qqq - Message documentation
Format
Export for off-line translation
Export in native format
Export in CSV format
Fetch
<languages /> {{TutorialBrowser| series=[[Special:myLanguage/Development/Tutorials/Qt4_Ruby_Tutorial|Qt4 Ruby Tutorial]]| name=Preparing for Battle| pre=[[Special:myLanguage/Development/Tutorials/Qt4_Ruby_Tutorial/Chapter_07|Tutorial 7 - One Thing Leads to Another]]| next=[[Special:myLanguage/Development/Tutorials/Qt4_Ruby_Tutorial/Chapter_09|Tutorial 9 - With Cannon You Can]] }} == Preparing for Battle == [[Image:Qt4_Ruby_Tutorial_Screenshot_8.png|center]] Files: * [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t8/lcdrange.rb lcdrange.rb] * [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t8/t8.rb t8.rb] * [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t8/cannon.rb cannon.rb] === Overview === In this example, we introduce the first custom widget that can paint itself. We also add a useful keyboard interface (with two lines of code). === Line by Line Walkthrough === '''[http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t8/lcdrange.rb lcdrange.rb]''' This file is very similar to the lcdrange.rb in [[Special:myLanguage/Development/Tutorials/Qt4_Ruby_Tutorial/Chapter_07|Chapter 7]]. We have added one slot: '''<tt>setRange()</tt>'''. We now add the possibility of setting the range of the '''<tt>LCDRange</tt>'''. Until now, it has been fixed at 0 to 99. <syntaxhighlight lang="ruby"> def setRange(minVal, maxVal) if minVal < 0 || maxVal > 99 || minVal > maxVal qWarning("LCDRange::setRange(#{minVal}, #{maxVal})\n" + "\tRange must be 0..99\n" + "\tand minVal must not be greater than maxVal") return end @slider.setRange(minVal, maxVal) end </syntaxhighlight> The '''<tt>setRange()</tt>''' slot sets the range of the slider in the '''<tt>LCDRange</tt>'''. Because we have set up the [http://doc.qt.nokia.com/latest/qlcdnumber.html QLCDNumber] to always display two digits, we want to limit the possible range of '''<tt>minVal</tt>''' and '''<tt>maxVal</tt>''' to avoid overflow of the [http://doc.qt.nokia.com/latest/qlcdnumber.html QLCDNumber]. (We could have allowed values down to -9 but chose not to.) If the arguments are illegal, we use Qt's [http://doc.qt.nokia.com/latest/qtglobal.html#qWarning QtGlobal::qWarning()] function to issue a warning to the user and return immediately. [http://doc.qt.nokia.com/latest/qtglobal.html#qWarning QtGlobal::qWarning()] is a '''<tt>printf</tt>'''-like function that by default sends its output to '''<tt>$stderr</tt>'''. If you want, you can install your own handler function using [http://doc.qt.nokia.com/latest/qtglobal.html#qInstallMsgHandler QtGlobal::qInstallMsgHandler()]. <syntaxhighlight lang="ruby"> lcd.setSegmentStyle(Qt::LCDNumber::Filled) </syntaxhighlight> This makes our lcd numbers look way better. I'm not certain, but I believe what makes it possible to do this is setting a palette (see next section). What I do know is that this line has no effect when I tried it in previous chapters, but works here. '''[http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t8/cannon.rb cannon.rb]''' <syntaxhighlight lang="ruby"> @currentAngle = 45 setPalette(Qt::Palette.new(Qt::Color.new(250, 250, 200))) setAutoFillBackground(true) </syntaxhighlight> The constructor initializes the angle value to 45 degrees and sets a custom palette for this widget. This palette uses the indicated color as background and picks other colors suitably. (For this widget only the background and text colors will actually be used.) We then call setAutoFillBackground(true) to tell Qt fill the background automatically. The [http://doc.qt.nokia.com/latest/qcolor.html Qt::Color] is specified as a RGB (red-green-blue) triplet, where each value is between 0 (dark) and 255 (bright). We could also have used a predefined color such as [http://doc.qt.nokia.com/latest/qt.html#GlobalColor-enum Qt::yellow] instead of specifying an RGB value. <syntaxhighlight lang="ruby"> def setAngle(angle) if angle < 5 angle = 5 elsif angle > 70 angle = 70 end if @currentAngle == angle return end @currentAngle = angle update() emit angleChanged(@currentAngle) end def setAngle(degrees) </syntaxhighlight> This function sets the angle value. We have chosen a legal range of 5 to 70 and adjust the given number of degrees accordingly. We have chosen not to issue a warning if the new angle is out of range. If the new angle equals the old one, we return immediately. It is important to only emit the '''<tt>angleChanged()</tt>''' signal when the angle really has changed. Then we set the new angle value and repaint our widget. The [http://doc.qt.nokia.com/latest/qwidget.html#update Qt::Widget::update()] function clears the widget (usually filling it with its background color) and sends a paint event to the widget. This results in a call to the paint event function of the widget. Finally, we emit the '''<tt>angleChanged()</tt>''' signal to tell the outside world that the angle has changed. The '''<tt>emit</tt>''' keyword is unique to Qt and not regular Ruby syntax. <syntaxhighlight lang="ruby"> def paintEvent(event) painter = Qt::Painter.new(self) painter.drawText(200, 200, tr("Angle = #{@currentAngle}")) painter.end() end </syntaxhighlight> This is our first attempt to write a paint event handler. The event argument contains a description of the paint event. [http://doc.qt.nokia.com/latest/qpaintevent.html Qt::PaintEvent] contains the region in the widget that must be updated. For the time being, we will be lazy and just paint everything. Our code displays the angle value in the widget at a fixed position. We create a [http://doc.qt.nokia.com/latest/qpainter.html Qt::Painter] operating on this widget and use it to paint a string. We'll come back to [http://doc.qt.nokia.com/latest/qpainter.html Qt::Painter] later; it can do a great many things. '''[http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t8/t8.rb t8.rb]''' <syntaxhighlight lang="ruby"> angle = LCDRange.new() angle.setRange(5, 70) </syntaxhighlight> In the constructor, we create and set up the LCDRange widget. We set the LCDRange to accept angles from 5 to 70 degrees. <syntaxhighlight lang="ruby"> cannonField = CannonField.new() </syntaxhighlight> We create our CannonField widget. <syntaxhighlight lang="ruby"> connect(angle, SIGNAL('valueChanged(int)'), cannonField, SLOT('setAngle(int)')) connect(cannonField, SIGNAL('angleChanged(int)'), angle, SLOT('setValue(int)')) </syntaxhighlight> Here we connect the '''<tt>valueChanged()</tt>''' signal of the '''<tt>LCDRange</tt>''' to the '''<tt>setValue()</tt>''' slot of the '''<tt>CannonField</tt>'''. This will update '''<tt>CannonField</tt>''''s angle value whenever the user operates the '''<tt>LCDRange</tt>'''. We also make the reverse connection so that changing the angle in the '''<tt>CannonField</tt>''' will update the '''<tt>LCDRange</tt>''' value. In our example we never change the angle of the '''<tt>CannonField</tt>''' directly; but by doing the last connect() we ensure that no future changes will disrupt the synchronization between those two values. This illustrates the power of component programming and proper encapsulation. Notice how important it is to emit the '''<tt>angleChanged()</tt>''' signal only when the angle actually changes. If both the '''<tt>LCDRange</tt>''' and the '''<tt>CannonField</tt>''' had omitted this check, the program would have entered an infinite loop upon the first change of one of the values. <syntaxhighlight lang="ruby"> gridLayout = Qt::GridLayout.new() </syntaxhighlight> So far, we have used [http://doc.qt.nokia.com/latest/qgridlayout.html Qt::VBoxLayout] for geometry management. Now, however, we want to have a little more control over the layout, and we switch to the more powerful [http://doc.qt.nokia.com/latest/qgridlayout.html Qt::GridLayout] class. [http://doc.qt.nokia.com/latest/qgridlayout.html Qt::GridLayout] isn't a widget; it is a different class that can manage the children of any widget. We don't need to specify any dimensions to the [http://doc.qt.nokia.com/latest/qvboxlayout.html Qt::GridLayout] constructor. The [http://doc.qt.nokia.com/latest/qgridlayout.html Qt::GridLayout] will determine the number of rows and columns based on the grid cells we populate. [[Image:Qt4_Ruby_Tutorial_Screenshot_8-layout.png]][[Image:Qt4_Ruby_Tutorial_Screenshot_8-reallayout.png]] The diagram above shows the layout we're trying to achieve. The left side shows a schematic view of the layout; the right side is an actual screenshot of the program. ''(These two images are copyrighted/owned by Nokia.)'' <syntaxhighlight lang="ruby"> gridLayout.addWidget(quit, 0, 0) </syntaxhighlight> We add the <strong>Quit</strong> button in the top-left cell of the grid, i.e., the cell with coordinates (0, 0). <syntaxhighlight lang="ruby"> gridLayout.addWidget(angle, 1, 0) </syntaxhighlight> We put the angle '''<tt>LCDRange</tt>''' cell (1, 0). <syntaxhighlight lang="ruby"> gridLayout.addWidget(cannonField, 1, 1, 2, 1) </syntaxhighlight> We let the '''<tt>CannonField</tt>''' object occupy cells (1, 1) and (2, 1). <syntaxhighlight lang="ruby"> gridLayout.setColumnStretch(1, 10) </syntaxhighlight> We tell [http://doc.qt.nokia.com/latest/qgridlayout.html Qt::GridLayout] that the right column (column 1) is stretchable, with a stretch factor of 10. Because the left column isn't (its stretch factor is 0, the default value), [http://doc.qt.nokia.com/latest/qgridlayout.html Qt::GridLayout] will try to let the left-hand widgets' sizes be unchanged and will resize just the '''<tt>CannonField</tt>''' when the '''<tt>MyWidget</tt>''' is resized. In this particular example, any stretch factor greater than 0 for column 1 would have the same effect. In more complex layouts, you can use the stretch factors to tell that a particular column or row should stretch twice as fast as another by assigning appropriate stretch factors. <syntaxhighlight lang="ruby"> angle.setValue(60) </syntaxhighlight> We set an initial angle value. Note that this will trigger the connection from '''<tt>LCDRange</tt>''' to '''<tt>CannonField</tt>'''. <syntaxhighlight lang="ruby"> angle.setFocus() </syntaxhighlight> Our last action is to set '''<tt>angle</tt>''' to have keyboard focus so that keyboard input will go to the '''<tt>LCDRange</tt>''' widget by default. === Running the Application === When the slider is operated, the '''<tt>CannonField</tt>''' displays the new angle value. Upon resizing, '''<tt>CannonField</tt>''' is given as much space as possible. === Exercises === Try to resize the window. What happens if you make it really narrow or really squat? If you give the left-hand column a non-zero stretch factor, what happens when you resize the window? Try to change "Quit" to "&Quit". How does the button's look change? ( Whether it does change or not depends on the platform.) What happens if you press <strong>Alt+Q</strong> while the program is running? Center the text in the '''<tt>CannonField</tt>'''. [[Category:Ruby]]
Toggle limited content width