Search code examples
c++qtqtreewidgetqtreewidgetitem

Is it possible to know whenever an item in a tree has been renamed?


I'm using a QTreeWidget. I allowed the user to rename items in the tree. Yet, whenever an item is renamed I have to manage something in the background. So I need to figure out when the user renames an item. I've seen the slot "ItemChanged" but I don't know if this slot is used only when an item is renamed.

here is how I set the item as renamable.

default_item->setSelected(true);
default_item->setFlags(default_item->flags() | Qt::ItemIsEditable);

Solution

  • The itemChanged signal is emitted whenever data changes for any of the roles in the item. That includes when the Qt::DisplayRole changes because the user edited the name, or when you call QTreeWidgetItem::setData. It's also emitted in some other cases like when flags change and when the item is enabled/disabled.

    If you want to know only when the name changes, then you can connect directly to the dataChanged signal of the underlying model and inspect the roles argument for the Qt::DisplayRole role. For example:

    connect(treeWidget->model(), &QAbstractItemModel::dataChanged,
    [](const QModelIndex &index, const QModelIndex &, const QVector<int> &roles) {
      if (roles.contains(Qt::DisplayRole))
        qDebug("Display role changed!");
    });