how to embed images in PyQt5 QScrollBar elements?

87 views Asked by At

I want to insert a Qscrollbar in my GUI developed in PyQt5. Customizing works fine, but I am not completely happy with the outcome. For instance, the following code (largely inspired from the example developed at Qt Style Sheets reference) produces a horizontal Qscrollbar with custom white handle and left/right arrows):

import sys
from PyQt5.QtWidgets import QScrollBar, QDialog, QVBoxLayout, QApplication
from PyQt5.QtCore import Qt
                        

class MainWindow(QDialog):
    def __init__(self):
        super().__init__()
        self.createWidgets()

    def createWidgets(self):
        self.layout = QVBoxLayout(self)
        self.scrollbar = QScrollBar(Qt.Horizontal, self)

        for widget in [self.scrollbar]:
            widget.valueChanged.connect(self.test)
            self.layout.addWidget(widget)

    def test(self, event):
        print(self.sender().value())


stylesheet = """
QScrollBar:horizontal {
    border: 2px solid grey;
    background: #32CC99;
    height: 35px;
    margin: 0px 20px 0 20px;
}
QScrollBar::handle:horizontal {
    background: white;
    min-width: 20px;
}
QScrollBar::add-line:horizontal {
    border: 2px solid grey;
    background: #32CC99;
    width: 20px;
    subcontrol-position: right;
    subcontrol-origin: margin;
}

QScrollBar::sub-line:horizontal {
    border: 2px solid grey;
    background: #32CC99;
    width: 20px;
    subcontrol-position: left;
    subcontrol-origin: margin;
}

QScrollBar:left-arrow:horizontal, QScrollBar::right-arrow:horizontal {
    border: 2px solid grey;
    width: 6px;
    height: 6px;
    background: white;
}

QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {
    background: none;
}
"""

if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyleSheet(stylesheet)  
    GUI = MainWindow()
    GUI.resize(300, 200)
    GUI.show()
    sys.exit(app.exec_())

However, the arrows of the scrollbar are now replaced with ugly white squares, and the handle appears as a plain white rectangle. I would like to replace the handle with some image (png) icon, and replace the arrow squares with actual arrow images as well. I tried to modify the let-arrow and right-arrow options in a couple of ways like:

QScrollBar:left-arrow:horizontal, QScrollBar::right-arrow:horizontal {
    image: url(:/images/down_arrow.png)
}

But that does not seem to work. Trying with relative path, different options like background-image instead of image does not work either. Anyone ever succeeded in doing this?

Thanks a lot.

0

There are 0 answers