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

如何让QListView显示QPdfSearchModel的完整PDF搜索结果(含页码)?

解决PySide6 QPdfSearchModel不显示页码的问题

QPdfSearchModel本身包含搜索结果的页码信息,但默认QListView只展示Qt.DisplayRole对应的上下文文本。要显示页码,需要自定义委托来同时绘制上下文和页码数据,具体修改步骤如下:

1. 添加自定义委托类

在mainwindow.py中新增一个继承自QStyledItemDelegate的委托类,用于自定义搜索结果项的显示:

from PySide6.QtWidgets import QStyledItemDelegate, QStyle
from PySide6.QtGui import QPainter, QTextOption
from PySide6.QtCore import Qt
from PySide6.QtPdf import QPdfSearchModel

class SearchResultDelegate(QStyledItemDelegate):
    def paint(self, painter: QPainter, option: QStyle.OptionViewItem, index):
        # 初始化绘制环境
        super().paint(painter, option, index)
        
        # 获取页码(模型返回的页码从0开始,加1转为用户习惯的1起始)
        page_num = index.data(QPdfSearchModel.PageNumberRole) + 1
        # 获取搜索上下文文本
        context_text = index.data(Qt.DisplayRole)
        
        painter.save()
        # 配置文本绘制选项:左对齐、自动换行
        text_option = QTextOption()
        text_option.setAlignment(Qt.AlignLeft | Qt.AlignTop)
        text_option.setWrapMode(QTextOption.WordWrap)
        
        # 绘制上下文文本,右侧预留60px空间显示页码
        context_rect = option.rect.adjusted(0, 0, -60, 0)
        painter.drawText(context_rect, context_text, text_option)
        
        # 绘制灰色页码,右对齐显示
        page_rect = option.rect.adjusted(option.rect.width() - 55, 0, 0, 0)
        painter.setPen(Qt.gray)
        painter.drawText(page_rect, f"第 {page_num} 页", QTextOption(Qt.AlignRight | Qt.AlignVCenter))
        
        painter.restore()

    def sizeHint(self, option: QStyle.OptionViewItem, index):
        # 自定义行高,适配换行后的文本高度
        base_hint = super().sizeHint(option, index)
        base_hint.setHeight(max(base_hint.height(), 40))
        return base_hint

2. 为QListView设置自定义委托

在MainWindow的初始化代码中(比如setupUi方法内),找到你的QListView实例,设置上面定义的委托:

# 假设你的QListView对象名为search_result_list
self.search_result_list.setItemDelegate(SearchResultDelegate(self))

3. 确保搜索模型正确关联

确认QPdfSearchModel已正确绑定PDF文档和QListView:

# 初始化搜索模型并关联PDF文档
self.search_model = QPdfSearchModel(self)
self.search_model.setDocument(self.pdf_viewer.document())
# 将模型绑定到QListView
self.search_result_list.setModel(self.search_model)

关键说明

  • QPdfSearchModel提供了多个数据角色,其中QPdfSearchModel.PageNumberRole用于获取搜索结果所在的页码(0起始),Qt.DisplayRole对应搜索上下文文本。
  • 通过自定义委托,可以自由组合不同角色的数据,实现同时显示上下文和页码的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 03:37:56