Angel Pensive Asked:2020-12-30 15:30:01 +0800 CST2020-12-30 15:30:01 +0800 CST 2020-12-30 15:30:01 +0800 CST 点击按钮动画 772 我试图找到如何在单击并悬停在按钮上时设置按钮动画的示例。到目前为止没有成功。 请分享秘密手稿。 理想情况下,我想将qss动画与 c结合起来QPushButton。 python 1 个回答 Voted Best Answer S. Nick 2020-12-30T17:40:27+08:002020-12-30T17:40:27+08:00 作为一种选择: import sys from PyQt5.QtCore import QPropertyAnimation, QRect from PyQt5.QtWidgets import (QApplication, QPushButton, QWidget, QHBoxLayout, QSpacerItem, QSizePolicy) class ZoomButton(QPushButton): def __init__(self, *args, **kwargs): super(ZoomButton, self).__init__(*args, **kwargs) self._animation = QPropertyAnimation( self, b'geometry', self, duration=200) def updatePos(self): # Запишите свое собственное фиксированное значение геометрии self._geometry = self.geometry() self._rect = QRect( self._geometry.x() - 6, self._geometry.y() - 2, self._geometry.width() + 12, self._geometry.height() + 4 ) def showEvent(self, event): super(ZoomButton, self).showEvent(event) self.updatePos() def enterEvent(self, event): super(ZoomButton, self).enterEvent(event) self._animation.stop() # Остановить анимацию # Изменить начальное значение анимации self._animation.setStartValue(self._geometry) # Изменить конечное значение анимации self._animation.setEndValue(self._rect) self._animation.start() def leaveEvent(self, event): super(ZoomButton, self).leaveEvent(event) self._animation.stop() self._animation.setStartValue(self._rect) self._animation.setEndValue(self._geometry) self._animation.start() def mousePressEvent(self, event): self._animation.stop() self._animation.setStartValue(self._rect) self._animation.setEndValue(self._geometry) self._animation.start() super(ZoomButton, self).mousePressEvent(event) class TestWindow(QWidget): def __init__(self, *args, **kwargs): super(TestWindow, self).__init__(*args, **kwargs) # 1. Присоединяйтесь к макету layout = QHBoxLayout(self) layout.addSpacerItem(QSpacerItem( 40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)) self.button1 = ZoomButton('Кнопка', self) layout.addWidget(self.button1) layout.addSpacerItem(QSpacerItem( 40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)) def showEvent(self, event): super(TestWindow, self).showEvent(event) # Обновить расположение кнопки self.button1.updatePos() def resizeEvent(self, event): super(TestWindow, self).resizeEvent(event) # Обновить расположение кнопки self.button1.updatePos() if __name__ == '__main__': app = QApplication(sys.argv) app.setStyleSheet(""" QPushButton { border: none; font-weight: bold; font-size: 16px; border-radius: 18px; min-width: 180px; min-height: 40px; background-color: blue; /*white;*/ } QPushButton:hover { background-color: #64b5f6; } QPushButton:pressed { background-color: #bbdefb; } """) w = TestWindow() w.show() sys.exit(app.exec_())
作为一种选择: