【问题标题】:How to create a timer in pyqt如何在pyqt中创建一个定时器
【发布时间】:2017-05-10 16:48:07
【问题描述】:

我有一个问题可能很简单,但我没能解决它 我想使用QTimeEdit 在pyqt 中创建一个计时器,默认时间从00:00:00 开始,并且每秒增加一次。我尝试了以下代码,但仅添加一秒钟后它就停止了。

self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.time)
self.timer.start(1000)

def time(self):
    self.upTime.setTime(QtCore.QTime(00,00,00).addSecs())

【问题讨论】:

  • 显示你的整个代码。
  • 如果您一直使用QtCore.QTime(00,00,00).addSecs(),那么您将无法获得更大的价值。您只需创建一次QtCore.QTime(00,00,00) 并在time() 中增加它

标签: python pyqt pyqt4 pyqt5


【解决方案1】:

我无法测试它,但我认为你需要

self.curr_time = QtCore.QTime(00,00,00)

self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.time)
self.timer.start(1000)

def time(self):
    self.curr_time = self.curr_time.addSecs()
    self.upTime.setTime(self.curr_time))

您只需创建一次QtCore.QTime(00,00,00),然后在time() 中增加其值。

现在你总是使用QtCore.QTime(00,00,00) 并增加这个值。

【讨论】:

    【解决方案2】:

    您只需将QTimeEdit中的当前时间加一秒即可:

    def time(self):
        self.upTime.setTime(self.upTime.time().addSecs(1))
    

    并确保在正常运行时间开始时正确初始化QTimeEdit

    self.upTime.setTime(QtCore.QTime(0, 0, 0))
    self.upTime.setDisplayFormat('hh:mm:ss')
    

    【讨论】:

      【解决方案3】:

      {yout time}.addSecs(1) 不改变时间,而是返回改变的时间。你必须使用{yout time} = {yout time}.addSecs(1)

      import sys
      
      from PyQt5 import QtCore
      
      
      def timerEvent():
          global time
          time = time.addSecs(1)
          print(time.toString("hh:mm:ss"))
      
      
      app = QtCore.QCoreApplication(sys.argv)
      
      timer = QtCore.QTimer()
      time = QtCore.QTime(0, 0, 0)
      
      timer.timeout.connect(timerEvent)
      timer.start(1000)
      
      sys.exit(app.exec_())
      

      输出:

      00:00:01
      00:00:02
      00:00:03
      00:00:04
      00:00:05
      00:00:06
      00:00:07
      00:00:08
      00:00:09
      00:00:10
      00:00:11
      00:00:12
      
      #

      【讨论】:

        【解决方案4】:

        这里有一个解决方案:

        import sys
        
        from PySide import QtCore
        
        def calculo():
            global time
            time = time.addSecs(1)
            print(time.toString("hh:mm:ss"))
        
        app = QtCore.QCoreApplication(sys.argv)
        
        timer0 = QtCore.QTimer()
        time = QtCore.QTime(0, 0, 0)
        timer0.setInterval(1000)
        timer0.timeout.connect(calculo)
        timer0.start()
        
        sys.exit(app.exec_())
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-12-13
          • 1970-01-01
          • 2018-02-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-20
          • 2014-06-20
          相关资源
          最近更新 更多