2011-11-19 42 views
3

在下面的代碼中,我可以爲標準的「幾何」屬性設置動畫,但我收到一條錯誤消息,告訴我我試圖設置動畫的屬性不存在。我錯了什麼?如何在PyQt4中創建和動畫定製小部件屬性?

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

你好@thomashollier你滿意答案,如果是標記解決。 –

回答

2

opacity屬性需要在類的範圍定義:

class FadingImage(QtGui.QWidget): 
    ... 

    def getOpacity(self): 
     return self._opacity 

    def setOpacity(self, value): 
     self._opacity = value 

    opacity = pyqtProperty(int, getOpacity, setOpacity) 
相關問題