Search code examples
pyqt5

Stylesheet issue in treewidget in pyqt5?


Code below populate a treewidget. TO change the design of the rows in treewidget, we add CSS like codes to stylesheet of the treewidget like below:

        self.treeWidget = QTreeWidget()

        stylesheet = ("""QTreeView::item {padding: 2px; 
                      border-bottom: 1px solid black;
                      }
                      QTreeView::item:selected {
                        background-color: black;                      
                        }""")

        self.treeWidget.setStyleSheet(stylesheet)

I just discovered if we set Gray in here, nothing happens when a row is selected:

QTreeView::item:selected {
                        background-color: Gray;                      
                        }

But if we change the colour to Blue or any other colours, the style of the selected row becomes unusual! There will be dotted borders all over the cells where we select in that selected row!

Why this issue does not happen with Gray? How we can set other colours without facing problems? Please have a look at the selected Blue row. The cell has a dotted border! The Gray row is clean without dotted border

Blue

Gray

I would like to change the colour of the selected row without those dotted border.


Solution

  • To solve this issue, the method is to disable focus indication.

    outline: none; /* Remove focus outline for all items */
    

    One way is to modify the stylesheet in this way:

            self.treeWidget = QTreeWidget()
    
        stylesheet = ("""QTreeView::item {padding: 2px; 
                      border-bottom: 1px solid black;
                      outline: none; /* Remove focus outline for all items */
                      }
                      QTreeView::item:selected {
                        background-color: black;                      
                        }""")
    
        self.treeWidget.setStyleSheet(stylesheet)
    

    Annother way is:

    from PyQt5.QtCore import Qt     
    self.treeWidget.setFocusPolicy(Qt.NoFocus)  # Disable focus