描画処理
Ruby/Qteの勉強 その34
画面に線や四角形を書いてみる。
描画を行うにはQPainterを使用して、beginとendの間に描画する内容を記述する。これらの処理はpaintEvent内で行い、updateまたはrepaintでイベントを発生させる。
下の例ではサイン曲線を描いている、曲線の描画はdrawPointで点で描いても良いが見やすくするためにlineToを用いて点と点の間を線で結んでいる。
#!/usr/bin/env ruby require "qte" require "qpe" include Qte include Qpe class SampleWindow < QMainWindow def initialize() super() setCaption(tr("サンプル")) @msg = QLabel.new(tr("描画のサンプル"),self) @msg.setGeometry(0,0,310,35) self.update() # paintEvent発生 # self.repaint() catchEvent end # 描画する式の定義 def function(x) Math.sin(x / 40.0) * 150 # (x ** 3) / 10000 end # 描画 def draw @p = QPainter.new @pen = QPen.new( Qt::black, 1) # 黒、幅1 @p.begin(self) # 描画開始 @p.setPen(@pen) @p.drawLine(0, 240, 640, 240) @p.drawLine(320, 0, 320, 480) @pen.setColor( Qt::blue ) # 青 @p.setPen(@pen) x = -320 y = function(x) @p.moveTo(x + 320, 240 - y) # 初期座標設定 for x in -319 .. 319 y = function(x) @p.lineTo(x + 320, 240 - y) # 一つ前の座標から線をひく # @p.drawPoint(x + 320, 240 - y) # 点を打つ end @p.end # 描画終了 end def paintEvent(p) draw end end $defaultCodec = QTextCodec.codecForName("utf8") app = QPEApplication.new([$0]+ARGV) app.setDefaultCodec($defaultCodec) QApplication.setFont(QFont.new("lcfont",18)) app.showMainWidget(SampleWindow.new) app.exec