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.
QTreeWidget
does not have agetLastItem
method. – scopchanovgetLastItem
is the OP-s own method. @dosvarog, can you share some more details about your code (maybe even a reproducible code snippet which demonstrates the issue)? Do you use a model behind the view? And if yes, do you add the new item via the model? – zgyarmati