Archive:Development/Tutorials/Qt4 Ruby Tutorial/Chapter 01 (zh TW)

Revision as of 11:35, 27 December 2009 by Alisha (talk | contribs)
Jump to: navigation, search

Template:I18n/Language Navigation Bar (zh TW)

Template:TutorialBrowser (zh TW)

Hello World!

Qt4 Ruby Tutorial Screenshot 1.png



第一個程式是一個簡單的「Hello world」範例。它僅包含了你完成並運作一個 Qt 應用程式的最少需求。上圖是這支程式的螢幕擷圖。


require 'Qt4'

app =

hello ='Hello World!') hello.resize(100, 30)



QtRuby 應用程式的上層通常只需要執行一些初始化,然後將控制權交給 Qt 函式庫。然後透過事件告訴程式使用者的操作。

在每個使用 Qt 的 GUI 應用程式,必須有一個確實的Qt::Application物件。Qt::Application管理各種應用程式的資源,如預設字體和游標(cursor)。

Qt::PushButton 是一個 GUI push 按鈕,使用者可以按下和放開。它管理自己的外觀和感覺,就像所有其他的Qt::Widget。widget 是一個使用者界面物件,可以處理使用者的輸入和繪製圖形。程式設計師可以改變整體外觀和感覺以及它的一些小型屬性(如顏色),以及 widget 的內容。Qt::PushButton可以顯示文字或Qt::Icon


require 'Qt4'

此行載入 QtRuby 擴充。

app =

app 是程式的 Qt::Application 實例(instance)。它是在這裡建立的。我們傳遞 ARGVQt::Application 建構子(constructor),使之能夠處理某些標準的命令列參數(如 X11 的 -display)。所有 Qt 能識別的命令列參數將會從 ARGV 移除 。

注意: 最重要的是, Qt::Application 物件要在使用任何 Qt 的視窗系統元件之前建立。

hello ='Hello World!')

Qt::Application 後,第一個出現的視窗系統程式碼:建立一個 push 按鈕。

The button is set up to display the text "Hello world!". Because we don't specify a parent window (as second argument to the Qt::PushButton constructor), the button will be a window of its own, with its own window frame and title bar.

hello.resize(100, 30)

The button is set up to be 100 pixels wide and 30 pixels high (excluding the window frame, which is provided by the windowing system). We could call Qt::Widget::move() to assign a specific screen position to the widget, but instead we let the windowing system choose a position.

A widget is never visible when you create it. You must call Qt::Widget::show() to make it visible.


This is where our program passes control to Qt. Qt::CoreApplication::exec() will return when the application exits. (Qt::CoreApplication is Qt::Application's base class. It implements Qt::Application's core, non-GUI functionality and can be used when developing non-GUI applications.)

In Qt::CoreApplication::exec(), Qt receives and processes user and system events and passes these on to the appropriate widgets.

You should now try to run this program.


When you run the application, you will see a small window filled with a single button, and on it you can read the famous words: "Hello world!"


Try to resize the window. Click the button. If you're running X11, try running the program with the -geometry option (for example, -geometry 100x200+10+20).

Content is available under Creative Commons License SA 4.0 unless otherwise noted.