在下面的代码中,我能够为标准的“geometry”属性设置动画,但是我收到一条错误消息,告诉我我尝试动画的属性不存在。我错了什么?
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()
运行此方法会抱怨不透明属性不存在:
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()
答案 0 :(得分:2)
opacity
属性需要在类的范围内定义:
class FadingImage(QtGui.QWidget):
...
def getOpacity(self):
return self._opacity
def setOpacity(self, value):
self._opacity = value
opacity = pyqtProperty(int, getOpacity, setOpacity)