这个问题以前曾被问过,但仅仅是关于光标的位置。
我已经实现了一种基于QTextEdit的自动加载的文本编辑器。问题是:当我应用新加载的文本时
self.my_editor.setPlainText(new_text)光标将跳转到0位置,这是非常不舒服的。
当然,我并不是唯一一个有这种感觉的人,所以人们已经在询问如何在应用新文本之后恢复光标,例如:https://www.qtcentre.org/threads/13933-Restoring-cursor-position-in-QTextEdit
但我找到的答案只涵盖了文本光标本身的位置。
例如,此代码将保存游标、设置新文本并还原游标:
c = self.my_editor.textCursor()
p = c.position()
self.my_editor.setPlainText(new_text)
c.setPosition(p)
self.my_editor.setTextCursor(c)但是现在,编辑器可以滚动到定位0,然后再向下滚动,以便能够在恢复的位置显示光标。因此,从视觉上看,编辑器会跳来跳去(这仍然比失去光标更好)
是否也有方法存储QTextEdit实例的可视区域?当然,如果文本内容真的发生了变化,那么尽量减少视觉跳跃几乎是微不足道的,但是如果文本在光标后面发生了变化,难道就不可能看到任何跳跃吗?
发布于 2021-05-29 14:52:06
假设内容总是几乎相同的,您可以存储滚动条的值,然后在更新文本之后设置它们:
c = self.my_editor.textCursor()
p = c.position()
hPos = self.my_editor.horizontalScrollBar().value()
vPos = self.my_editor.verticalScrollBar().value()
self.my_editor.setPlainText(new_text)
c.setPosition(p)
self.my_editor.horizontalScrollBar().setValue(hPos)
self.my_editor.verticalScrollBar().setValue(vPos)
self.my_editor.setTextCursor(c)滚动条和光标重置的顺序取决于您的需要:如果光标可能位于可见视图之外,您可能更愿意先设置游标,然后恢复滚动条。
最后,如果内容可能会发生更大的变化,则应该使用基于滚动条最大值的比率:
try:
hBar = self.my_editor.horizontalScrollBar()
hPos = hBar.value() / hBar.maximum()
except ZeroDivisionError:
hPos = 0
try:
vBar = self.my_editor.verticalScrollBar()
vPos = vBar.value() / vBar.maximum()
except ZeroDivisionError:
vPos = 0
self.my_editor.setPlainText(new_text)
c.setPosition(p)
self.my_editor.setTextCursor(c)
hBar.setValue(hPos * hBar.maximum())
vBar.setValue(vPos * vBar.maximum())注意:最大值必须动态使用,因为范围可能随着文本的变化而改变。
https://stackoverflow.com/questions/67751888
复制相似问题