我正在继承QAbstractItemDelegate。这是我的代码。欢迎提出建议:

QWidget *ParmDelegate::createWidget(Parm *p, const QModelIndex &index) const {
    QWidget *w;
    if (index.column() == 0) {
        w = new QLabel(p->getName().c_str());
    } else {
        if (p->isSection())
            return NULL;
        w = p->createControl();
    }
    return w;
}

QWidget *ParmDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    cout << "createEditor called" << endl;
    Parm    *p = reinterpret_cast<Parm*>(index.internalPointer());
    QWidget *retval = createWidget(p, index);
    retval->setFocusPolicy(Qt::StrongFocus);
    retval->setParent(parent);
    return retval;
}

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

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

QSize ParmDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const {
    Parm    *p = reinterpret_cast<Parm*>(index.internalPointer());
    scoped_ptr<QWidget> w(createWidget(p, index));
    if (!w)
        return QSize(0,0);
    return w->sizeHint();
}

bool ParmDelegate::editorEvent(QEvent * event, QAbstractItemModel * model, const QStyleOptionViewItem & option, const QModelIndex & index ) {
    cout << "editorEvent called" << endl;
    return false;
}

当这个运行时,我只看到每个编辑事件都会调用两次editorEvent - 没有createEditor!

有帮助吗?

解决方案

来自Qt的 AbstractItemDelegate 文档:

  

要提供自定义编辑,可以使用两种方法。第一种方法是创建一个编辑器小部件并直接在项目顶部显示它。为此,您必须重新实现createEditor()以提供编辑器窗口小部件,setEditorData()以使用模型中的数据填充编辑器,以及setModelData(),以便委托可以使用编辑器中的数据更新模型。

     

第二种方法是通过重新实现editorEvent()来直接处理用户事件。

这似乎表明你错过了触发第一种方法的东西。我的猜测是你的模型的 data()函数没有返回 Qt :: EditRole 选项的正确值。

其他提示

我已经实现了一个我从QItemDelegate中获取的TableView。然后我有类似的问题。我跟踪它没有调用'return QItemDelegate :: editorEvent(event,model,option,index);'在editorEvent(...)方法中。

你可以试试这个。也许有帮助。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top