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

如何在添加数据到QTableWidget前按指定类型过滤列表?

问题分析与修复方案

你的代码存在两个致命问题导致程序无预警终止,同时还有逻辑错误无法实现过滤效果:

  1. filter函数完全用错
    Python内置filter()的第一个参数必须是返回布尔值的判断函数,第二个参数是可迭代对象。你直接把下拉框文本choice(字符串)当判断函数传入,会触发类型错误——字符串无法作为函数调用,程序因此直接崩溃。

  2. 过滤逻辑缺失
    你没有对Technology.TECHNOLOGY中的对象做类型匹配判断,反而错误地用filter处理单个Technology实例t,完全偏离了过滤需求。

另外还有一个逻辑bug:row = 0放在循环内部,导致每次插入数据都会覆盖第0行,永远只能显示最后一条数据。


修复后的代码

def show_types(self):
    # 清空表格现有内容
    for i in reversed(range(self.ui.tbl_collection.rowCount())):
        self.ui.tbl_collection.removeRow(i)

    Technology.load_from_file()
    choice = self.ui.cb_type_2.currentText()
    row = 0  # 行号初始化移到循环外
    # 遍历所有技术对象,只保留类型匹配的条目
    for t in Technology.TECHNOLOGY:
        if t.type == choice:
            self.ui.tbl_collection.insertRow(row)
            self.ui.tbl_collection.setItem(row, 0, QTableWidgetItem(t.manufacture))
            self.ui.tbl_collection.setItem(row, 1, QTableWidgetItem(t.model))
            self.ui.tbl_collection.setItem(row, 2, QTableWidgetItem(t.type))
            self.ui.tbl_collection.setItem(row, 3, QTableWidgetItem(t.price))
            self.ui.tbl_collection.setItem(row, 4, QTableWidgetItem(t.dom.strftime("%d/%m/%Y")))
            self.ui.tbl_collection.setItem(row, 5, QTableWidgetItem(t.dal.strftime("%d/%m/%Y")))
            row += 1

关键修复说明

  • 去掉错误的filter调用,直接用if t.type == choice做精确匹配判断,逻辑清晰且符合需求。
  • 将row = 0移到循环外部,确保每插入一条数据行号递增,不会覆盖之前的内容。
  • 如果需要模糊匹配(比如下拉框文本是类型的一部分),可以把判断条件改成:
    if choice in t.type:
    

内容的提问来源于stack exchange,提问作者jake mc gahern

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 18:19:54