正确的MVC兼容方式将QComboBox填充为QTableView委托

时间:2016-12-12 14:22:57

标签: qt model-view-controller delegates qtableview qcombobox

我一直在关注Qt QSpinBox委托example以在QTableView单元格中创建QComboBox编辑器委托。我能够通过使用委托类的私有数据成员来实现编辑器并使用来自外部源('字典')的项填充组合框:

delegate.h

class Delegate : public QItemDelegate
{    
    Q_OBJECT
public:
    explicit Delegate(QObject *parent = 0);
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
    void setEditorData(QWidget *editor, const QModelIndex &index) const;
    void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;

    //...

    void setDictionary(const QStringList &dict);
    void setCurrIndex(const qint16 &ind);

    //...

private:
    // the internal dictionary, wich is being filled from an external source
    QStringList dictionary;
    int currentIndex;
};

delegate.cpp

//...
QWidget *Delegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QComboBox *editor = new QComboBox(parent);

    editor->clear();
    editor->addItems(dictionary);

    return editor;
}

void Delegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QComboBox *cbox = qobject_cast<QComboBox*>(editor);
    QString str = index.model()->data(index, Qt::EditRole).toString();
    int idx = dictionary.indexOf(str);
    cbox->setCurrentIndex(idx);
}

    void Delegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QComboBox *cbox = qobject_cast<QComboBox*>(editor);
    QString val = cbox->currentText();
    model->setData(index, QVariant(val), Qt::EditRole);
}

void Delegate::setDictionary(const QStringList &dict)
{
    dictionary = dict;
}

void Delegate::setCurrIndex(const qint16 &ind)
{
    currentIndex = ind;
}

在窗口方法中使用已定义的外部源填充内部字典:

QStringList dict;
// ...    
// filling the dict with strings
// ...
mydelegate = new Delegate(this);
mydelegate->setDictionary(dict);

此解决方案是否与MVC兼容?如果没有,那我该怎么写一个正确的&#39; MVC风格的方法,为这些代表提供数据?

0 个答案:

没有答案