Search code examples
qtqtstylesheets

QSlider different color for add-page (width should be constant)


I am currently developing a GUI using Qt6. I want to create a custom vertical slider using stylesheets. I want the bottom part of the slider, right below the handle, have a different color, but when I try to manipulate the "add-page" section of the slider's stylesheet, the width is not constant anymore and it looks like this:

enter image description here

I expect the width of the groove area of the slider to stay the same, on top and below the handle. Here's my code so far:

QSlider:vertical
{
  min-height: 100px;
  min-width: 20px;
  background: none;
}
QSlider::groove:vertical
{
  background: rgb(43, 43, 43); 
  border: 1px solid rgb(43, 43, 43); 
  border-radius: 2px;
  width: 4px;
  margin: 0px 17px;
}
QSlider::handle:vertical
{
  background: white;
  border: 1px solid white;
  border-radius: 3px;
  top: 14px;
  bottom: 14px;
  margin: -15px -7px;
  min-width: 30px;
  min-height: 30px;
}
QSlider::add-page:vertical
{
  background: white;
}

When I remove the add-page section from the stylesheet, the slider looks like this:

enter image description here

As you can see, the bottom part is not white anymore, but the width does look nice now.


Solution

  • Move the definition of your margin so it affects the groove and the add-page together (and the sub-page if you want). The gist of it, where I put the bottom part red to make the difference with the handle visible, is:

    QSlider::groove:vertical,
    QSlider::add-page:vertical
    {
      margin:0px 17px;
    }
    QSlider::add-page:vertical
    {
      background-color: red;
    }
    

    And the complete stylesheet based on the one in your question:

    QSlider:vertical
    {
      min-height: 100px;
      min-width: 20px;
      background: none;
    }
    QSlider::groove:vertical
    {
      background: rgb(43, 43, 43); 
      border: 1px solid rgb(43, 43, 43); 
      border-radius: 2px;
      width: 4px;
    }
    QSlider::handle:vertical
    {
      background: white;
      border: 1px solid white;
      border-radius: 3px;
      top: 14px;
      bottom: 14px;
      margin: -15px -7px;
      min-width: 30px;
      min-height: 30px;
    }
    QSlider::groove:vertical,
    QSlider::add-page:vertical
    {
      margin:0px 17px;
    }
    QSlider::add-page:vertical
    {
      background-color: red;
    }