Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Slider with two handles && styles support


  • Qt Champions 2020

    Hi all.

    I need to create the new widget, as slider with two handles. I know that similar widget exists in libqxt and named as "SpanSlider", but my question is in another.

    I derive my widget from the QSlider and draw two handles in this way:

    MySlider::MySlider(QWidget *parent)
        : QSlider(Qt::Horizontal, parent)
    {
    }
     
    void MySlider::paintEvent(QPaintEvent *ev)
    {
        Q_UNUSED(ev);
        QPainter p(this);
     
        QStyleOptionSlider opt;
        initStyleOption(&opt);
     
        // First handle.
        opt.sliderPosition = 0;
        opt.subControls = QStyle::SC_SliderHandle;
        style()->drawComplexControl(QStyle::CC_Slider, &opt, &p, this);
        // Second handle.
        opt.sliderPosition = 50;
        opt.subControls = QStyle::SC_SliderHandle;
        style()->drawComplexControl(QStyle::CC_Slider, &opt, &p, this);
    }
    

    All looks fine.. BUT, when I setup stylesheet for MySlider (e.g. spacify the background color):

    app.setStyleSheet("MySlider { background-color: yellow; }");
    

    Then I see only second handle!!!

    What I doing wrong?


  • Qt Champions 2020

    Hmm, it work in this way:

    void MySlider::paintEvent(QPaintEvent *ev)
    {
        Q_UNUSED(ev);
        QPainter p(this);
     
        QStyleOptionSlider opt;
     
        // First handle.
        initStyleOption(&opt);
        opt.sliderPosition = 0;
        opt.subControls = QStyle::SC_SliderHandle;
        opt.rect = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this);
        style()->drawComplexControl(QStyle::CC_Slider, &opt, &p, this);
     
        // Second handle.
        initStyleOption(&opt);
        opt.sliderPosition = 50;
        opt.subControls = QStyle::SC_SliderHandle;
        opt.rect = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this);
        style()->drawComplexControl(QStyle::CC_Slider, &opt, &p, this);
    }
    


  • slider does not move



  • I just had the exact same problem (using QxtSpanSlider) and it seems that the reason is that every time drawComplexControl() is called, it re-draws a background if it has one. My problem was that that background was inherited from some parent style sheet so the only way to prevent the second call to drawComplexControl() from overriding the stuff that was drawn in the first call was to override the background to be 100% transparent:

    app.setStyleSheet(
      "QWidget{ background-color: yellow; }
       MySlider { background-color: rgba(255,255,255,0); }"
    );
    

Log in to reply