I needed something similar a few years ago. You can find what I came up with here: https://svn.enthought.com/enthought/wiki/OutputStream
The OutputStream
class has a file-like interface to a string. In particular, you add to the string with its write
method. The default view of an OutputStream
is a multiline text field. It has a handler that uses the appropriate toolkit method to move the cursor to the end of the string whenever it is changed. Two different demos of its use, output_stream_demo.py
and output_stream_demo2.py
, are given in the wiki page.
You'll probably want to drop the enthought
namespace in the imports. That is, change
from enthought.traits.api import ...
from enthought.traits.ui.api import ...
from enthought.etsconfig.api import ETSConfig
to
from traits.api import ...
from traitsui.api import ...
from traits.etsconfig.api import ETSConfig
Update, to address a comment:
Apparently the "readonly" style of a TextEditor
in the Qt backend uses a QLabel
for the text field instead of a QTextEdit
, and a QLabel
doesn't provide the moveCursor
method. The following modification to the handler provides a way to force the text field to be read-only while still using style="custom"
.
def _get_editor(uiinfo, name):
ui = uiinfo.ui
if ui is None:
return None
for ed in ui._editors:
if ed.name == name:
return ed
return None
class _OutputStreamViewHandler(Handler):
def init(self, uiinfo):
if ETSConfig.toolkit == 'qt4':
ed = _get_editor(uiinfo, 'text')
if ed is not None:
# Make the text field read-only.
ed.control.setReadOnly(True)
return True
def object_text_changed(self, uiinfo):
ed = _get_editor(uiinfo, 'text')
if ed is None:
return
if ETSConfig.toolkit == 'wx':
# With wx, the control is a TextCtrl instance.
ed.control.SetInsertionPointEnd()
elif ETSConfig.toolkit == 'qt4':
# With qt4, the control is a PyQt4.QtGui.QTextEdit instance.
from PyQt4.QtGui import QTextCursor
ed.control.moveCursor(QTextCursor.End)