4

QTableView でコンボボックスを提供するために、次のデリゲートを実装しました。使用例は、一般にユーザーにとって意味のない列 (キー) (数値 ID など) を同等のテキストに置き換えることです。

以下のスニペットは (適切な値を保存するためにも) 機能しますが、3 つの問題があります。

  1. 同等のテキストではなく、元の値が表示されます。
  2. QTableView で行を選択すると、すべての列が提供されますが、このデリゲートを含む列は提供されません。
  3. 理想的には、ユーザーがクリックしてコンボボックスであることを確認しなくても、コンボボックスがそのように表示されるようにしたいと考えています。

注:キーは任意の文字列にすることができます (整数である必要はありません)。典型的な例は国です (値 "France" はキー "FR" に対応します)。

class ComboDelegate(QtGui.QItemDelegate):
    """
    A delegate that places a QComboBox in every
    cell of the column to which it is being applied
    """

    def __init__(self, parent, value_data):
        "Value_data is a list of tuples: (item, label)"
        QtGui.QItemDelegate.__init__(self, parent)
        self.value_data = value_data

    @property
    def items(self):
        "The list of items for display"
        return [item[0] for item in self.value_data]

    @property
    def labels(self):
        "The list of labels for display"
        return [item[1] for item in self.value_data]

    def item(self, label):
        "Get the item from a label"
        try:
            index = self.labels.index(label)
        except ValueError:
            pass
        print("Value no:  &%s" % index)
        return self.items[index]

    def createEditor(self, parent, option, index):
        "Create the editor (called each time)"

        combo = QtGui.QComboBox(parent)
        for duplet in self.value_data:
            # the duplet is label, item
            item, label = duplet
            combo.addItem(label)

        combo.currentIndexChanged.connect(self.currentIndexChanged)
        return combo

    def setEditorData(self, editor, index):
        editor.blockSignals(True)
        editor.setCurrentIndex(index.row())
        editor.blockSignals(False)

    def setModelData(self, editor, model, index):
        "This is the data stored into the field"
        print("Current text: %s" % editor.currentText())
        model.setData(index, self.item(editor.currentText()))

    def currentIndexChanged(self):
        self.commitData.emit(self.sender())
4

2 に答える 2