Reputation: 133
In the following code, I am able to animate the standard "geometry" property but I get an error message telling me that the property I am trying to animate does not exist. What am I getting wrong?
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import QObject, pyqtProperty
This is my custom widget:
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))
This widget draws a solid rectangle of varying opacity on top of an image:
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
This is where I define "opacity" as a property of this object:
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()
Running this method works as expected:
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()
Running this method complains that the opacity property doesn't exist:
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()
Upvotes: 3
Views: 2028
Reputation: 120698
The opacity
property needs to be defined in the scope of the class:
class FadingImage(QtGui.QWidget):
...
def getOpacity(self):
return self._opacity
def setOpacity(self, value):
self._opacity = value
opacity = pyqtProperty(int, getOpacity, setOpacity)
Upvotes: 2