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

attach Qslider to a paint event



  • Hi all,

    I have a paint event implemented as follows:

    void MainWindow::paintEvent(QPaintEvent *e)
    {
        QPainter painter(this);
        QPen pointpen(Qt::black);
        pointpen.setWidth(5);
        QPen linepen(Qt::red);
        linepen.setWidth(2);
    
    
        QPoint p1;
        p1.setX(400);
        p1.setY(200);  //--> set QSlider value
    
        QPoint p2;
        p2.setX(500);
        p2.setY(100); //---> set QSlider value
    
        painter.setPen(linepen);
    
    
        painter.drawLine(p1,p2);
    
        painter.setPen(pointpen);
        painter.drawPoint(p1);
        painter.drawPoint(p2);
    }
    

    in this, I'm setting fixed y values to p1 and p2.
    How do I set dynamic values to y from a QSlider?

    Thanks in advance



  • @viniltc hi,
    you can move p1 and p2 to member variables section, then just connect your sliders valueChanged signal to a method where you modify p1 and p2



  • This post is deleted!


  • @LeLev

    Thanks for your feedback.

    Here I can now vary p1.y and p2.y with QSlider, but as I'm calling:

    painter.drawLine(p1,p2);
    

    I expect realtime change of height of line as I change the Slider. But this is stuck at one value and does not change

    void MainWindow::paintEvent(QPaintEvent *e)
    {
    
        p1.setX(400);
        p2.setX(500);
    
        QPainter painter(this);
        QPen pointpen(Qt::black);
        pointpen.setWidth(5);
        QPen linepen(Qt::red);
        linepen.setWidth(2);
        painter.setPen(linepen);
    
        painter.drawLine(p1,p2); //----> can't see realtime chnage as I change Slider
    
        painter.setPen(pointpen);
        painter.drawPoint(p1);
        painter.drawPoint(p2);
    }
    
    void MainWindow::changeP1value(int value)
    {
        p1.setY(value);
        p2.setY(value);
    }
    
    //connection in class constructor
    connect(ui->verticalSlider, &QSlider::valueChanged, this, &MainWindow::changeP1value);
    

    Can you spot an error?


  • Lifetime Qt Champion

    @viniltc said in attach Qslider to a paint event:
    Hi

    void MainWindow::changeP1value(int value)
    {
    p1.setY(value);
    p2.setY(value);
    update(); // make it repaint so it uses the new values
    }



  • @mrjj Thanks a lot, now it works fine! :)


  • Lifetime Qt Champion

    @viniltc
    Hi
    Well you did good job of following @LeLev advice so it was just a very minor detail
    but its good to note that when you change member values,
    you must call update() for it to repaint as it won't detect you change them.


Log in to reply