Remove editable item from QListWidget if empty

隐身守侯 提交于 2019-12-11 05:08:28

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/50409139/remove-editable-item-from-qlistwidget-if-empty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!