Jan Bodnar
Jan Bodnar

Reputation: 11637

Removing focus border from QSlider in PyQt

I am looking for a solution to remove a terrible looking focus rectangle over a QSlider. In addition that it looks terrible, it covers the ticks and is not entirely drawn.
This is an ancient issue; I remember stumbling into it many years ago. The workarounds mentioned (e.g. Removing dotted border without setting NoFocus in Windows PyQt) do not work for a slider on my Linux system.

Setting outline to none or using the Qt.WA_MacShowFocusRect does not work on Linux.

slider.setStyleSheet('QSlider { outline:none; }')
slider.setAttribute(Qt.WA_MacShowFocusRect, 0)

The only thing that 'works' is setting the focus policy to Qt.NoFocus, which is not a real solution, since one might want to work with keyboard.

slider.setFocusPolicy(Qt.NoFocus)

I am on Linux and the issue is on all available themes. Source code:

#!/usr/bin/python


from PyQt5.QtWidgets import (QWidget, QSlider, QHBoxLayout,
                             QLabel, QApplication)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
import sys


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        hbox = QHBoxLayout()

        sld = QSlider(Qt.Horizontal, self)
        # sld.setFocusPolicy(Qt.NoFocus)
        # sld.setStyleSheet('QSlider { outline:none; padding: 0 2 0 2;}')
        # sld.setAttribute(Qt.WA_MacShowFocusRect, 0)
        sld.setTickPosition(QSlider.TicksAbove)
        sld.setRange(0, 100)
        sld.setPageStep(5)

        sld.valueChanged.connect(self.changeValue)

        self.label = QLabel("0", self)
        self.label.setMinimumWidth(80)

        hbox.addWidget(sld)
        hbox.addSpacing(15)
        hbox.addWidget(self.label)

        self.setLayout(hbox)

        self.setGeometry(300, 300, 350, 250)
        self.setWindowTitle('QSlider')
        self.show()

    def changeValue(self, value):

        self.label.setText(str(value))

def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

Screenshot:

enter image description here

Upvotes: 2

Views: 690

Answers (0)

Related Questions