Zach Starnes
Zach Starnes

Reputation: 3198

QWidget does not respond after a mouse press event.

I am trying to get a mouse press event to work with my widget I created but every time I click the widget, the window stops responding and I have to kill the program. Does anyone know how to fix this and also how to get the color to change?

Here is the .h and the .cpp files.

.cpp file:

#include "iconwidget.h"
#include <QPaintEvent>
#include <QPainter>
#include <QPainterPath>

iconWidget::iconWidget(QWidget *parent) :
    QWidget(parent)
{
    this->resize(ICON_WIDGET_WIDTH,ICON_WIDGET_HEIGHT);
    pressed = false;
}

void iconWidget::paintEvent(QPaintEvent *event)
{
    QRect areatopaint = event->rect();
    QPainter painter(this);
    QBrush brush(Qt::black);
    QPointF center = this->rect().center();
    QPainterPath icon;
    icon.addEllipse(center,20,20);
    painter.drawPath(icon);
    painter.fillPath(icon, brush);

    if (pressed) {
        brush.setColor(Qt::red);
    }
}

void iconWidget::mousePressEvent(QMouseEvent *event)
{
    pressed = true;
    update();
    iconWidget::mousePressEvent(event);
}

.h file:

#define ICONWIDGET_H

#include <QWidget>

#define ICON_WIDGET_WIDTH 45
#define ICON_WIDGET_HEIGHT 45

class iconWidget : public QWidget
{
    Q_OBJECT

public:
    explicit iconWidget(QWidget *parent = 0);
    void paintEvent(QPaintEvent *event);
    bool pressed;

protected:
    void mousePressEvent(QMouseEvent *event);
};

#endif // ICONWIDGET_H

Upvotes: 3

Views: 4253

Answers (1)

Daniel Hedberg
Daniel Hedberg

Reputation: 5817

You call mousePressEvent() in an endless recursion. You should change the line:

iconWidget::mousePressEvent(event);

in your mousePressEvent function to:

QWidget::mousePressEvent(event);

Upvotes: 9

Related Questions