QTreeWidget: renaming item to empty

1.1k views Asked by At

just a quick and easy (maybe) question:

How do I prevent an edit on a QTreeWidgetItem from allowing an empty string?

Currently, I use QTreeWidgetItem::itemChanged(QTreeWidgetItem*, int) to check for modifications, and of course, I could just check for an empty string, but I don't have the previous text. So I'm left with setting a "default" QString, but this is bad...

Thanks & Cheers!

1

There are 1 answers

0
vahancho On

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();