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?
You can connect to closeEditor signal of the delegate instead of
commitData
signal:closeEditor
signal is emitted when the editor is closed regardless of the fact whether any new data was entered into the model or not.