How to translate Python console program (including while true loop) to PyQt?
<p>I have a Python console program that I want to transfer to a GUI.
I thought of using PyQt 5, but I'm open to alternatives.</p>

<p>The simplified console code looks like this:</p>

<pre><code>while True:
   data = obtain_data_from_device(source)
   print(datatotext(data))
</code></pre>

<p>Now from what I understand, GUI code works different.
But how do I continuously update a text box in PyQt using the obtain_data_from_device function which might take any time from 0.5 to 30 seconds?</p>

<p>A while loop can't do it, as it screws up the GUI, a timer doesn't work, as the duration is variable.</p>

<p>I'd appreciate any hints.</p>

<p>You could try something like this:</p>

<pre><code>import sys
import random
import time
import string

from PyQt5 import QtWidgets, QtCore


def obtain_data_from_device(source):
    time.sleep(0.001)
    data = ''.join(random.choice(string.ascii_uppercase + string.digits)
                   for _ in range(len(source)))
    return data


class Main(QtWidgets.QMainWindow):

    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.init_ui()

    def init_ui(self):

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

        self.lcd = QtWidgets.QLineEdit(self)
        self.lcd.setText(
            obtain_data_from_device("whatever data you're capturing"))

        self.setCentralWidget(self.lcd)

        self.setGeometry(300, 300, 250, 100)
        self.setWindowTitle("Displaying capture data from device")

    def time(self):
        self.lcd.setText(
            obtain_data_from_device("whatever data you're capturing"))


def main():
    app = QtWidgets.QApplication(sys.argv)
    main = Main()
    main.show()

    sys.exit(app.exec_())

if __name__ == "__main__":
    main()
</code></pre>

<p>You will just need to replace the existing obtain_data_from_device by yours.</p>

python qt pyqt