user2739064
user2739064

Reputation: 53

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.

The code works almost as expected - the only thing that doesn't is the 'else' clause.

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:

  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. In the loop that would be 1, 11, 21 ... and so on
  3. General comments on my code

Thx in advance

Upvotes: 1

Views: 269

Answers (1)

Syed Habib M
Syed Habib M

Reputation: 1817

Add the following line in your else part

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

Upvotes: 1

Related Questions