PyQt5 - Display lines from script

140 Views Asked by At

I'm new in pyqt5 and I'm working on a gui that runs tasks from a txt file (each line is a task) and I have 8 QTextBrowser's ,i want to display each line into a QTextBrowser (for example the first line will be shown in the first QTextBrowser, the second line in the second QTextBrowser ..., but the ninth line will be displayed in the first QTextBrowser , the tenth line in the second QTextBrowser ...) and keep looping thru my eight QTextBrowser's

I tried something but it didn't work :

def execute_all(self) :
    file = open("taches.txt")
    lines = file.readlines()
    t1 = QTextBrowser()
    t2 = QTextBrowser()
    t3 = QTextBrowser()
    t4 = QTextBrowser()
    t5 = QTextBrowser()
    t6 = QTextBrowser()
    t7 = QTextBrowser()
    t8 = QTextBrowser()
    for line in lines :
        for i in t1,t2,t3,t4,t5,t6,t7,t8 :
            widget.addWidget(i)
            widget.setCurrentIndex(widget.currentIndex()+1)
            self.i.setText(line)

the gui i'm talking about !

Thanks for your support!

1

There are 1 best solutions below

7
musicamante On

Use itertools.cycle(). You have to first create all the widgets, and then cycle through them while iterating the lines.

You cannot also use setText(), as it overwrites any existing content. Instead, use append().

Also note that QTextBrowser is intended for navigation purposes, if you only need a read only QTextEdit, just call setReadOnly(True) or add the property in the constructor.

def execute_all(self):
    editors = []
    for i in range(8):
        editor = QTextEdit(readOnly=True)
        editors.append(editor)
        widget.addWidget(editor)

    with open("taches.txt") as file:
        lines = file.readlines()

    it = itertools.cycle(editors)
    for line in lines:
        editor = next(it)
        editor.append(line)

Note that you shall not use global references like you did with widget, nor attempt to change the current index like that; if you're following a YouTube tutorial named "Code First from Hala", then be aware that it's known to provide a lot of terrible suggestions and bad practices, and I strongly suggest you to avoid it completely.