<p>.0我终于找到了不使用样式表的方法!
谢谢eyllanesc的回答,它给了我一个新的工作基础,我终于理解了Qt是如何处理大小调整的(我猜),我在一个叫做每次动画值改变的方法中使用<code>setFixedSize</code></p>
<p>要工作,这需要有一个重写的<code>sizeHint</code>方法,该方法返回宽度的动画值。
此外,这也适用于Autodesk Maya(不幸的是,eyllanesc提供的解决方案由于未知原因无法在Maya中工作)</p>
<p>我的解决方案是:</p>
<pre class="lang-py prettyprint-override"><code>from PySide2 import QtWidgets, QtCore, QtGui
class MyTE(QtWidgets.QPlainTextEdit):
def __init__(self):
super(MyTE, self).__init__()
self.setVerticalScrollBar(MyScrollBar(self))
self.setPlainText("mmmmmmmmmmmmmmmmmmmmmmmmmmmmm" * 50)
self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
def resizeEvent(self, event):
super(MyTE, self).resizeEvent(event)
class MyScrollBar(QtWidgets.QScrollBar):
def __init__(self, parent=None):
super(MyScrollBar, self).__init__(parent=parent)
self._animation = QtCore.QVariantAnimation(
startValue=10.0, endValue=25.0, duration=300
)
self._animation.valueChanged.connect(self.changeWidth)
self._width = 10
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 sizeHint(self):
"""This must be overrided and return the width processed by the animation
.. note:: In my final version I've replaced self.height() with 1 because it does not change
anything but self.height() was making my widget grow a bit each time.
"""
return QtCore.QSize(self._width, self.height())
def changeWidth(self, width):
self._width = width # This will allow us to return this value as the sizeHint width
self.setFixedWidth(width) # This will ensure to scale the widget properly.
if __name__ == "__main__":
app = QtWidgets.QApplication()
wid = MyTE()
wid.show()
app.exec_()
</code></pre>
<p>注意:QVariantAnimation的起始值和结束值必须是浮点,如果它们是int类型,则动画将不起作用(适用于Qt 5.6.1(Maya 2018),但不适用于Qt 5.12.5(Maya 2020)</p>
<p>PS:如果有人询问我的最后一个小部件(窗口10开始菜单滚动条),请私下问我</p>