qtpyqt4qstylesheet

Qt Change stylesheet on focus in/out event


Okay I'm feeling really stupid right now... I have a QTableWidget and when it has focus I want to change the stylesheet so that it's border "highlights". I can do this simply by subclassing the widget's focusInEvent however if I call setStyleSheet() it overrides all styling that I did before. In the name of cleanliness I'm trying to find the best way to ONLY change the border color without overriding my other styling.

As a note I'm trying to find the best way to do this for all properties. In this case I need border-color, but I imagine I'll want to change other things as well in the future.

Simple example in PyQt4:

class MyTableWidget(QtGui.QTableWidget):
    def __init__(self):
        super(MyTableWidget, self).__init__()
        self.style = "QTableView {background: red; selection-background-color: green; border: 1px solid gray}" # beautiful, I know...
        self.setStyleSheet(self.style)

    def focusInEvent(self, event):
        super(MyTableWidget, self).focusInEvent(event)
        self.setStyleSheet("border-color: blue")

    def focusOutEvent(self, event):
        super(MyTableWidget, self).focusOutEvent(event)
        self.setStyleSheet(self.style)

Solution

  • Just had to do something similar and found QTableView::focus give this a try :)

    class MyTableWidget(QtWidgets.QTableWidget):
        def __init__(self):
            super(MyTableWidget, self).__init__()
            self.style = """
                QTableView {
                    background: red;
                    selection-background-color: green;
                    border: 1px solid gray;}
                QTableView::focus {border-color: blue;}"""
            self.setStyleSheet(self.style)
    

    Thanks, Mark