Qt 如何将带有静态项的组合框映射到数据库字段?
我花了一整天的时间寻找答案(我知道答案是存在的,因为我过去用过它,但后来找不到了) 我将这个普通的SQL表映射到编辑表单上的小部件。 虽然我在映射到相关SQL模型方面没有问题,但如何在DB字段和带有静态预设项的组合框之间创建映射Qt 如何将带有静态项的组合框映射到数据库字段?,qt,combobox,mapper,Qt,Combobox,Mapper,我花了一整天的时间寻找答案(我知道答案是存在的,因为我过去用过它,但后来找不到了) 我将这个普通的SQL表映射到编辑表单上的小部件。 虽然我在映射到相关SQL模型方面没有问题,但如何在DB字段和带有静态预设项的组合框之间创建映射 例如,“性别”字段包含“M”或“F”,但组合框显示“男性”或“女性”。您可以使用QDataWidgetMapper::setItemDelegate并编写QItemDelegate派生类来处理性别模型列: void ItemDelegate::setEditorData
例如,“性别”字段包含“M”或“F”,但组合框显示“男性”或“女性”。您可以使用
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);
}
}
您可以使用
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);
}
}