0

私は一日中答えを探していました(私は過去にそれを使用したが失われたので、存在することを知っています)。

この通常の SQL テーブルを編集フォームのウィジェットにマップしています。関連する SQL モデルへのマッピングに問題はありませんが、DB フィールドと静的で事前設定されたアイテムを含むコンボボックスとの間のマッピングを作成するにはどうすればよいですか?

つまり、「性別」フィールドには「M」または「F」が入りますが、コンボボックスには「男性」または「女性」が表示されます。

4

1 に答える 1

3

性別モデル列を処理する派生クラスを使用QDataWidgetMapper::setItemDelegateおよび作成できます。QItemDelegate

void ItemDelegate::setEditorData ( QWidget * editor, const QModelIndex & index ) const {
    if(index.column() == GenderColumnIndex) {
        QComboBox *combobox = qobject_cast<QComboBox*>(editor);
        Q_ASSERT(combobox);
        if(index.data().toString() == "M") {
           combobox->setCurrentIndex(0);
        } else {
           combobox->setCurrentIndex(1);
        }
    } else {
        QItemDelegate::setEditorData(editor, index);
    }
}
void ItemDelegate::setModelData ( QWidget * editor, QAbstractItemModel * model, const QModelIndex & index ) const {
    if(index.column() == GenderColumnIndex) {
        QComboBox *combobox = qobject_cast<QComboBox*>(editor);
        Q_ASSERT(combobox);
        if(combobox->currentIndex() == 0) {
           model->setData(index, "M");
        } else {
           model->setData(index, "F");
        }
    } else {
        QItemDelegate::setModelData(editor, model, index);
    }       
}    

また

QComboBox派生クラスをQDataWidgetMapper作成し、性別文字の読み取り/書き込みに使用できるカスタムプロパティを定義できます。

class QGenderComboBox : public QComboBox
{
    Q_OBJECT
    // If you set USER to true, you can omit the propertyName parameter
    // when you call QDataWidgetMapper::addMapping
    Q_PROPERTY(QString value READ value WRITE setValue USER true)

public:
    QGenderComboBox(QWidget *parent);

    // Sets the currentIndex from the gender letter
    void setValue(const QString);

    // Returns the letter from the currentIndex
    QString value() const;
};
于 2012-03-26T01:19:22.953 に答える