我正在尝试在循环中为帧的背景设置动画,因此它从 color1 变为 color2 再到 color1 等。
这是我到目前为止正在工作的东西,但它占用了我认为不应该占用的 CPU 的 2-3%:
class MyWindow(QtWidgets.QDialog):
def __init__(self):
super(MyWindow, self).__init__()
self.ui = Ui_MyDialog()
self.ui.setupUi(self)
self._animation = QVariantAnimation(self.ui.frame)
self._animation.setDirection(QAbstractAnimation.Forward)
self._animation.setEndValue(QColor(55, 25, 99))
self._animation.setStartValue(QColor(120, 214, 159))
self._animation.setDuration(1000)
self._animation.valueChanged.connect(self._animate)
self.animate_timer = QTimer()
self.animate_timer.setInterval(1000)
self.animate_timer.timeout.connect(self.add_animation)
def add_animation(self):
if self._animation.direction() == QAbstractAnimation.Forward:
self._animation.setDirection(QAbstractAnimation.Backward)
else:
self._animation.setDirection(QAbstractAnimation.Forward)
self._animation.start()
def _animate(self, color):
qss = "QWidget#frame {background-color: " + color.name() + ";}"
self.ui.frame.setStyleSheet(qss)
我相信应该有一种更优雅的方式不会导致这种 CPU 使用率,但我无法弄清楚。问题是我有一个相当高端的 CPU,如果它在这个 CPU 上运行 2-3%,它会在我们将运行这个程序的一些较慢的 CPU 上导致更多。如果我不做动画,它是 0%。