python - PyQt5如何将QLabel更新为动画

标签 python pyqt pyqt5 qlabel

我想使用我的 qlabel 作为倒计时。基本上,当倒计时被调用时,标签会更改为“3 2 1 begin”,其间有 1 秒间隙。

但是,如果我这样做:

def nextSound(self):

    self.mainLabel.setText("3")

    sleep(1)

    self.mainLabel.setText("2")

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

它只是等到结束而不更新标签。所以我尝试使用QPropertyAnimation:

  def nextSound(self):

        self.animate = QPropertyAnimation(self.mainLabel,"setText")

        self.animate.setDuration(1000)
        self.animate.startValue("3")
        self.animate.setEndValue("2")
        self.animate.start()

但收到此错误:

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'

有什么建议吗?谢谢

最佳答案

QPropertyAnimation 基于插入 q-property 所采用的值,当想要使用 setText 时,我认为最接近的是 q-property 文本,但文本无法插入,因此解决方案是创建一个采用数值的 q 属性。

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:

from PyQt5 import QtCore, QtWidgets

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)
    w.resize(640, 480)
    start = 3
    end = 0
    timeLine = QtCore.QTimeLine(abs(end - start)*1000, w)
    timeLine.setFrameRange(start, end)
    timeLine.frameChanged.connect(w.setNum)

    # set start value
    w.setNum(start)
    # start timer
    timeLine.start()

    w.show()
    sys.exit(app.exec_())

关于python - PyQt5如何将QLabel更新为动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53402046/

相关文章:

python - 如何在python中将带时区的日期时间转换为UTC时间

Python:数组与列表

python - PYSide/PyQt Qtreewidget字体颜色

python - 作为本地实例化类的方法的插槽永远不会被调用

python - 将 Acrobat Reader 嵌入 PyQt5 应用程序会导致空白页面 [PyQt5]

python - 如何在 Django 中创建用户和组迁移?

python - 在 PyPy 上矢量化高斯 CDF(或 erf/erfc/等)的最快方法(即没有 SciPy)

python - QThread 不使用事件更新 View

python - 是否需要removeWidget()

python - 使用 PyQt5 运行命令并获取 stdout 和 stderr