Reputation: 6134
I have a QListWidget
in a Form with a QListWidgetItem
displaying "Add new". When I click on it, I'd like a serie of things to happen:
QInputDialog::getText
asks for the content of the new item.That last part is the one I'm having trouble. I've tried many different approaches, all leading to the same result: the item I want selected has a dashed border and it understood as selected (by ui->list->selectedItems()
for example), but the selection color stays on the last item before the "Add new".
item->setSelected(true);
ui->list->setCurrentItem(item);
ui->list->setCurrentRow(ui->list->row(item);
When the debugger is on with a breakpoint that slowly goes through those steps, I notice everything seems to work nicely, but the UI isn't updated before the function I'm calling is done.
Also, when I want to select a given item from the list from a slot called by another button click, it works correctly with item->setSelected(true);
(and the others too).
My guess: I can't select the item in the same function I add it because I can't graphically select something that isn't there yet.
Any guess on how to achieve this?
If you're experiencing the same problem, please read the comment on the selected answer, it was actually a signal problem!
Upvotes: 0
Views: 777
Reputation: 441
Did you try to select added item and after that set current row to row index of added item. This works in my example.
Example: mainwindow.cpp
#include <QInputDialog>
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->listWidget->addItem("Add New");
connect(ui->listWidget, SIGNAL(itemClicked(QListWidgetItem *)), this, SLOT(slot_itemClicked(QListWidgetItem *)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::slot_itemClicked(QListWidgetItem *item)
{
if (item && (item->text() == "Add New"))
{
QString text = QInputDialog::getText(this, "Input item text", "Text: ");
QListWidgetItem *newItem = new QListWidgetItem(text);
// Add new item and sort list
ui->listWidget->addItem(newItem);
ui->listWidget->sortItems();
// Move "Add New" item to list end
item = ui->listWidget->takeItem(ui->listWidget->row(item));
ui->listWidget->addItem(item);
// Select new item
// Set current row to index of new item row
newItem->setSelected(true);
ui->listWidget->setCurrentRow(ui->listWidget->row(newItem));
}
}
Upvotes: 1
Reputation: 1122
If you can select item from regular slot so just emit dummy signal from very short timer. Like this
//add item
//...
QTimer::singleShot(1, this, SLOT(MySlotForSelectItem())); // 1 ms timer
MainWindow::MySlotForSelectItem()
{
//select item
}
Upvotes: 0