0

I'm editing a TraitsUI app that uses Qt4. How can I style specific elements in the view using a style_sheet?

I understand that a TraitsUI Item/Button/etc is translated into possibly several Qt Widgets. I just can't figure out how to reference specific elements. Is there a decent way to style the specific QLabel/QPushButtn/etc that is created? I'd be happy with a way to assign ids or a class to the widgets that are created and using a separate style sheet or a way to specify styling when creating the Item/Button/etc.

So for example, here's a simple view in a Controller with a style_sheet that colors both input elements yellow. I'd like to be able to style the two Items differently. How can I do that?

    def traits_view(self):
        style_sheet = '''
            QLineEdit { background: yellow }
            '''

        return QtView(
            Item('object.name'),
            Item('object.age'),
            style_sheet=style_sheet)
jmilloy
  • 7,875
  • 11
  • 53
  • 86

1 Answers1

1

The Item can take a style_sheet argument on its own, so you can create separate style sheets for each item, as seen here in an extension of your example:

from traits.api import HasStrictTraits, Int, String
from traitsui.api import Item
from traitsui.qt4.extra.qt_view import QtView


class MinimalWorkingExample(HasStrictTraits):
    name = String
    age = Int

    def traits_view(self):
        style_sheet_name = '''
            QLineEdit { background: yellow }
            '''
        style_sheet_age = '''
            QLineEdit { background: green }
            '''


        return QtView(
            Item('object.name', style_sheet=style_sheet_name),
            Item('object.age', style_sheet=style_sheet_age),
        )


if __name__ == '__main__':
    mwe = MinimalWorkingExample(name='Steven', age=32)
    mwe.configure_traits()

Which produces the UI below:

enter image description here

Steve Kern
  • 586
  • 3
  • 6
  • Thanks; will test out tomorrow. I'm also really curious if this is documented somewhere. – jmilloy May 26 '16 at 01:43
  • 1
    It seems as though it is not, and there is no API reference in the TraitsUI readthedocs, where I would hope to find it. Though this feature has been extant since TraitsUI 4.1.0. I would encourage you to open an issue on github to point out the absence or to make a P R to add it if you are up for it. Thinking about it more, it may be left out of the docs since this option is Qt-specific and the docs are generally toolkit agnostic. Anyway, it is a good topic of discussion in a github issue if you'd like to make one. – Steve Kern May 26 '16 at 14:00