hakeの日記

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

コンボボックスをつくる

Ruby/Qteの勉強 その10

コンボボックスの作成はQComboBoxを用いる。項目の追加は.insertItemを使用

@comb1 = QComboBox.new(self)

@comb1.insertItem(tr("項目1"))
@comb1.insertItem(tr("項目2"))
@comb1.insertItem(tr("項目3"))

現在どの項目が選択されているかは.currentItem.to_iのようにして数値に変換して得る。値は0からとなる。
またプログラム側で選択項目を変更する場合は.setCurrentItem(n)を用いる、nは0から始まる数値。

現在選択されている項目を表示するメソッドchk_comboと選択項目を次の項目へ変更するメソッドinc_comboをボタン1とボタン2に割り当ててみる。

#!/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(10,10,300,30)

      @comb1 = QComboBox.new(self)
      @comb1.setGeometry(0,50,300,40)

      @comb1.insertItem(tr("項目1"))  #コンボボックスに項目追加
      @comb1.insertItem(tr("項目2"))
      @comb1.insertItem(tr("項目3"))


      @ebox1 = QMultiLineEdit.new(self)
      @ebox1.setGeometry(0,280,635,120)
      @ebox1.setReadOnly(true)

      @pb1 = QPushButton.new(tr("ボタン1"),self)
      @pb1.setGeometry(320,5,100,30)
      connect(@pb1,QSIGNAL("clicked()"), self, 'chk_combo')

      @pb2 = QPushButton.new(tr("ボタン2"),self)
      @pb2.setGeometry(425,5,100,30)
      connect(@pb2,QSIGNAL("clicked()"), self, 'inc_combo')
   end

   def chk_combo
      case @comb1.currentItem.to_i      #現在の項目を取得
      when 0
         @ebox1.setText(tr("項目1が選択されています"))
      when 1
         @ebox1.setText(tr("項目2が選択されています"))
      when 2
         @ebox1.setText(tr("項目3が選択されています"))
      end
   end

   def inc_combo
      i = @comb1.currentItem.to_i + 1  #現在の項目を取得し、+1する
      i = 0 if i == 3                  #もし値が3ならば0にする
      @comb1.setCurrentItem(i)         #値をコンボボックスにセット
      case i
      when 0
         @ebox1.setText(tr("項目1を選択しました"))
      when 1
         @ebox1.setText(tr("項目2を選択しました"))
      when 2
         @ebox1.setText(tr("項目3を選択しました"))
      end
   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