I would suggest using the item delegate for your tree widget to handle the possible user input. Below is the simplified solution.
The implementation of item delegate:
class Delegate : public QItemDelegate
{
public:
void setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
if (!lineEdit->isModified()) {
return;
}
QString text = lineEdit->text();
text = text.trimmed();
if (text.isEmpty()) {
// If text is empty, do nothing - preserve the old value.
return;
} else {
QItemDelegate::setModelData(editor, model, index);
}
}
};
Implementation of the simple tree widget with an editable item and custom item delegate:
QTreeWidget tw;
QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget*)0,
QStringList(QString("item 1")));
item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsEditable);
tw.addTopLevelItem(item);
tw.setItemDelegate(new Delegate);
tw.show();