3

我遵循模型/视图/控制器范式。我很确定模型和视图是正确的,但我认为我的代表做错了一些事情。一切都“正常工作”,除了第一次单击控件只是“点亮控件”并且第二个与之交互。这就是代表通常的实现方式吗?我的实现需要大量的构造和破坏(由 scoped_ptr 隐藏),因此任何有关这方面的提示也很有帮助。

QWidget *ParmDelegate::createWidget(const QModelIndex &index) const {
    if (!index.isValid())
        return NULL;
    const Parm  *p = static_cast<const Parm*>(index.internalPointer());
    QWidget *w = p->createControl();
    w->setAutoFillBackground(true);
    w->setBackgroundRole(QPalette::Base);  // white background instead of grey
    return w;
}

QWidget*
ParmDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    QWidget *retval = createWidget(index);
    if (dynamic_cast<QComboBox*>(retval))
        connect(retval, SIGNAL(activated(int)), this, SLOT(commitAndCloseEditor()));
    else if (dynamic_cast<QSlider*>(retval))
        connect(retval, SIGNAL(sliderReleased()), this, SLOT(commitAndCloseEditor()));
    else if (dynamic_cast<QAbstractButton*>(retval))
        connect(retval, SIGNAL(clicked()), this, SLOT(commitAndCloseEditor()));
    else
        connect(retval, SIGNAL(editingFinished()), this, SLOT(commitAndCloseEditor()));
    retval->setFocusPolicy(Qt::StrongFocus);
    retval->setParent(parent);
    return retval;
}

void
ParmDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const {
    const Parm  *p = static_cast<const Parm*>(index.internalPointer());
    p->setEditorData(editor);
}

void
ParmDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const {
    ParmControl::Base*  base = dynamic_cast<ParmControl::Base*>(editor);
    model->setData(index, base->toQVariant());
}

void
ParmDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    editor->setGeometry(option.rect);
}

void
ParmDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    scoped_ptr<QWidget> w(createWidget(index));
    if (!w)
        return;
    const Parm  *p = static_cast<const Parm*>(index.internalPointer());
    setEditorData(w.get(), index);
    w->setGeometry(option.rect);
    w->render(painter, option.rect.topLeft());
}

QSize
ParmDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const {
    scoped_ptr<QWidget> w(createWidget(index));
    if (!w)
        return QSize(0,0);
    return w->sizeHint();
}

void
ParmDelegate::commitAndCloseEditor() {
    QWidget *editor = static_cast<QWidget *>(sender());
    ParmControl::Base* base = dynamic_cast<ParmControl::Base*>(editor);
    emit commitData(editor);
    emit closeEditor(editor, QAbstractItemDelegate::EditNextItem);
}
4

1 回答 1

4

如果您有兴趣更改自定义编辑器的显示条件,请使用QAbstractItemView::setEditTriggers(). 尽管您的委托负责将信息传入和传出自定义编辑器,但视图决定了编辑器的启动时间。

文档参考:http ://doc.qt.digia.com/4.5/qabstractitemview.html#editTriggers-prop 。

于 2009-05-12T17:17:12.350 回答