Important: Please read the Qt Code of Conduct -

How to get a Rubberband Line

  • I can get the rubberband rectangle to work, but not the rubberband line. Has anyone made the QRubberBand to work providing just a line and not a rectangle?
    In the past I have used an off screen buffer to draw into and bitblit it to the visible screen (window) and then draw the rubberband line on the screen. It worked and was fast--on both OS/2 and Windows NT. Another possibility is to place another widget with a transparent background over the widget in which I am doing my actual drawing and use it to show the rubberband line. Or, if the number of items to be drawn and the GPU strong enough, then I could draw on the widget and then draw the rubberband line and redraw all when the mouse moves. Anybody tried any of the above?

  • Lifetime Qt Champion


    Can you show the code you are using for the rubber band line ?

  • The code is nearly the same as the Qt documentation, but with Line specified.

    void MyCanvas::mousePressEvent(QMouseEvent *e)
    origin = e->pos();
    rubberRect = new QRubberBand(QRubberBand::Line, this);
    rubberRect->setGeometry(QRect(origin, QSize()));
    qDebug() << origin;

    void MyCanvas::mouseMoveEvent(QMouseEvent *e)
    qDebug() << e->pos();
    rubberRect->setGeometry(QRect(origin, e->pos()).normalized());

    void MyCanvas::mouseReleaseEvent(QMouseEvent *e)
    corner = e->pos();
    This code produces the same results as using Rectangle.

    I must point out the this will only solve part of my problem. What I also want to do, and have done in the past, is to move a sprite on the hidden mouse pointer. When the sprite nears a rectilinear object it will orientate itself perpendicular to the object and a dot will appear on the line representing the correlation point.


  • I resolved this problem by using a Pixmap to double-buffer. Then I can draw a rubber line or rectangle or move a sprite using the Pixmap to restore the original image after each move, thus no need to try to use QRubberband and I am not limited, but it is a little more programming.

Log in to reply