我试图获取存储在列表中的一系列文本选择的边界框。边界框是可以包含整个选择的最小矩形。列表中的每个项目都有一个起始点和结束点,以字符数为单位从起始点开始计算QTextEdit
窗口和字母标识符。QTextEdit.cursorRect(cursor)
应该这样做,但会产生无意义的盒子尺寸:
id: A -- PySide.QtCore.QRect(0, 0, 1, 10)
id: B -- PySide.QtCore.QRect(0, 0, 1, 10)
id: C -- PySide.QtCore.QRect(0, 0, 1, 10)
所有选择都从不同的点开始,因此 (0,0) 在视点坐标中不正确。此外,其中一些跨越多行,因此宽度和高度应该有所不同。问题可能是光标处于循环中并且我没有设置它setTextCursor
直到循环结束后。我这样做是因为我还将选择呈现为突出显示。我怎样才能得到cursorRect
正确工作或以其他方式为每个选择获得单独的边界框?这是代码:
import sys
from PySide.QtCore import *
from PySide.QtGui import *
db = ((5,8,'A'),(20,35,'B'),(45,60,'C')) # start, end, and identifier of highlights
class TextEditor(QTextEdit):
def __init__(self, parent=None):
super().__init__(parent)
text="This is example text that is several lines\nlong and also\nstrangely broken up and can be\nwrapped."
self.setText(text)
for n in range(0,len(db)):
row = db[n]
startChar = row[0]
endChar = row[1]
id = row[2]
cursor = self.textCursor()
cursor.setPosition(startChar)
cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor, endChar-startChar)
rect = self.cursorRect(cursor)
print("id: %s -- %s" % (id,str(rect)))
charfmt = cursor.charFormat()
charfmt.setBackground(QColor(Qt.yellow))
cursor.setCharFormat(charfmt)
cursor.clearSelection()
self.setTextCursor(cursor)
if __name__ == '__main__':
app = QApplication(sys.argv)
editor = TextEditor()
editor.show()
app.exec_()
sys.exit(app.exec_())
EDIT 1:
这是该程序的文本。我将使用大写字母来突出显示文本:
This IS example text THAT IS SEVERAL lines
loNG AND ALSO
STRangely broken up and can be
wrapped.
假设每个字符都是 10 像素 x 10 像素。 “IS ”从 5 个字符开始,并延伸 3 个字符(包括末尾的空格)。因此,“I”的左上角将位于 x=50,y=0 处。空间的右下角位于 x=80,y=10 处。如果边界矩形以坐标给出,则为 (50,0,80,10)。如果边界矩形以起始坐标和大小给出,则为 (50,0,30,10)。
第二行是一个亮点,一直延续到第三行。它最左边的字符是第 3 行开头的“S”,即 x=0 处。它最右边的字符是“ALSO”中的“O”,以 x=130 结尾。它的最上面一行是第二行,从 y=10 开始。它的最底下一行是第三行,结束于 y=30。因此,边界框的坐标为 (0,10,130,30),起点和大小为 (0,10,130,20)。