【问题标题】:Easiest way to interrupt pyqt4?中断pyqt4的最简单方法?
【发布时间】:2016-10-04 12:12:15
【问题描述】:

我正在用 Python 构建一个简单的快速阅读器作为练习。基本上是一个Spritz 克隆。

运行 printword() 函数后,停止它的正确方法是什么?我应该把它放在一个线程中吗?使用线程还是 QThread?我有点迷茫。

#!/usr/bin/env python3

from time import sleep

import sys
from PyQt4 import QtGui, QtCore    

class Fastreader(QtGui.QWidget):

    def __init__(self):
        super(Fastreader, self).__init__()
        self.initUI()

    def initUI(self):

        self.le = QtGui.QLineEdit(self)
        self.le.setAlignment(QtCore.Qt.AlignCenter)
        self.le.move(20, 20)

        self.btn = QtGui.QPushButton('Play', self)
        self.btn.move(20, 50)
        self.btn.clicked.connect(self.printword)

        self.btn = QtGui.QPushButton('Stop', self)
        self.btn.move(120, 50)

        self.setGeometry(300, 300, 225, 80)
        self.setWindowTitle('fastreader')
        self.show()

    def printword(self):

        cb = QtGui.QApplication.clipboard()
        text = cb.text()

        words_per_minute = 200

        sleeptime = 60.0/words_per_minute

        for word in text.split(" "):
                self.le.setText(word)
                self.le.repaint()
                sleep(sleeptime)

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Fastreader()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

非常感谢!

【问题讨论】:

    标签: python multithreading pyqt pyqt4


    【解决方案1】:

    我会使用带有回调的计时器,以避免在 Qt 中使用线程或休眠。你可以试试这样的:

    def initUI(self):
        ...
        self.btn = QtGui.QPushButton('Play', self)
        self.btn.move(20, 50)
        self.btn.clicked.connect(self.play)
    
        self.btn = QtGui.QPushButton('Stop', self)
        self.btn.move(120, 50)
        self.btn.clicked.connect(self.stop)
        ...
    
    def play(self):
        cb = QtGui.QApplication.clipboard()
        text = cb.text()
        self.words = text.split(' ') 
        self.current_word = 0
    
        words_per_minute = 200
    
        # setInterval apparently takes msecs
        sleeptime = 60000.0 / words_per_minute
    
        self.timer = QtCore.QTimer(self)
        self.timer.setInterval(sleeptime)
        self.timer.timeout.connect(self.printword)
        self.timer.start()
    
    def stop(self):
        self.timer.stop()
    
    def printword(self):
        word = self.words[self.current_word]
        self.le.setText(word)
    
        self.current_word += 1
        if self.current_word == len(self.words):
            self.timer.stop()
    

    您甚至不必以这种方式调用 self.le.repaint()。

    【讨论】:

      【解决方案2】:

      这是我使用QThread的解决方案,请查看。而且我还使用了slot和signal机制在主线程和工作线程之间传递数据。

      嗯,最初我认为这样更改它会很容易。但事实证明,需要做一些改变。但只需将其视为使用QThread 的示例。

      from time import sleep
      
      import sys
      from PyQt4.QtCore import *
      from PyQt4.QtGui import *
      
      
      class Fastreader(QWidget):
      
          def __init__(self):
              super(Fastreader, self).__init__()
              self.initUI()
      
          def initUI(self):
              self.le = QLineEdit(self)
              self.le.setAlignment(Qt.AlignCenter)
              self.le.move(20, 20)
      
              self.btnplay = QPushButton('Play', self)
              self.btnplay.move(20, 50)
      
              self.btnstop = QPushButton('Stop', self)
              self.btnstop.move(120, 50)
      
              self.mthread = QThread() # New thread to run the Measurement Engine
              self.worker = PrintWord() # Measurement Engine Object
      
              # Transfer worker to the new thread. Calls to the worker will execute in mthread.
              self.worker.moveToThread(self.mthread)
              self.mthread.finished.connect(self.worker.deleteLater) # Cleanup after thread finished
      
              self.btnplay.clicked.connect(self.worker.printword)
              self.btnstop.clicked.connect(self.worker.kill, Qt.DirectConnection)
      
              self.worker.wordshow.connect(self.showword)
              self.mthread.start() 
      
              self.setGeometry(300, 300, 225, 80)
              self.setWindowTitle('fastreader')
              self.show()
      
          @pyqtSlot(str)
          def showword(self, word):
              self.le.setText(word)
      #        self.le.repaint()
      
          def closeEvent(self, event):
              """ Example how to capture all window close events and perform an action before closing. It reimplements the default closeEvent"""
              print("Close Event Received")
      
              # Cleanup mthread.
              self.mthread.quit()
              self.mthread.wait()
      
              # Accept the event, so that the window really closed. 
              # ignore() wold leave the window alive, for example if there is unsaved data. 
      #        event.accept()
      
      class PrintWord(QObject):
          wordshow   = pyqtSignal(str)              # started measurement loop
      
          def __init__(self):
              self.dokill = False # Flag to interrupt the loop if needed
              QObject.__init__(self) # Don't forget to call base class constructor
              self.printword()
      
          def printword(self):
      
              cb = QApplication.clipboard()
              text = cb.text()
      
              words_per_minute = 200
      
              sleeptime = 60.0/words_per_minute
              self.dokill = False
              for word in text.split(" "):
                      if self.dokill:
                          break
                      self.wordshow.emit(word)
                      sleep(sleeptime)
      #                print word
      
          @pyqtSlot()
          def kill(self):
              """ Set loop interruption flag to exit the measurment loop """
              self.dokill = True
      
      def main():
          app = QApplication(sys.argv)
          ex = Fastreader()
          sys.exit(app.exec_())
      
      if __name__ == '__main__':
          main()
      

      【讨论】:

      • 非常感谢您的宝贵时间!即使经过广泛的测试,我也无法让您的建议发挥作用。但我将来会更多地研究 QThread。
      • @MarkusPreislinger ,我可以知道错误是什么吗?我可以在我这边成功运行代码。我正在使用 Python 3.3 和 pyqt 4
      • 启动时没有任何反应 - 没有窗口出现。有时它突然出现,但是当我按下“分段错误(核心转储)”时。我尝试调试它with this,但一段时间后放弃了。 Python 3.4.3+、PyQt 4.8.6、4.2.0-36-generic
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      • 2017-10-19
      • 2011-02-22
      相关资源
      最近更新 更多