Vii
Vii

Reputation: 841

PyQT Reading a text file

I've been searching all over google and have found no solution, which is unbelievable! It should be simple. I'm trying to make my PyQT UI open a text file into a QTextBrowser or a QTextEdit.

But QTextEdit can't 'setSource' and QTextBrowser can not display anything but HTML, if I open the text file it doesn't have any of the paragraphing, it's all one line. This area will also display log files and I do NOT want my log files being output in html!

All I want to do is display the contents of a text file with plain text formatting. Why is this so stupidly hard??

Upvotes: 5

Views: 22452

Answers (2)

vittorio
vittorio

Reputation: 143

You can use this function

    def openFileDialog(self):
    filename = QFileDialog.getOpenFileName(self,'Open File')

    if filename[0]:
        f = open(filename[0],'r')

        with f:
            data = f.read()
            self.textedit.setText(data)

Upvotes: 1

Oleh Prypin
Oleh Prypin

Reputation: 34136

text_edit = QPlainTextEdit()
...
text=open('file.txt').read()
text_edit.setPlainText(text)

Doesn't seem hard to me.

Upvotes: 16

Related Questions