PyQt5 QTextEdit垂直滚动条事件捕获:正确信号及报错解决
Hey there, let's work through this issue step by step! First, let's unpack that error you're seeing: AttributeError: 'builtin_function_or_method' object has no attribute 'valueChanged'. The root cause is simple—verticalScrollBar is a method of QTextEdit, not a direct attribute. You need to call it with parentheses to get the actual QScrollBar object, which exposes the valueChanged signal we need.
Let's walk through the corrected code and how to implement saving/restoring the scroll position properly:
1. Fix the Signal Connection & Slot Function
First, adjust how you access the vertical scrollbar, then update your slot to use the value the signal automatically passes:
# Initialize a variable to store the last scroll position (use a class attribute in proper apps instead of global) last_scroll_pos = 0 # Correct signal connection: call verticalScrollBar() as a method textEdit.verticalScrollBar().valueChanged.connect(setScrollBarPos) # Updated slot function: accepts the current scroll position directly from the signal def setScrollBarPos(pos): global last_scroll_pos last_scroll_pos = pos
No need to call textEdit.verticalScrollBar().value() inside the slot anymore—the valueChanged signal sends the current scroll position straight to your function.
2. Restore Scroll Position When Switching Text Edits
When you switch back to this text edit (or swap between multiple edits), use the saved position to reset the scrollbar:
# Restore the saved scroll position textEdit.verticalScrollBar().setValue(last_scroll_pos)
Best Practice: Use a Class for Clean Code
If you're building a proper PyQt application, avoid global variables by storing the scroll position as a class attribute. Here's a quick example of how that might look:
from PyQt5.QtWidgets import QMainWindow, QTextEdit, QVBoxLayout, QWidget, QPushButton class ScrollSaveWindow(QMainWindow): def __init__(self): super().__init__() # Store scroll position as a class attribute self.last_scroll_pos = 0 # Set up your text edit self.text_edit = QTextEdit() # Connect the corrected signal self.text_edit.verticalScrollBar().valueChanged.connect(self.save_scroll_pos) # Example button to test restoring position self.restore_btn = QPushButton("Restore Last Scroll Position") self.restore_btn.clicked.connect(self.restore_scroll_pos) # Layout setup layout = QVBoxLayout() layout.addWidget(self.text_edit) layout.addWidget(self.restore_btn) central_widget = QWidget() central_widget.setLayout(layout) self.setCentralWidget(central_widget) def save_scroll_pos(self, pos): self.last_scroll_pos = pos def restore_scroll_pos(self): self.text_edit.verticalScrollBar().setValue(self.last_scroll_pos)
That should fix the AttributeError and let you save/restore the vertical scroll position seamlessly when switching between text edits.
内容的提问来源于stack exchange,提问作者Johnas Cukier

