2012-03-25 7 views
0

私は一日中、答えを探しました(私が知っているのは、過去に使っていたが、紛失していたからです)。コンボボックスを静的アイテムとデータベースフィールドにどのようにマップするのですか?

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

I.e. 'gender'フィールドは 'M'または 'F'を保持しますが、コンボボックスは 'Male'または 'Female'のいずれかを示します。

あなたが QDataWidgetMapper::setItemDelegateを使用し、ジェンダーモデル列を扱うでしょう QItemDelegate派生クラスを作成することができます

答えて

3

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); 
    }  
}  

OR

あなたは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; 
}; 
関連する問題