编辑模式下QTreeView委托中的持久文本

Persistent text in a QTreeView delegate during edit mode

本文关键字:文本 模式 QTreeView 编辑      更新时间:2023-10-16

我使用带有默认委托的QTreeView来显示可编辑的模型数据。当我双击或按F2键在要更改的字段上时,我会得到文本编辑框,但当编辑器出现时,现有文本会被删除。我希望保留现有文本,但将其选中。Qt文档中的"可编辑树模型"示例正是具有这种行为,但是我一辈子都不知道它是如何实现的。据我所知,该示例没有使用自定义委托,也找不到与委托行为相关的调用。这可以在没有自定义委托的情况下完成吗?

编辑:这是我重新实现的QAbstractItemModel::data():的代码

QVariant projectModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();
    node* item = static_cast<node*>(index.internalPointer());
    if (role == Qt::DisplayRole)
        return QVariant(item->data(index.column()).c_str());
    else if (role == Qt::ForegroundRole)
        return item->text_color(index.column());
    else if (role == Qt::BackgroundRole)
        return item->background_color(index.column());
    else if (role == Qt::CheckStateRole)
        return item->check_state(index.column());
    else if (role == Qt::DecorationRole)
        return item->icon(index.column());
    else if (role == Qt::TextAlignmentRole)
        return item->text_alignment(index.column());
    else
        return QVariant();
}

您的模型应该通过Qt::EditRole返回您希望在ediitor中看到的数据。若数据是无效的(QVariant::isValid() == false),则编辑器将通过Qt::DisplayRole请求数据。