添加时选择QListWidgetItem

 收藏

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:

  1. A QInputDialog::getText asks for the content of the new item.
  2. A new item is added to the list with the given text.
  3. The list is sorted, except for the "Add new" that stays at the end (this is done by removing the "Add new" item, sorting, and adding the removed item again).
  4. The new item is selected.

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);

我注意到的

当调试器在断点上缓慢执行这些步骤时,我注意到一切似乎都正常运行,但是UI并没有在我调用的函数完成之前进行更新。

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).

我的猜测:我无法在添加功能的同时选择该项目,因为我无法以图形方式选择尚不存在的项目。

关于如何实现这一目标的任何猜测?

注意

如果您遇到相同的问题,请阅读所选答案的评论,这实际上是一个信号问题!

回复
  • 祈~祷 回复

    如果您可以从常规插槽中选择项目,那么只需从很短的计时器中发出虚拟信号即可。像这样

    //add item
    //...
    QTimer::singleShot(1, this, SLOT(MySlotForSelectItem())); // 1 ms timer
    
    MainWindow::MySlotForSelectItem()
    {
         //select item
    }
    

  • 也,許 回复

    您是否尝试选择添加的项目,然后将当前行设置为添加项目的行索引。这在我的示例中有效。

    示例: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));
        }
    }