简体   繁体   中英

Changing the font in Enthought TraitsUI TextEditor

I would like to change the font in a TextEditor in TraitsUI view. How can I do this?

I read the (excellent) documentation, the API reference docs and asked Google for an answer, but could not find one.

Platform- and toolkit-independence is not a requirement for my application. I work on Windows and use the wx toolkit.

After digging into the source code and some experimenting, I came up with the following solution. To me, this seems to be too complicated (I have to subclass two classes!) to be the simplest or intended way to do this.

If there is a better solution, I would be glad to learn about it.

import wx
from traitsui.wx.text_editor import CustomEditor
from traitsui.editors.text_editor import ToolkitEditorFactory

class _MyTextEditor(CustomEditor):
    def init(self, parent):
        CustomEditor.init(self, parent)
        font = wx.Font(10, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)
        self.control.SetFont(font)

class MyTextEditor(ToolkitEditorFactory):
    klass = _MyTextEditor
    def _get_custom_editor_class(self):
        return _MyTextEditor
    def _get_simple_editor_class(self):
        return _MyTextEditor

if __name__ == "__main__":
    from traitsui.api import View, Item
    from traits.api import Str, HasTraits

    class MyTestcase(HasTraits):
        a_string = Str()
        traits_view = View(Item('a_string', editor=MyTextEditor()))

    w = MyTestcase()
    w.configure_traits()

I think Traits uses Qt. So to change the font size, use the style_sheet argument. See example below

Item('a_string', style_sheet='*{font-size:24px}')

If you want to apply multiple font options, separate with a semicolon like this:

Item('a_string', style_sheet='*{font-size:24px; font-style:italic}')

For all of Qt stylesheet options that you can apply, look at Qt Style Sheets Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM