QWidget 在鼠标按下事件后没有响应



我正在尝试让鼠标按下事件与我创建的小部件一起使用,但每次单击小部件时,窗口都会停止响应,我必须杀死该程序。有谁知道如何解决这个问题以及如何改变颜色?

这是 .h 和.cpp文件。

.cpp文件:

#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 文件:

#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

你在无休止的递归中调用mousePressEvent()。您应该更改该行:

iconWidget::mousePressEvent(event);

在您的mousePressEvent函数中:

QWidget::mousePressEvent(event);

相关内容

  • 没有找到相关文章

最新更新