QListWidget调用setitemSelected后,再调用currentRow()返回的是-1,而不是当前选中的行索引

问题原因

  1. setItemSelected() 与 currentItem 的区别:

    • setItemSelected() 只设置项目的选中状态,不会改变 currentItem

    • currentRow() 返回的是 currentItem 的行索引,而不是任意选中项

  2. Qt 的设计逻辑:

    • 一个 QListWidget 可以有多个选中项(在多选模式下)

    • 但只能有一个 currentItem(当前项,用于键盘导航等操作)

解决方案

方法1:同时设置 currentItem

cpp
 
复制
 
下载
// C++ 版本
int row = 2; // 要选中的行
QListWidgetItem* item = listWidget->item(row);
item->setSelected(true);    // 设置选中状态
listWidget->setCurrentItem(item); // 同时设置为当前项

// 现在 currentRow() 会返回正确的行号
qDebug() << listWidget->currentRow(); // 输出 2
posted @ 2025-06-12 16:22  远方是什么样子  阅读(30)  评论(0)    收藏  举报