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

From KDE TechBase
Revision as of 17:04, 13 January 2010 by Alisha (talk | contribs)

Template:I18n/Language Navigation Bar (zh TW)

Template:TutorialBrowser (zh TW)

With Cannon You Can

檔案:

概覽

在這個範例中,我們來繪製一個可愛小巧的藍色加農砲。只有 cannon.rb 不同於前面的章節。

一行一行的瀏覽

cannon.rb

def paintEvent(event)

 painter = Qt::Painter.new(self)

我們現在開始要認真的使用 Qt::Painter。我們建立了一個操作這個 widget 的 painter。

painter.setPen(Qt::NoPen)

Qt::Painter 使用筆觸(pen)來繪製出邊緣(edge)。這裡我們將它設定為 Qt::NoPen。這意味著當我們繪製東西時,將不會有明確的邊緣。

painter.setBrush(Qt::Brush.new(Qt::blue))

Qt::Painter 要填充矩形、圓形,或其他圖形時,它會使用筆刷(Brush)來填充形狀。這裡我們把它設定為使用純藍色筆刷。(我們也可以用調色盤。)藍色的畫筆會填滿直到我們畫出東西的邊緣。

painter.translate(0, rect().height())

Qt::Painter::translate() 函式轉換(translate)了 Qt::Painter 的坐標系統(也就是說,藉由偏移量(offset)移動它)。在這裡,我們設定 widget 的左下角為(0,0)。x 和 y 的方向維持不變,即所有在 widget 內的 y 坐標現在都是負的。(更多關於 Qt 坐標系統的資訊,請見坐標系統。)

painter.drawPie(Qt::Rect.new(-35, -35, 70, 70), 0, 90 * 16)

Qt::Painter::drawPie() 函式使用起始角度以及弧長,在指定的矩形內畫出圓餅的形狀。角度單位為十六分之一度。零度位在3點鐘方向。繪畫方向是逆時針。這裡我們在 widget 的左下角畫出四分之一圓。圓餅填充了藍色,而且沒有邊框。

painter.rotate(-@currentAngle)

The Qt::Painter::rotate() function rotates the coordinate system of the Qt::Painter around the origin. The rotation argument is given in degrees (not given in sixteenths of a degree as above) and clockwise. Here we rotate the coordinate system @currentAngle degrees counter-clockwise.

painter.drawRect(Qt::Rect.new(30, -5, 20, 10))

The Qt::Painter::drawRect() function draws the specified rectangle. Here we draw the barrel of the cannon.

It can often be difficult to envision the resulting drawing when the coordinate system has been transformed ( translated, rotated, scaled, or sheared) as above.

In this case the coordinate system is first translated and then rotated. If the rectangle Qt::Rect.new(30, -5, 20, 10) had been drawn in the translated coordinate system, it would have looked like this:

Note that the rectangle is clipped by the border of the CannonField widget. When we rotate the coordinate system, for instance 60 degrees, the rectangle will be rotated around (0, 0), which is the bottom-left corner because we have translated the coordinate system. The result looks like this:

執行應用程式

當 slider 操作時,畫出的加農砲角度也會跟著改變。

練習

設定一枝不同的筆觸,代替 Qt::NoPen。設定一枝調色盤筆刷。