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

PySide6中QPdfDocument.getSelection返回无效QPdfSelection的问题求助

PySide6中QPdfDocument.getSelection返回无效QPdfSelection的问题求助

大家好,我最近在使用PySide6处理PDF文本选择时碰到了一个非常棘手的问题:调用QPdfDocument.getSelection()方法时,无论传入什么参数,返回的都是无效的QPdfSelection实例,它的boundingRectangle始终是全0的矩形,但相同文档调用getAllText()却能正常返回有效的选择结果,完全符合预期。

问题详情

我先通过getAllText()获取指定页面的全部文本选择,得到的结果完全正常——isValid()返回True,boundingRectangle也有合理的数值:

selection: QPdfSelection = document.getAllText(1)
print(selection.isValid(), selection.boundingRectangle())
# 输出:True PySide6.QtCore.QRectF(72.000000, 72.000000, 451.000000, 728.000000)

接着我直接用这个有效选择的boundingRectangle的左上角和右下角坐标作为参数,传给getSelection()方法,结果却得到了完全无效的选择:

top_left: QPointF = selection.boundingRectangle().topLeft()
bottom_right: QPointF = selection.boundingRectangle().bottomRight()
selection: QPdfSelection = document.getSelection(current_page, top_left, bottom_right)
print(selection.isValid(), selection.boundingRectangle())
# 输出:False PySide6.QtCore.QRectF(0.000000, 0.000000, 0.000000, 0.000000)

我试过调整传入的坐标参数(比如手动输入不同的页面坐标),结果都是一样的——始终返回无效的QPdfSelection。

最小可复现示例

首先安装指定版本的依赖:

pip install pyside6==6.9.2

完整测试代码(记得替换成你本地的PDF文件路径):

from PySide6.QtCore import QPointF
from PySide6.QtPdf import QPdfDocument, QPdfSelection

document: QPdfDocument = QPdfDocument(None)
# 替换为你本地的PDF文件路径
document.load("filename.pdf")
current_page: int = 1

print("# getAllText()")
selection: QPdfSelection = document.getAllText(current_page)
print(selection.isValid(), selection.boundingRectangle())
# 预期输出:True PySide6.QtCore.QRectF(72.000000, 72.000000, 451.000000, 728.000000)

top_left: QPointF = selection.boundingRectangle().topLeft()
bottom_right: QPointF = selection.boundingRectangle().bottomRight()
print(top_left)  # 输出:PySide6.QtCore.QPointF(72.000000, 72.000000)
print(bottom_right)  # 输出:PySide6.QtCore.QPointF(523.000000, 800.000000)

print("# getSelection()")
selection: QPdfSelection = document.getSelection(current_page, top_left, bottom_right)
print(selection.isValid(), selection.boundingRectangle())
# 实际输出:False PySide6.QtCore.QRectF(0.000000, 0.000000, 0.000000, 0.000000)

测试环境

我在多个不同环境下测试,结果完全一致:

  • Linux 5.10.0-19-amd64(Debian)+ Python 3.12.11 + Qt/PySide6 6.9.2
  • Linux Debian 12 6.1.0-22-amd64 + Python 3.11.2 + Qt/PySide6 6.9.2
  • Windows 10 10.0.19045 + Python 3.12.6 + Qt/PySide6 6.9.2

所有环境安装的Python依赖包版本统一为:

  • pyside6==6.9.2
  • pyside6-addons==6.9.2
  • pyside6-essentials==6.9.2
  • shiboken6==6.9.2

有没有朋友遇到过类似的问题?或者是不是我对getSelection()方法的参数逻辑理解有误?希望能得到大家的帮助,谢谢!

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 08:08:08