Export translations SettingsGroupCategory:PhononContribute/List of KDE ModulesDevelopmentDevelopment/FAQs/General FAQDevelopment/FAQs/Technical FAQDevelopment/KDevelop-PG-Qt IntroductionDevelopment/ToolsDevelopment/TutorialsDevelopment/Tutorials/CommandLineArgumentsDevelopment/Tutorials/Common Programming MistakesDevelopment/Tutorials/First programDevelopment/Tutorials/First program/KDE4Development/Tutorials/First program/KF5Development/Tutorials/KDE3/Qt Designer and KDevelop 3.0 for BeginnersDevelopment/Tutorials/Metadata/Nepomuk/TipsAndTricksDevelopment/Tutorials/Physical SimulationDevelopment/Tutorials/Qt4 Ruby TutorialDevelopment/Tutorials/Qt4 Ruby Tutorial/Chapter 01Development/Tutorials/Qt4 Ruby Tutorial/Chapter 04Development/Tutorials/Qt4 Ruby Tutorial/Chapter 05Development/Tutorials/Qt4 Ruby Tutorial/Chapter 06Development/Tutorials/Qt4 Ruby Tutorial/Chapter 07Development/Tutorials/Qt4 Ruby Tutorial/Chapter 08Development/Tutorials/Qt4 Ruby Tutorial/Chapter 09Development/Tutorials/Qt4 Ruby Tutorial/Chapter 10Development/Tutorials/Qt4 Ruby Tutorial/Chapter 11Development/Tutorials/Qt4 Ruby Tutorial/Chapter 12Development/Tutorials/Qt4 Ruby Tutorial/Chapter 13Development/Tutorials/Qt4 Ruby Tutorial/Chapter 14Development/Tutorials/Qt4 Ruby Tutorial/Chapter 2Development/Tutorials/Qt4 Ruby Tutorial/Chapter 3Development/Tutorials/Saving and loadingDevelopment/Tutorials/Setting UpDevelopment/Tutorials/Using ActionsDevelopment/Tutorials/Using KXmlGuiWindowDocumentation PrimerEdit MarkupGetting StartedHelp:ContentsHelp:ContributeHow To Convert a UserBase Manual to DocbookKDE FrameworksKDE Frameworks/Getting StartedKDE Frameworks/Getting Started/Source CodeKDE TechBase:AboutKDE TechBase:ContributorsKDE TechBase:General disclaimerKDE TechBase:Privacy policyOff-line TranslationProjects/Calligra/Plugin TutorialsToolboxTranslate a PageTranslation WorkflowTypographical GuidelinesUser:NeverendingoWelcome to KDE TechBaseLanguageaa - Afarab - Abkhazianabs - Ambonese Malayace - Achineseady - Adygheady-cyrl - Adyghe (Cyrillic script)aeb - Tunisian Arabicaeb-arab - Tunisian Arabic (Arabic script)aeb-latn - Tunisian Arabic (Latin script)af - Afrikaansak - Akanaln - Gheg Albanianalt - Southern Altaiam - Amharicami - Amisan - Aragoneseang - Old Englishanp - Angikaar - Arabicarc - Aramaicarn - Mapuchearq - Algerian Arabicary - Moroccan Arabicarz - Egyptian Arabicas - Assamesease - American Sign Languageast - Asturianatj - Atikamekwav - Avaricavk - Kotavaawa - Awadhiay - Aymaraaz - Azerbaijaniazb - South Azerbaijaniba - Bashkirban - Balinesebar - Bavarianbbc - Batak Tobabbc-latn - Batak Toba (Latin script)bcc - Southern Balochibcl - Central Bikolbe - Belarusianbe-tarask - Belarusian (Taraškievica orthography)bg - Bulgarianbgn - Western Balochibh - Bhojpuribho - Bhojpuribi - Bislamabjn - Banjarbm - Bambarabn - Banglabo - Tibetanbpy - Bishnupriyabqi - Bakhtiaribr - Bretonbrh - Brahuibs - Bosnianbtm - Batak Mandailingbto - Iriga Bicolanobug - Buginesebxr - Russia Buriatca - Catalancbk-zam - Chavacanocdo - Min Dong Chinesece - Chechenceb - Cebuanoch - Chamorrocho - Choctawchr - Cherokeechy - Cheyenneckb - Central Kurdishco - Corsicancps - Capiznoncr - Creecrh - Crimean Turkishcrh-cyrl - Crimean Tatar (Cyrillic script)crh-latn - Crimean Tatar (Latin script)cs - Czechcsb - Kashubiancu - Church Slaviccv - Chuvashcy - Welshda - Danishde - Germande-at - Austrian Germande-ch - Swiss High Germande-formal - German (formal address)din - Dinkadiq - Zazakidsb - Lower Sorbiandtp - Central Dusundty - Dotelidv - Divehidz - Dzongkhaee - Eweegl - Emilianel - Greekeml - Emiliano-Romagnoloen - Englishen-ca - Canadian Englishen-gb - British Englisheo - Esperantoes - Spanishes-419 - Latin American Spanishes-formal - español (formal)et - Estonianeu - Basqueext - Extremaduranfa - Persianff - Fulahfi - Finnishfit - Tornedalen Finnishfj - Fijianfo - Faroesefr - Frenchfrc - Cajun Frenchfrp - Arpitanfrr - Northern Frisianfur - Friulianfy - Western Frisianga - Irishgag - Gagauzgan - Gan Chinesegan-hans - Gan (Simplified)gan-hant - Gan (Traditional)gcr - Guianan Creolegd - Scottish Gaelicgl - Galicianglk - Gilakign - Guaranigom - Goan Konkanigom-deva - Goan Konkani (Devanagari script)gom-latn - Goan Konkani (Latin script)gor - Gorontalogot - Gothicgrc - Ancient Greekgsw - Swiss Germangu - Gujaratigv - Manxha - Hausahak - Hakka Chinesehaw - Hawaiianhe - Hebrewhi - Hindihif - Fiji Hindihif-latn - Fiji Hindi (Latin script)hil - Hiligaynonho - Hiri Motuhr - Croatianhrx - Hunsrikhsb - Upper Sorbianht - Haitian Creolehu - Hungarianhu-formal - magyar (formal)hy - Armenianhyw - Western Armenianhz - Hereroia - Interlinguaid - Indonesianie - Interlingueig - Igboii - Sichuan Yiik - Inupiaqike-cans - Eastern Canadian (Aboriginal syllabics)ike-latn - Eastern Canadian (Latin script)ilo - Ilokoinh - Ingushio - Idois - Icelandicit - Italianiu - Inuktitutja - Japanesejam - Jamaican Creole Englishjbo - Lojbanjut - Jutishjv - Javaneseka - Georgiankaa - Kara-Kalpakkab - Kabylekbd - Kabardiankbd-cyrl - Kabardian (Cyrillic script)kbp - Kabiyekg - Kongokhw - Khowarki - Kikuyukiu - Kirmanjkikj - Kuanyamakjp - Eastern Pwokk - Kazakhkk-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 - Kalaallisutkm - Khmerkn - Kannadako - Koreanko-kp - Korean (North Korea)koi - Komi-Permyakkr - Kanurikrc - Karachay-Balkarkri - Kriokrj - Kinaray-akrl - Karelianks - Kashmiriks-arab - Kashmiri (Arabic script)ks-deva - Kashmiri (Devanagari script)ksh - Colognianku - Kurdishku-arab - Kurdish (Arabic script)ku-latn - Kurdish (Latin script)kum - Kumykkv - Komikw - Cornishky - Kyrgyzla - Latinlad - Ladinolb - Luxembourgishlbe - Laklez - Lezghianlfn - Lingua Franca Novalg - Gandali - Limburgishlij - Ligurianliv - Livonianlki - Lakilld - Ladinlmo - Lombardln - Lingalalo - Laoloz - Lozilrc - Northern Lurilt - Lithuanianltg - Latgalianlus - Mizoluz - Southern Lurilv - Latvianlzh - Literary Chineselzz - Lazmai - Maithilimap-bms - Basa Banyumasanmdf - Mokshamg - Malagasymh - Marshallesemhr - Eastern Marimi - Maorimin - Minangkabaumk - Macedonianml - Malayalammn - Mongolianmni - Manipurimnw - Monmo - Moldovanmr - Marathimrj - Western Marims - Malaymt - Maltesemus - Muscogeemwl - Mirandesemy - Burmesemyv - Erzyamzn - Mazanderanina - Naurunah - Nāhuatlnan - Min Nan Chinesenap - Neapolitannb - Norwegian Bokmålnds - Low Germannds-nl - Low Saxonne - Nepalinew - Newaring - Ndonganiu - Niueannl - Dutchnl-informal - Nederlands (informeel)nn - Norwegian Nynorskno - Norwegiannov - Novialnqo - N’Konrm - Normannso - Northern Sothonv - Navajony - Nyanjanys - Nyungaroc - Occitanolo - Livvi-Karelianom - Oromoor - Odiaos - Osseticpa - Punjabipag - Pangasinanpam - Pampangapap - Papiamentopcd - Picardpdc - Pennsylvania Germanpdt - Plautdietschpfl - Palatine Germanpi - Palipih - Norfuk / Pitkernpl - Polishpms - Piedmontesepnb - Western Punjabipnt - Ponticprg - Prussianps - Pashtopt - Portuguesept-br - Brazilian Portuguesequ - Quechuaqug - Chimborazo Highland Quichuargn - Romagnolrif - Riffianrm - Romanshrmy - Vlax Romanirn - Rundiro - Romanianroa-tara - Tarantinoru - Russianrue - Rusynrup - Aromanianruq - Megleno-Romanianruq-cyrl - Megleno-Romanian (Cyrillic script)ruq-latn - Megleno-Romanian (Latin script)rw - Kinyarwandasa - Sanskritsah - Sakhasat - Santalisc - Sardinianscn - Siciliansco - Scotssd - Sindhisdc - Sassarese Sardiniansdh - Southern Kurdishse - Northern Samisei - Serises - Koyraboro Sennisg - Sangosgs - Samogitiansh - Serbo-Croatianshi - Tachelhitshi-latn - Tachelhit (Latin script)shi-tfng - Tachelhit (Tifinagh script)shn - Shanshy-latn - Shawiya (Latin script)si - Sinhalasimple - Simple Englishsk - Slovakskr - Saraikiskr-arab - Saraiki (Arabic script)sl - Sloveniansli - Lower Silesiansm - Samoansma - Southern Samismn - Inari Samisn - Shonaso - Somalisq - Albaniansr - Serbiansr-ec - Serbian (Cyrillic script)sr-el - Serbian (Latin script)srn - Sranan Tongoss - Swatist - Southern Sothostq - Saterland Frisiansty - себертатарsu - Sundanesesv - Swedishsw - Swahiliszl - Silesianszy - Sakizayata - Tamiltay - Tayaltcy - Tulute - Telugutet - Tetumtg - Tajiktg-cyrl - Tajik (Cyrillic script)tg-latn - Tajik (Latin script)th - Thaiti - Tigrinyatk - Turkmentl - Tagalogtly - Talyshtn - Tswanato - Tongantpi - Tok Pisintr - Turkishtru - Turoyotrv - Tarokots - Tsongatt - Tatartt-cyrl - Tatar (Cyrillic script)tt-latn - Tatar (Latin script)tum - Tumbukatw - Twity - Tahitiantyv - Tuviniantzm - Central Atlas Tamazightudm - Udmurtug - Uyghurug-arab - Uyghur (Arabic script)ug-latn - Uyghur (Latin script)uk - Ukrainianur - Urduuz - Uzbekuz-cyrl - Uzbek (Cyrillic script)uz-latn - Uzbek (Latin script)ve - Vendavec - Venetianvep - Vepsvi - Vietnamesevls - West Flemishvmf - Main-Franconianvo - Volapükvot - Voticvro - Võrowa - Walloonwar - Waraywo - Wolofwuu - Wu Chinesexal - Kalmykxh - Xhosaxmf - Mingrelianxsy - Saisiyatyi - Yiddishyo - Yorubayue - Cantoneseza - Zhuangzea - Zeelandiczgh - Standard Moroccan Tamazightzh - Chinesezh-cn - Chinese (China)zh-hans - Simplified Chinesezh-hant - Traditional Chinesezh-hk - Chinese (Hong Kong)zh-mo - Chinese (Macau)zh-my - Chinese (Malaysia)zh-sg - Chinese (Singapore)zh-tw - Chinese (Taiwan)zu - Zuluqqq - Message documentationFormatExport for off-line translationExport in native format Fetch <languages /> {{TutorialBrowser| series=[[Special:myLanguage/Development/Tutorials/Qt4_Ruby_Tutorial|Qt4 Ruby Tutorial]]| name=Let There Be Widgets| pre=[[Special:myLanguage/Development/Tutorials/Qt4_Ruby_Tutorial/Chapter_3|Tutorial 3 - Family Values]]| next=[[Special:myLanguage/Development/Tutorials/Qt4_Ruby_Tutorial/Chapter_05|Tutorial 5 - Building Blocks]] }} == Let There Be Widgets == [[Image:Qt4_Ruby_Tutorial_Screenshot_4.png|center]] Files: * [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t4/t4.rb t4.rb] === Overview === This example shows how to create your own widget, and describes how to control the minimum and maximum sizes of a widget. <syntaxhighlight lang="ruby"> require 'Qt4' class MyWidget < Qt::Widget def initialize(parent = nil) super setFixedSize(200, 120) quit = Qt::PushButton.new(tr('Quit'), self) quit.setGeometry(62, 40, 75, 30) quit.setFont(Qt::Font.new('Times', 18, Qt::Font::Bold)) connect(quit, SIGNAL('clicked()'), $qApp, SLOT('quit()')) end end app = Qt::Application.new(ARGV) widget = MyWidget.new() widget.show() app.exec() </syntaxhighlight> === Line by Line Walkthrough === <syntaxhighlight lang="ruby"> class MyWidget < Qt::Widget </syntaxhighlight> Here we create a new class. Because this class inherits from [http://doc.qt.nokia.com/latest/qwidget.html Qt::Widget], the new class is a widget and may be a top-level window or a child widget (like the [http://doc.qt.nokia.com/latest/qpushbutton.html Qt::PushButton] in the previous chapter). <syntaxhighlight lang="ruby"> def initialize(parent = nil) super </syntaxhighlight> This class has only one member, a constructor (in addition to the members it inherits from [http://doc.qt.nokia.com/latest/qwidget.html Qt::Widget]). The constructor is a standard Qt widget constructor; you should always include a similar constructor when you create widgets. The argument is its parent widget. To create a top-level window you specify '''<tt>nil</tt>''' as the parent. As you can see, this widget defaults to be a top-level window. Like most widgets, it just passes on the '''<tt>parent</tt>''' parameter to the [http://doc.qt.nokia.com/latest/qwidget.html Qt::Widget] constructor. (If you're new to Ruby, calling '''<tt>super</tt>''' without any parameters will automatically pass on any parameters a method received to the superclass's method of the same name. ''Update'': Apparently, it's also important to leave off the parentheses — calling '''<tt>super()</tt>''' will call the superclass's method of the same name with an empty parameter list.) <syntaxhighlight lang="ruby"> setFixedSize(200, 120) </syntaxhighlight> Because this widget doesn't know how to handle resizing, we fix its size. In the next chapter, we will show how a widget can respond to resize event from the user. <syntaxhighlight lang="ruby"> quit = Qt::PushButton.new(tr('Quit'), self) quit.setGeometry(62, 40, 75, 30) quit.setFont(Qt::Font.new('Times', 18, Qt::Font::Bold)) </syntaxhighlight> Here we create and set up a child widget of this widget (the new widget's parent is '''<tt>self</tt>''', i.e. the '''<tt>MyWidget</tt>''' instance). The [http://doc.qt.nokia.com/latest/qobject.html#tr QObject::tr()] function call around the string literal 'Quit' marks the string for translation, making it possible to change it at run-time based on the contents of a translation file. It is a good habit to use [http://doc.qt.nokia.com/latest/qobject.html#tr QObject::tr()] around all user-visible strings, in case you decide later to translate your application to other languages. The [http://doc.qt.nokia.com/latest/qwidget.html#geometry-prop Qt::Widget::setGeometry()] call sets both the widget's screen position and the size. It is equivalent to calling [http://doc.qt.nokia.com/latest/qwidget.html#pos-prop Qt::Widget::move()] followed by [http://doc.qt.nokia.com/latest/qwidget.html#size-prop Qt::Widget::resize()]. <syntaxhighlight lang="ruby"> connect(quit, SIGNAL('clicked()'), $qApp, SLOT('quit()')) </syntaxhighlight> The '''<tt>$qApp</tt>''' pointer is a global variable created when you '''<tt>require 'Qt'</tt>'''. It points to the application's unique [http://doc.qt.nokia.com/latest/qapplication.html Qt::Application] instance. <syntaxhighlight lang="ruby"> app = Qt::Application.new(ARGV) widget = MyWidget.new() widget.show() app.exec() </syntaxhighlight> Here we instantiate our new child, set it to be the main widget, and execute the application. === Running the Application === This program is very similar in behavior to the previous one. The difference lies in the way we have implemented it. It does behave slightly differently, however. Just try to resize it to see. === Exercises === Try to create another '''<tt>MyWidget</tt>''' object. What happens? Try to add more buttons or put in widgets other than [http://doc.qt.nokia.com/latest/qpushbutton.html Qt::PushButton]. [[Category:Ruby]]