I have a QTreeWidget
and two buttons "+" and "-". When I press "+" I want to add new item to QTreeWidget and I want that item to be in edit mode. I managed to do that with following code (it gets called every time "+" is pressed):
// QTreeWidgetItem* lastItem = getLastItem();
// if (lastItem) { widget->closePersistentEditor(lastItem); }
QTreeWidgetItem* item = new QTreeWidgetItem(widget, {"100000"});
item->setFlags(item->flags() | Qt::ItemIsEditable);
widget->addTopLevelItem(item);
widget->editItem(item);
Problem is when I try to add a new item, but don't exit edit mode before adding (press Enter or something). I get error edit: editing failed
and new item is added below current item (which is still in edit mode).
What I would like is that current item exists edit mode and that newly added item becomes focused and enters edit mode.
I tried to do that with first getting the last item in a QTreeWidget
and calling closePersistentEditor(lastItem)
(commented code) and then creating and adding new item, but it didn't work. So, how to close currently opened edit on item?
EDIT:
Ok, I have added additional code with minimal example. Only thing you have to do to build it is to add QTreeWidget
and QPushButton
to the form mainwindow.ui
and connect that button to on_btnAdd_clicked()
:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTreeWidget>
#include <QTreeWidgetItem>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_btnAdd_clicked()
{
QTreeWidgetItem* item = new QTreeWidgetItem(ui->treeWidget, {"100000"});
item->setFlags(item->flags() | Qt::ItemIsEditable);
ui->treeWidget->addTopLevelItem(item);
ui->treeWidget->editItem(item);
}
EDIT2: This is happening on macOS (Mojave) with Qt 5.12.
Ok, it looks like this is a bug in Qt for macOS. Workaround that I did is following:
QTreeWidgetItem* lastItem = getLastTreeWidgetItem(widget);
if (lastItem) {
widget->setDisabled(true);
widget->setDisabled(false);
}
conversation->setFlags(conversation->flags() | Qt::ItemIsEditable);
getLastTreeWidget()
is my own method that returns last added item in a QTreeWidget
. Now every time when I press button to add new item, previous gets deselected and newly added enters edit mode.