这是代码。我的想法是,当我单击按钮时,窗口会慢慢从底部到顶部透明,然后窗口的透明度为0,最后窗口关闭,但是我不知道该怎么做。
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_())
您想要的效果我们可以使用只能使小部件可见的setMask()
方法来创建它,因此我们必须更改该区域的高度QPropertyAnimation
,但是为此,我们必须通过pyqtProperty
创建属性。此任务将在closeEvent()
方法中启动,如下所示:
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_())
可以通过调整fade
函数的time.sleep()
值来调整淡出速度。
它不如真正的动画那么光滑,但它将很有用。
import sys
import time
from PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QVBoxLayout
class FadeWindow(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
button = QPushButton(self)
button.setText("Close")
button.resize(200, 200)
button.clicked.connect(self.fade)
layout = QVBoxLayout(self)
layout.addWidget(button)
self.resize(300, 300)
def fade(self):
for i in range(10):
i = i / 10
self.setWindowOpacity(1 - i)
time.sleep(0.05)
self.close()
def close(self):
sys.exit()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = FadeWindow()
window.show()
sys.exit(app.exec_())