c++qtdrawrubberqrubberband

QRubberBand, how to draw on it


I'm trying to draw numbers on QRubberBand object. I have class widget with QRubberBand object rectangleRubberBand;

I can show this area etc, but I'm trying to draw on area not on the widget some numbers, for example width and height of this area. How can I do this? It's for measure purpose of charts.


Solution

  • It is not drawing on rubber band but it does what you need :

    void MyButton::mouseMoveEvent(QMouseEvent *event)
    {
        rubberBand->setGeometry(QRect(mypoint, event->pos()).normalized());//Area Bounding
        QToolTip::showText( event->globalPos(), QString("%1,%2")
                                                 .arg(rubberBand->size().width())
                                                 .arg(rubberBand->size().height()),this );
    }
    

    QToolTip is shown near the cursor. It dynamically changes and shows actual information about size of rubber band.

    Result (black area is a cursor) :

    enter image description here

    Harder solution: subclass QRubberBand and reimplement paintEvent. For example:

    Header :

    #ifndef RUBBERBAND_H
    #define RUBBERBAND_H
    
    #include <QRubberBand>
    #include <QPaintEvent>
    
    class RubberBand : public QRubberBand
    {
        Q_OBJECT
    public:
        explicit RubberBand(Shape s, QWidget * p = 0);
    
    
    signals:
    
    protected:
        void paintEvent(QPaintEvent *event);
    
    public slots:
    
    };
    
    #endif // RUBBERBAND_H
    

    cpp :

    #include "rubberband.h"
    #include <QPainter>
    RubberBand::RubberBand(QRubberBand::Shape s, QWidget *p) :
        QRubberBand(s,p)
    {
    }
    
    void RubberBand::paintEvent(QPaintEvent *event)
    {
        QRubberBand::paintEvent(event);
        QPainter p(this);
        p.setPen(QPen(Qt::black,2));
        if(size().width() >10 && size().height() >10)
        {
            p.drawText(20,20,QString("%1,%2").arg(size().width()).arg(size().height()));
        }
    }
    

    Result:

    enter image description here

    Choose the best approach for you.