QListWidget调用setitemSelected后,再调用currentRow()返回的是-1,而不是当前选中的行索引
问题原因
-
setItemSelected()
与currentItem
的区别:-
setItemSelected()
只设置项目的选中状态,不会改变currentItem
-
currentRow()
返回的是currentItem
的行索引,而不是任意选中项
-
-
Qt 的设计逻辑:
-
一个 QListWidget 可以有多个选中项(在多选模式下)
-
但只能有一个
currentItem
(当前项,用于键盘导航等操作)
-
解决方案
方法1:同时设置 currentItem
// C++ 版本
int row = 2; // 要选中的行
QListWidgetItem* item = listWidget->item(row);
item->setSelected(true); // 设置选中状态
listWidget->setCurrentItem(item); // 同时设置为当前项
// 现在 currentRow() 会返回正确的行号
qDebug() << listWidget->currentRow(); // 输出 2