2012-03-25 4 views
0

저는 하루 종일 답을 찾아 보았습니다 (과거에 사용했기 때문에 존재한다는 것을 알고 있지만 잃어 버렸습니다).콤보 상자와 정적 항목을 데이터베이스 필드에 매핑하는 방법은 무엇입니까?

이 일반 SQL 테이블을 편집 폼의 위젯에 매핑했습니다. 관련된 SQL 모델에 매핑하는 데 문제가 없지만 DB 필드와 정적, 사전 설정된 항목이있는 콤보 상자 사이의 매핑을 만들려면 어떻게해야합니까?

e.e. '성별'필드에는 'M'또는 'F'가 있지만 콤보 박스에는 '남성'또는 '여성'이 표시됩니다.

답변

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