<p>要使宽度更改更平滑,可以使用<code>QVariantAnimation</code>:</p>
<pre class="lang-py prettyprint-override"><code>from PySide2 import QtWidgets, QtCore
class MyTE(QtWidgets.QPlainTextEdit):
def __init__(self):
super(MyTE, self).__init__()
self.setVerticalScrollBar(MyScrollBar(self))
self.setPlainText("mmmmmmmmmmmmmmmmmmmmmmmmmmmmm" * 50)
class MyScrollBar(QtWidgets.QScrollBar):
def __init__(self, parent=None):
super(MyScrollBar, self).__init__(parent=parent)
self._animation = QtCore.QVariantAnimation(
startValue=10, endValue=25, duration=500
)
self._animation.valueChanged.connect(self.change_width)
def enterEvent(self, event):
super(MyScrollBar, self).enterEvent(event)
self._animation.setDirection(QtCore.QAbstractAnimation.Forward)
self._animation.start()
def leaveEvent(self, event):
super(MyScrollBar, self).leaveEvent(event)
self._animation.setDirection(QtCore.QAbstractAnimation.Backward)
self._animation.start()
def change_width(self, width):
self.setStyleSheet("""QScrollBar:vertical{ width: %dpx;}""" % (width,))
if __name__ == "__main__":
app = QtWidgets.QApplication()
wid = MyTE()
wid.show()
app.exec_()
</code></pre>