我花了一整天的时间寻找答案(我知道它存在,因为我过去使用过它但迷路了)。
我将这个普通的 SQL 表映射到编辑表单上的小部件。虽然我在映射到相关 SQL 模型时没有问题,但如何在 DB 字段和带有静态预设项的组合框之间创建映射?
即“性别”字段包含“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);
}
}
或者
您可以编写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;
};