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

PySide2实现QTableView多列过滤时QRegExp无match属性如何解决

问题原因

你传入setFilterByColumn的参数是PySide2.QtCore.QRegExp实例,而原代理模型的匹配逻辑默认适配Python标准库re的正则对象,QRegExp不存在match方法,因此触发属性错误。

解决方法

提供两种可选修改方案:

方案一:调整调用逻辑,统一使用Python标准re(改动最小,推荐)

仅需要修改你调用setFilterByColumn的代码,不需要修改代理模型源码:

  1. 先导入Python标准正则模块:import re
  2. 将原来传入QRegExp的部分替换为re.compile生成的正则对象:
for i in range(model.columnCount()):
    self.lineEditSearchShotSets.textChanged.connect(lambda text, col=i:
                           self.filter_proxy_model_templates_shots.setFilterByColumn
                           (col, re.compile(text, re.IGNORECASE)))

方案二:修改代理模型,兼容QRegExp类型

如果需要保留QRegExp的使用,可以修改MultiFilterProxyModel的filterAcceptsRow方法中的匹配逻辑,区分不同正则类型调用对应方法:

def filterAcceptsRow(self, source_row, source_parent):
    if not self.filters:
        return True

    results = []
    for key, regex in self.filters.items():
        text = ''
        index = self.sourceModel().index(source_row, key, source_parent)
        if index.isValid():
            text = self.sourceModel().data(index, Qt.DisplayRole)
            if text is None:
                text = ''
        # 兼容两种正则对象
        if hasattr(regex, "match"):
            # Python标准re对象
            results.append(regex.match(str(text)))
        else:
            # QRegExp对象
            results.append(regex.exactMatch(str(text)))

    if self.multi_filter_mode == MultiFilterMode.OR:
        return any(results)
    return all(results)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 01:36:04