pyqt - how to make a textarea to write messages to

2019-04-20 10:43发布

问题:

I'm fiarly new to pyqt - I'm currently using it to make a visual representation of a graph. I made a custom widget for this, which was fairly easy. But now I'm stuck when having to use built in functionality.

I want to add a 'view' to my application and be able to print text to it (kinda like what happens when you print to the console with print("blablabla") )

I tried to use the pyqt api to discover what/how but..

http://pyqt.sourceforge.net/Docs/PyQt4/qtgui.html

It contains 41 classes in the form of text + something else and to be fair I have NO clue to which one to use?

so if someone could point me out which one, and if you have time on how to use it for the purpose I want to, that would be much appreciated ^^

回答1:

The easiest way would be to use a QTextEdit, probably set it to read only through setReadOnly() and append your text with the append() or insertPlainText() method. I roughly used something like the following for a similar use case:

Basic Snippet:

...
logOutput = QTextEdit(parent)
logOutput.setReadOnly(True)
logOutput.setLineWrapMode(QTextEdit.NoWrap)

font = logOutput.font()
font.setFamily("Courier")
font.setPointSize(10)

theLayout.addWidget(logOutput)
...

To append text in an arbitrary color to the end of the text area and to automatically scroll the text area so that the new text is always visible, you can use something like

Automatic Scroll Snippet:

...
logOutput.moveCursor(QTextCursor.End)
logOutput.setCurrentFont(font)
logOutput.setTextColor(color)

logOutput.insertPlainText(text)

sb = logOutput.verticalScrollBar()
sb.setValue(sb.maximum())
...