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

时间:2012-03-25 18:40:53

标签: qt combobox mapper

我花了一整天的时间寻找答案(我知道这个答案存在,因为我过去曾经使用它但却丢失了)。

我将这个普通的SQL表映射到编辑表单上的小部件。 虽然我没有映射到相关SQL模型的问题,但如何使用静态预设项创建DB字段和组合框之间的映射?

即。 'gender'字段包含'M'或'F',但组合框显示“男性”或“女性”。

1 个答案:

答案 0 :(得分: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;
};