hakeの日記

Windows環境でプログラミングの勉強をしています。

引数付きシグナル

Ruby/Qteの勉強 その41
画面をタップしてその座標をテキストエリアに表示するプログラム。MyWidgetのmousePressEventにてシグナルtappedを発生、それを受けてMyLineEditのdispPosメソッドで座標を表示させる。その際にシグナルの引数として座標を示すクラスMyPointのオブジェクトを渡す。
シグナルで引数を持つ場合はオブジェクト作成の際にRSignal.new("Object")とし、sendWithで引数を渡す。
詳細は以下
http://noir.s7.xrea.com/rubyqte/?Ruby%2FQte%CE%AE%A5%B7%A5%B0%A5%CA%A5%EB%A1%A6%A5%B9%A5%ED%A5%C3%A5%C8#l2
Qtのオブジェクトには渡せない型があるとのことで、試しにQPointを引数にしてみたらエラーになった。

#!/usr/bin/env ruby

require "qte"
require "qpe"
include Qte
include Qpe


class SampleWindow < QMainWindow
  def initialize()
    super()
    setCaption(tr("サンプル"))

    @h = QVBox.new(self)
    setCentralWidget(@h)

    @w = MyWidget.new(@h)
    @e = MyLineEdit.new(@h)

#   connect(@w.tapped, self, "tapped")
    connect(@w.tapped, @e, "dispPos")
  end

# def tapped(pos)
#   @e.setText("x = #{pos.x}, y = #{pos.y}")
# end
end

class MyWidget < QWidget
  attr_reader :tapped

  def initialize(parent)
    super(parent)
#   @tapped = RSignal.new("QPoint")
#   @pos = QPoint.new(0,0)
    @tapped = RSignal.new("Object")
    @pos = MyPoint.new(0,0)
    catchEvent
  end

  def mousePressEvent(e)
    @pos.setX(e.x)
    @pos.setY(e.y)
    @tapped.sendWith(@pos)
  end
end

class MyLineEdit < QLineEdit
  def initialize(parent)
    super(parent)
  end

  def dispPos(pos)
    setText("x = #{pos.x}, y = #{pos.y}")
  end
end

class MyPoint
  attr_reader :x, :y
  def initialize(x = 0, y = 0)
    @x = x
    @y = y
  end
  def setX(x)
    @x = x
  end
  def setY(y)
    @y = y
  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