Search code examples
pythonqt4enthoughtqtstylesheetstraitsui

How can I use a Qt4 id or class selector in the style sheet with TraitsUI?


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)

Solution

  • 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