Issue
Here is the code. My idea is when I click the button, the window will became transparent from the bottom to the top slowly, and then the window's transparency is 0 and lastly the window closes, but I don't know how to do this.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import (QWidget,QPushButton,QVBoxLayout,QApplication)
class Window(QWidget):
def __init__(self, parent = None):
QWidget.__init__(self, parent)
button = QPushButton(self.tr("Click me!"))
button.clicked.connect(self.fade)
layout = QVBoxLayout(self)
layout.addWidget(button)
def fade(self):
self.setWindowOpacity(0.2)
QTimer.singleShot(5000, self.unfade)#it does not work
self.close()
def unfade(self):
self.setWindowOpacity(1)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
Solution
The effect you want we can create it using the setMask()
method that only makes the widget part visible to the region, so we must vary the height of the region for that we will use the class QPropertyAnimation
, but for this we must create a property through pyqtProperty
. this task will be launched in the closeEvent()
method as shown below:
class FadeWidget(QWidget):
def __init__(self, parent = None):
QWidget.__init__(self, parent)
self._heightMask = self.height()
self.animation = QPropertyAnimation(self, b"heightPercentage")
self.animation.setDuration(1000)
self.animation.setStartValue(self.height())
self.animation.setEndValue(-1)
self.animation.finished.connect(self.close)
self.isStarted = False
@pyqtProperty(int)
def heightMask(self):
return self._heightMask
@heightMask.setter
def heightPercentage(self, value):
self._heightMask = value
rect = QRect(0, 0, self.width(), self.heightMask)
self.setMask(QRegion(rect))
def closeEvent(self, event):
if not self.isStarted:
self.animation.start()
self.isStarted = True
event.ignore()
else:
QWidget.closeEvent(self, event)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = FadeWidget()
window.show()
sys.exit(app.exec_())
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.