c – 鼠标按下事件后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);
上一篇:c – 如何使用QWebEngineUrlRequestInterceptor


下一篇:c – Qt 5迁移 – 无法打开包含文件:’ui_mainwindow.h’