我想问一下我们是否可以使用 QPropertyAnimation 对 PyQt5 中的 QLabel 的字体大小进行动画处理。
我尝试添加 QPropertyAnimation(self.label , b"fontSize")
但它不起作用,我收到了警告
我希望您增加 QLabel 的文本,然后再次切换到正常大小
最佳答案
来自QPropertyAnimation description :
QPropertyAnimation interpolates over Qt properties. As property values are stored in QVariants, the class inherits QVariantAnimation, and supports animation of the same meta types as its super class.
A class declaring properties must be a QObject. To make it possible to animate a property, it must provide a setter (so that QPropertyAnimation can set the property's value).
所有继承自 QObject 的类(包括小部件)都支持 Qt 属性,事实上,它们中的大多数都有“内置”属性,但显然,并非所有属性都支持动画:它们必须基于数值。您可以动画化数字变化(例如:从 0 到 100),而不是文本(例如从“ABC”到“PYZ”)。
例如,所有 QWidget 都有 pos
属性,并且由于此类属性(即 QPoint)是基于数字的,因此您可以创建动画。您可以在 QVariantAnimation docs 中查看支持的动画变体类型列表。 。考虑到有关 QObject 子类的所有文档页面都包含 property 部分(例如,请参阅 QWidget properties),并且属性显然是从其父类(super class)继承的。
但是,字体大小没有属性,因此有两种可能性:
- 创建自定义属性(通过使用 PyQt 中的
pyqtProperty
装饰器); - 使用 QVariantAnimation,它不绑定(bind)任何属性;
根据具体情况,人们可能更喜欢其中一种方法,但对于这种特定情况,它不会改变太多; QVariantAnimation 当然更简单,Qt 属性方法更“合规”。
在这里您可以看到如何使用 pyqtProperty 装饰器创建属性。由于动画写入属性,因此必须有一个 setter。
class AnimationTest(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.startButton = QtWidgets.QPushButton('Start')
self.label = QtWidgets.QLabel('Hello!')
self.labelFont = self.font()
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.startButton)
layout.addWidget(self.label)
self.ani = QtCore.QPropertyAnimation(self, b'labelFontSize')
self.ani.setStartValue(10)
self.ani.setEndValue(80)
self.ani.setDuration(1500)
self.startButton.clicked.connect(self.ani.start)
@QtCore.pyqtProperty(int)
def labelFontSize(self):
return self.labelFont.pointSize()
@labelFontSize.setter
def labelFontSize(self, size):
self.labelFont.setPointSize(size)
self.label.setFont(self.labelFont)
import sys
app = QtWidgets.QApplication(sys.argv)
test = AnimationTest()
test.show()
sys.exit(app.exec_())
变体动画当然更短:
class AnimationTest(QtWidgets.QWidget):
def __init__(self):
# ...
self.ani = QtCore.QVariantAnimation()
self.ani.setStartValue(10)
self.ani.setEndValue(80)
self.ani.setDuration(1500)
self.ani.valueChanged.connect(self.updateLabelFont)
self.startButton.clicked.connect(self.ani.start)
def updateLabelFont(self, value):
self.labelFont.setPointSize(value)
self.label.setFont(self.labelFont)
请注意,字体大小动画通常会出现问题,因为大多数字体根据大小的不同,其字形和间距略有不同。在上面的例子中,我使用了一个相当长的动画,大概会显示这样的效果:虽然尺寸线性增加,但字体的变化通常不是很平滑。
关于python - PyQt5 中 QLabel 的 FontSize 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68130545/