Pyqt-qcombobox-widget

提供:Dev Guides
移動先:案内検索

PyQt-QComboBoxウィジェット

*QComboBox* オブジェクトは、選択するアイテムのドロップダウンリストを提供します。 現在選択されている項目のみを表示するために必要なフォーム上の最小画面スペースが必要です。

コンボボックスは編集可能に設定できます。 pixmapオブジェクトも保存できます。 以下の方法が一般的に使用されます-

以下に、QComboBoxで最も一般的に使用される方法を示します。

Sr.No. Methods & Description
1

addItem()

コレクションに文字列を追加します

2

addItems()

リストオブジェクトにアイテムを追加します

3

Clear()

コレクション内のすべてのアイテムを削除します

4

count()

コレクション内のアイテムの数を取得します

5

currentText()

現在選択されているアイテムのテキストを取得します

6

itemText()

特定のインデックスに属するテキストを表示します

7

currentIndex()

選択したアイテムのインデックスを返します

8

setItemText()

指定したインデックスのテキストを変更します

QComboBox信号

Sr.No. Methods & Description
1

activated()

ユーザーがアイテムを選択したとき

2

currentIndexChanged()

現在のインデックスがユーザーまたはプログラムによって変更されたとき

3

highlighted()

リスト内のアイテムが強調表示されている場合

次の例で、QComboBoxウィジェットのいくつかの機能がどのように実装されているかを見てみましょう。

アイテムは、addItem()メソッドによってコレクションに個別に追加されるか、addItems()メソッドによってListオブジェクトにアイテムが追加されます。

self.cb.addItem("C++")
self.cb.addItems(["Java", "C#", "Python"])

QComboBoxオブジェクトはcurrentIndexChanged()シグナルを発信します。 selectionchange()メソッドに接続されています。

コンボボックス内のアイテムは、各アイテムに対してitemText()メソッドを使用してリストされます。 現在選択されているアイテムに属するラベルは、currentText()メソッドによってアクセスされます。

def selectionchange(self,i):
   print "Items in the list are :"

   for count in range(self.cb.count()):
      print self.cb.itemText(count)
   print "Current index",i,"selection changed ",self.cb.currentText()

コード全体は次のとおりです-

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class combodemo(QWidget):
   def __init__(self, parent = None):
      super(combodemo, self).__init__(parent)

      layout = QHBoxLayout()
      self.cb = QComboBox()
      self.cb.addItem("C")
      self.cb.addItem("C++")
      self.cb.addItems(["Java", "C#", "Python"])
      self.cb.currentIndexChanged.connect(self.selectionchange)

      layout.addWidget(self.cb)
      self.setLayout(layout)
      self.setWindowTitle("combo box demo")

   def selectionchange(self,i):
      print "Items in the list are :"

      for count in range(self.cb.count()):
         print self.cb.itemText(count)
      print "Current index",i,"selection changed ",self.cb.currentText()

def main():
   app = QApplication(sys.argv)
   ex = combodemo()
   ex.show()
   sys.exit(app.exec_())

if __name__ == '__main__':
   main()

上記のコードは、次の出力を生成します-

QComboBoxウィジェット出力

リスト内のアイテムは-

C
C++
Java
C#
Python
Current selection index 4 selection changed Python