c++qtqt5qlistwidgetqlistwidgetitem

QListWidget's editItem() outputs "edit: editing failed"


I am attempting to add an item to a QListWidget, select that item, and then begin editing the new item.

The item gets added, and it gets selected, but the line is not brought into a QLineEdit, or whatever it would attempt to use.

Here's the code for my widget, with the relevant code under the connect for "m_addButton":

Sequencer::Sequencer(QWidget* parent) :
    QWidget(parent)
{
    m_list = new QListWidget();
    m_addButton = new QPushButton("Add Step");
    m_removeButton = new QPushButton("Remove Step");

    connect(m_addButton, &QPushButton::clicked, this, [&]()
    {
        m_list->addItem(""); // This part works,
        m_list->setCurrentItem(m_list->item(m_list->count() - 1)); // This part works...
        m_list->editItem(m_list->currentItem()); // This part puts out "edit: editing failed" into the console.
    });

    connect(m_removeButton, &QPushButton::clicked, this, [&]()
    {
        if (!m_list->selectedItems().isEmpty())
        {
            qDeleteAll(m_list->selectedItems());
        }
    });

    QHBoxLayout* hLayout = new QHBoxLayout();
    hLayout->addStretch();
    hLayout->addWidget(m_addButton);
    hLayout->addWidget(m_removeButton);

    QVBoxLayout* vLayout = new QVBoxLayout();
    vLayout->addWidget(m_list);
    vLayout->addLayout(hLayout);

    setLayout(vLayout);
}

Solution

  • By default a QListWidgetItem is not editable so if you want it to be, you must enable the Qt::ItemIsEditable flag:

    connect(m_addButton, &QPushButton::clicked, this, [&]()
    {
        QListWidgetItem *item = new QListWidgetItem;
        item->setFlags(item->flags() | Qt::ItemIsEditable); # enable
        m_list->addItem(item);
        m_list->setCurrentItem(item);
        m_list->editItem(item);
    });