WyomingUndercover
WyomingUndercover

Reputation: 61

Qt rubberband not being drawn

I am attempting to implement a rubberband. Here is my code.

void TOTMain::mousePressEvent(QMouseEvent * event)
{
    QPoint origin = event->pos();
    _selectionSquare = new QRubberBand(QRubberBand::Rectangle, this);
    _selectionSquare->setGeometry(QRect(origin, QSize()));
    _selectionSquare->raise();
    _selectionSquare->show();
}

void TOTMain::mouseMoveEvent(QMouseEvent *event)
{
    QPoint origin = event->pos();
    _selectionSquare->setGeometry(QRect(origin, event->pos()).normalized());
}

void TOTMain::mouseReleaseEvent(QMouseEvent *event)
{
    _selectionSquare->hide();
    // determine selection, for example using QRect::intersects()
    // and QRect::contains().
}

The issue is that the band is not being drawn. I confirm it is being constructed and persists through the dragging, but no rendering.

Any ideas appreciated.

Upvotes: 0

Views: 758

Answers (1)

G.M.
G.M.

Reputation: 12899

Take a look at your mouseMoveEvent implementation...

void TOTMain::mouseMoveEvent(QMouseEvent *event)
{
    QPoint origin = event->pos();
    _selectionSquare->setGeometry(QRect(origin, event->pos()).normalized());
}

You're setting the geometry of the rubber band to QRect(origin, event->pos()), but you've previously set origin = event->pos() so the top-left and bottom-right corners of the rectangle are the same.

Make origin a member variable variable of your class (untested)...

class TOTMain: public QWidget {
public:
protected:
    virtual void mousePressEvent (QMouseEvent *event) override
    {
        _origin = event->pos();
        _selectionSquare = new QRubberBand(QRubberBand::Rectangle, this);
        _selectionSquare->setGeometry(QRect(_origin, QSize()));
        _selectionSquare->raise();
        _selectionSquare->setStyleSheet("{ background-color : red; }");
        _selectionSquare->show();
    }
    virtual void mouseMoveEvent (QMouseEvent *event) override
    {
        _selectionSquare->setGeometry(QRect(_origin, event->pos()).normalized());
    }
    virtual void mouseReleaseEvent (QMouseEvent *event) override
    {
        _selectionSquare->hide();
        // determine selection, for example using QRect::intersects()
        // and QRect::contains().
    }
private:
    QPoint       _origin;
    QRubberBand *_selectionSquare = nullptr;
};

Upvotes: 4

Related Questions