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

PySide6中QTextEdit光标矩形的绝对像素位置获取问题

解决QTextEdit获取选中文本像素矩形的问题

你遇到的问题源于cursorRect()方法默认返回的是光标插入点的矩形,而非选中文本的整体包围区域。要获取选中"yz"的完整像素矩形,需通过selectionRects()方法获取所有选中区域的矩形集合,再合并成一个整体矩形。

修改后的代码如下:

from PySide6 import QtCore, QtWidgets, QtGui

class MyWidget(QtWidgets.QWidget):
    def __init__(self, parent):
        super().__init__(parent)

        self.text_edit = QtWidgets.QTextEdit(self)
        self.text_edit.setGeometry(10, 10, 100, 100)

        self.cursor = QtGui.QTextCursor(self.text_edit.document())
        self.cursor.insertText('abc yz abc')

        self.cursor = QtGui.QTextCursor(self.text_edit.document())
        self.cursor.setPosition(4)
        self.cursor.movePosition(QtGui.QTextCursor.MoveOperation.Right, QtGui.QTextCursor.MoveMode.KeepAnchor, 2)
        self.text_edit.setTextCursor(self.cursor)
        
        # 获取所有选中区域的矩形集合
        selection_rects = self.text_edit.selectionRects()
        if selection_rects:
            # 合并所有矩形为一个整体包围盒
            full_selection_rect = selection_rects[0]
            for rect in selection_rects[1:]:
                full_selection_rect = full_selection_rect.united(rect)
            print("选中区域局部矩形:", full_selection_rect)
            # 转换为全局屏幕坐标
            global_pos = self.text_edit.mapToGlobal(full_selection_rect.topLeft().toPoint())
            print("选中区域全局坐标:", global_pos)


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    dialog = QtWidgets.QDialog()
    main = MyWidget(dialog)
    dialog.setGeometry(10,10,200,200)
    dialog.show()
    # 确保UI渲染完成后再获取矩形,避免窗口刚显示时的渲染延迟问题
    app.processEvents()
    app.exec()

核心说明:

  • selectionRects()会返回QTextEdit中所有选中文本的矩形列表(若选中文本跨多行,会返回多个独立矩形)
  • 利用QRectF.united()方法将多个矩形合并为一个能覆盖全部选中区域的整体矩形
  • 调用app.processEvents()可确保窗口完全渲染后再获取坐标,避免因UI未绘制完成导致的位置偏差

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:50:27