如何将静态项目的组合框映射到数据库字段?

问题描述:

我花了整整一天的时间寻找答案(我知道存在的答案,因为我过去使用过它,但已经丢失)。如何将静态项目的组合框映射到数据库字段?

我有这个普通的SQL表映射到编辑窗体上的小部件。 尽管我没有映射到相关SQL模型的问题,但是如何使用静态预设项目创建数据库字段和组合框之间的映射?

I.e. '性别'字段保存'M'或'F',但组合框显示“男性”或“女性”。

您可以使用QDataWidgetMapper::setItemDelegateQItemDelegate派生类中,将处理性别种列:

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