PyQt5如何将QLabel更新为动画

2024-09-28 05:41:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用我的qlabel作为倒计时。基本上,当倒计时被称为“3,2,1开始”的标签变化,中间有1秒的间隔。在

但是,如果我这样做:

def nextSound(self):

    self.mainLabel.setText("3")

    sleep(1)

    self.mainLabel.setText("2")

    sleep(1)
    self.mainLabel.setText("1")

它只是简单地等待到结束,而不更新标签。所以我尝试使用QPropertyAnimation

^{pr2}$

但是收到了这个错误:

self.animate = QPropertyAnimation(self.mainLabel,"setText")
TypeError: arguments did not match any overloaded call:
  QPropertyAnimation(parent: QObject = None): too many arguments
  QPropertyAnimation(QObject, Union[QByteArray, bytes, bytearray], parent: QObject = None): argument 2 has unexpected type 'str'

有什么建议吗?谢谢


Tags: selfnone间隔defsleep标签argumentsparent
1条回答
网友
1楼 · 发布于 2024-09-28 05:41:23

QPropertyAnimation是基于对q-property所取值的插值,当想要使用setText时,我认为最接近的是q-property文本,但是文本不能被插值,因此解决方案是创建一个采用数值的q-property。在

from PyQt5 import QtCore, QtWidgets

class NumLabel(QtWidgets.QLabel):
    def number(self):
        try:
            return int(self.text())
        except:
            return 0
    def setNumber(self, number):
        self.setNum(number)
    number = QtCore.pyqtProperty(int, fget=number, fset=setNumber)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = NumLabel(alignment=QtCore.Qt.AlignCenter)
    w.resize(640, 480)
    animation = QtCore.QPropertyAnimation(w, b'number')
    animation.setStartValue(3)
    animation.setEndValue(0)
    animation.setDuration(1000*(abs(animation.endValue() - animation.startValue())))
    animation.start()
    w.show()
    sys.exit(app.exec_())

另一个最佳选择是使用QTimeLine

^{pr2}$

相关问题 更多 >

    热门问题