简体   繁体   English

PyQt4 Gui打印循环

[英]PyQt4 Gui that prints loop

I'm trying to learn PyQt4 and has made the following Gui for this purpose - it has no other use. 我正在尝试学习PyQt4,并为此目的制作了以下Gui-它没有其他用途。

The code works almost as expected - the only thing that doesn't is the 'else' clause. 该代码几乎可以按预期工作-唯一没有的是'else'子句。

import sys
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Form(QDialog):
    def __init__ (self, parent=None):
        super(Form, self).__init__(parent)
        self.startButton = QPushButton('Start')
        self.stopButton = QPushButton('Stop')
        self.browser = QTextBrowser()
        self.myLabel = QLabel()
        layout = QVBoxLayout()
        layout.addWidget(self.startButton)
        layout.addWidget(self.stopButton)
        layout.addWidget(self.browser)
        layout.addWidget(self.myLabel)
        self.setLayout(layout)
        self.startButton.setFocus()
        self.startButton.clicked.connect(self.guiLoop)
        self.stopButton.clicked.connect(self.guiLoop)
        self.setWindowTitle('Loop Gui')


    def guiLoop(self):
        state = False
        text = self.sender()
        self.myLabel.setText(text.text())
        time.sleep(1)
        if text.text() == 'Start':
            state = True
        else:
            state = False
        i = 0
        while state:
            time.sleep(.1)
            self.browser.append(str(i))
            QApplication.processEvents()
            i += 1
        else:
            self.browser.append('Stop loop')
            time.sleep(3)
            sys.exit()

app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

...I'd expect that the program would print 'Stop loop' in the browser widget before exiting, but it doesn't ...我希望程序可以在退出前在浏览器小部件中打印“停止循环”,但不会

       else:
            self.browser.append('Stop loop')
            time.sleep(3)
            sys.exit()

I now have 3 questions: 我现在有3个问题:

  1. Why doesn't it print 'Stop loop' 为什么不显示“停止循环”
  2. If you imagine that the loop was instead a data stream from a serial connection, how could I print only every 10th value. 如果您认为循环是串行连接中的数据流,那么我如何仅每10个值打印一次。 In the loop that would be 1, 11, 21 ... and so on 在循环中将是1,11,21 ...依此类推
  3. General comments on my code 对我的代码的一般评论

Thx in advance 提前Thx

Add the following line in your else part 在您的else部分中添加以下行

QApplication.processEvents()

like 喜欢

while state:
    time.sleep(.1)
    if i % 10 == 1:
        self.browser.append(str(i))
        QApplication.processEvents()
    i += 1
else:
    self.browser.append('Stop loop')
    QApplication.processEvents()
    time.sleep(3)
    sys.exit()

Output is like: 1 11 21 31 etc.. and Stop Loop 输出就像:1 11 21 31等。和Stop Loop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM