QWidget doesn't respond after mouse click event.

I am trying to get the mouse click event to work with my widget that I created, but every time I click on the widget, the window stops responding and I need to kill the program. Does anyone know how to fix this as well as how to change the color?

Here are the .h and .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

      

+3


source to share


1 answer


You are calling mousePressEvent()

in infinite recursion. You have to change the line:

iconWidget::mousePressEvent(event);

      



in your function mousePressEvent

:

QWidget::mousePressEvent(event);

      

+9


source







All Articles