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

如何读取QTableView中已选中行/单元格的背景颜色

你可以直接通过data()方法显式指定Qt.BackgroundRole参数读取对应背景色,和你设置值的逻辑是对应的,实现代码如下:

# 1. 获取和你之前设置背景色位置对应的单元格index,这里以你之前设置的行第0列为例
target_index = index.sibling(index.row(), 0)
# 2. 显式指定BackgroundRole读取背景画刷
background_brush = target_index.data(Qt.BackgroundRole)

# 3. 判空后对比颜色,避免未设置背景的单元格报错
if background_brush and background_brush.color() == Qt.yellow:
    # 此处填写你要执行的对应操作
    pass

注意事项:

  • 必须给data()方法传入Qt.BackgroundRole参数,默认调用data()不传参数时读取的是单元格显示内容,拿不到背景属性
  • 如果你是给整行所有单元格都设置了黄色背景,取选中行任意一列的index读取都可以,只要和你之前setData的位置匹配即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:45:04