You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Squish自动化PyQt QListView时获取文本为空,求解决方法

解决Squish中QListView图标模式下获取项文本的问题

我之前也踩过类似的坑,手动调用model().data()返回空字符串,大概率是没指定正确的数据角色,或者获取QModelIndex的方式不够可靠。给你几个实用的解决方案:

方法1:指定DisplayRole获取文本

QModelIndex的data()方法默认使用的角色不一定是显示文本的角色,在图标模式下必须明确指定Qt.DisplayRole才能拿到项的显示文本。代码示例:

from squish import *
from PyQt5.QtCore import Qt  # 若使用PyQt4则替换为PyQt4.QtCore

targetList = waitForObject("{name='someListView' type='QListView'}")
model_index = object.children(targetList)[11]

# 先校验索引是否有效
if model_index.isValid():
    # 指定DisplayRole获取显示文本
    item_text = model_index.model().data(model_index, Qt.DisplayRole).toString()
    print(item_text)
else:
    print("Warning: 获取到的QModelIndex无效!")

方法2:使用Squish内置的itemText()函数(推荐)

Squish专门为Qt视图控件封装了便捷工具函数,itemText()可以直接获取视图项的文本,不需要手动操作模型和索引,而且适配图标、列表等多种视图模式,稳定性更高:

from squish import *

targetList = waitForObject("{name='someListView' type='QListView'}")

# 方式1:通过项的索引直接获取(注意:索引从0开始计数)
item_text = itemText(targetList, 11)

# 方式2:先获取项对象,再提取文本
item_obj = waitForObjectItem(targetList, 11)
item_text = itemText(item_obj)

print(item_text)

方法3:通过选择模型获取选中项文本

如果你实际需求是获取选中项的文本,还可以通过视图的选择模型来精准获取:

from squish import *
from PyQt5.QtCore import Qt

targetList = waitForObject("{name='someListView' type='QListView'}")
selection_model = targetList.selectionModel()
# 获取第一个选中的索引(若多选可遍历selectedIndexes())
selected_index = selection_model.selectedIndexes()[0]

if selected_index.isValid():
    item_text = selected_index.model().data(selected_index, Qt.DisplayRole).toString()
    print(item_text)

小提醒

  • 尽量别用object.children()来获取QModelIndex,控件的子元素顺序可能随Qt版本、布局变化而改变,容易导致索引失效。
  • 优先使用Squish提供的封装函数,比如waitForObjectItem()、itemText(),这些工具经过官方测试,兼容性和稳定性都更有保障。

内容的提问来源于stack exchange,提问作者Shaiju Janardhanan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:11:38