I'm using Qt 4.8.6.
I have a QListWidget
. When the user click on an Add button, a new item is inserted at the end of the list and edition of the item's text is initiated:
void slot_add_item()
{
auto* item = new QListWidgetItem(QString());
item->setFlags(item->flags() | Qt::ItemIsEditable);
listWidget->addItem(item);
listWidget->setCurrentItem(item);
listWidget->editItem(item);
}
Based on this comment, I'm listening to the commitData
signal to catch when the user has finished editing the item and to remove it if the item's text is empty:
connect(
listWidget->itemDelegate(), SIGNAL(commitData(QWidget*)),
SLOT(slot_item_edited(QWidget*)));
...
void slot_item_edited(QWidget* widget)
{
const QString path = reinterpret_cast<QLineEdit*>(widget)->text();
if (path.isEmpty())
delete listWidget->currentItem();
}
However that doesn't catch the case where the user cancels editing with the Escape key: in that case, slot_item_edited()
is not called (expectedly) and the (empty) item is not removed.
Any idea on how to remove the item in that case?