我有一个只包含QTextEdit的弹出窗口,里面有很多文字,很多行。我希望它滚动到show()上的QTextEdit中的某一行。所以我想要的线在顶部。
代码段:
editor = QtGui.QTextEdit()
# fill the editor with text
# set the scroll to nth line
editor.show()
我怎样才能做到这一点?
我设法让它显示底部的第n行:
cursor = QtGui.QTextCursor(editor.document().findBlockByLineNumber(n))
editor.moveCursor(QtGui.QTextCursor.End)
editor.setTextCursor(cursor)
例如,对于n = 25,我得到:
_______________________
.
.
.
.
25th line
_______________________
但我需要它在顶部......
答案 0 :(得分:4)
你几乎拥有它。诀窍是将当前光标移动到底部第一个,然后将光标重置到目标线。然后视图将自动滚动以使光标可见:
editor.moveCursor(QtGui.QTextCursor.End)
cursor = QtGui.QTextCursor(editor.document().findBlockByLineNumber(n))
editor.setTextCursor(cursor)
通过扩展,将光标定位在底部,将当前光标移动到开头:
editor.moveCursor(QtGui.QTextCursor.Start)
...
这是一个演示脚本:
from PyQt4 import QtCore, QtGui
class Window(QtGui.QWidget):
def __init__(self):
super(Window, self).__init__()
self.edit = QtGui.QTextEdit(self)
self.edit.setPlainText(
'\n'.join('%04d - blah blah blah' % i for i in range(200)))
self.button = QtGui.QPushButton('Go To Line', self)
self.button.clicked.connect(self.handleButton)
self.spin = QtGui.QSpinBox(self)
self.spin.setRange(0, 199)
self.spin.setValue(50)
self.check = QtGui.QCheckBox('Scroll Top')
self.check.setChecked(True)
layout = QtGui.QGridLayout(self)
layout.addWidget(self.edit, 0, 0, 1, 3)
layout.addWidget(self.button, 1, 0)
layout.addWidget(self.spin, 1, 1)
layout.addWidget(self.check, 1, 2)
QtCore.QTimer.singleShot(0, lambda: self.scrollToLine(50))
def scrollToLine(self, line=0):
if self.check.isChecked():
self.edit.moveCursor(QtGui.QTextCursor.End)
else:
self.edit.moveCursor(QtGui.QTextCursor.Start)
cursor = QtGui.QTextCursor(
self.edit.document().findBlockByLineNumber(line))
self.edit.setTextCursor(cursor)
def handleButton(self):
self.scrollToLine(self.spin.value())
self.edit.setFocus()
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(500, 100, 400, 300)
window.show()
sys.exit(app.exec_())