在下面的代码中,我可以使用标准的“geometry”属性进行动画处理,但我收到一个错误消息,告诉我我试图动画处理的属性不存在。我做错了什么?
这是我的自定义小部件:
这是我定义“不透明度”作为该对象属性的地方:
运行此方法会报错,提示opacity属性不存在:
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import QObject, pyqtProperty
这是我的自定义小部件:
class FadingImage(QtGui.QWidget, QObject):
def __init__(self, parent = None):
super(QtGui.QWidget, self).__init__(parent)
self.initUI()
def initUI(self):
self.setMinimumSize(5,5)
self.setOpacity(50)
def paintEvent(self, ev):
image = QtGui.QImage("/Users/thomas/pic1.jpg")
qp = QtGui.QPainter()
qp.begin(self)
sourceRect = QtCore.QRect(0,0,image.width(),image.height())
destRect = QtCore.QRect(0,0,self.width(),self.height())
qp.drawImage(destRect, image, sourceRect)
qp.setPen(QtGui.QColor(255, 255, 255))
这个小部件在图像上绘制一个不透明度不同的实心矩形:
qp.setBrush(QtGui.QColor(0,0,0,self.getOpacity()))
qp.drawRect(0, 0, self.width(),self.height())
qp.end()
def getOpacity(self):
return self._opacity
def setOpacity(self, value):
self._opacity = value
这是我定义“不透明度”作为该对象属性的地方:
opacity = pyqtProperty( "int", self.getOpacity, self.setOpacity )
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.setGeometry(0,0,300,400)
self.w = FadingImage(self)
self.w.setGeometry(0,0,300,300)
b = QtGui.QPushButton("fade",self)
b.move(100,330)
b.clicked.connect(self.animateOpacity)
self.show()
运行这个方法会按预期工作:
def animateGeometry(self):
self.anim = QtCore.QPropertyAnimation(self.w, "geometry")
self.anim.setDuration(300)
self.anim.setStartValue(QtCore.QRect(0, 0, 300,300))
self.anim.setEndValue(QtCore.QRect(150, 0, 300,300))
self.anim.setEasingCurve(QtCore.QEasingCurve.InOutQuad)
self.anim.start()
运行此方法会报错,提示opacity属性不存在:
def animateOpacity(self):
self.anim = QtCore.QPropertyAnimation(self.w, "opacity")
self.anim.setDuration(300)
self.anim.setStartValue(1)
self.anim.setEndValue(255)
self.anim.setEasingCurve(QtCore.QEasingCurve.InOutQuad)
self.anim.start()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()