I'm using a QTreeView
with the default delegate to display editable model data. When I double-click or press F2 on the field I want to change, I get the text edit box, but the existing text is erased when the editor appears. I want the existing text to remain but become selected. The "editable tree model" example from the Qt documentation has this behavior exactly, however I can't for the life of me figure out how it is accomplished. The example does not use a custom delegate as far as I can tell and there are no calls related to delegate behavior that I can find. Can this be done without a custom delegate?
Edit: here's my code for the reimplemented 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();
}
Your model should return a data, that you want to see in ediitor, via Qt::EditRole
. If data is invalid (QVariant::isValid() == false)
then editor will request data via Qt::DisplayRole
.