How to map a combobox with static items to database field?
Question
I've spent whole day looking for the answer (which I know exists, because I used it in the past but was lost).
I have this ordinary SQL table mapped to widgets on edit form. While I don't have problems with mapping to related SQL models, how can I create a mapping between DB field and a combobox with static, pre-set items?
I.e. 'gender' field holds 'M' or 'F', but the combobox shows either "Male" or "Female".
La solution
You can use QDataWidgetMapper::setItemDelegate
and write QItemDelegate
derived class that would handle the gender model column:
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
You can write a QComboBox
derived class and define a custom property that QDataWidgetMapper
can use to read/write the gender letter:
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;
};
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow