【问题标题】:QWidget does not respond after a mouse press event.QWidget 在鼠标按下事件后没有响应。
【发布时间】:2013-01-22 21:07:10
【问题描述】:

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

这是 .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

【问题讨论】:

    标签: c++ qt qt4 qwidget qt5


    【解决方案1】:

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

    iconWidget::mousePressEvent(event);
    

    在您的 mousePressEvent 函数中:

    QWidget::mousePressEvent(event);
    

    【讨论】:

    • 可以阻止窗口冻结,但小部件的颜色仍然不会改变。知道为什么吗?
    • 使用前需要设置画笔颜色。目前,这是您在退出paintEvent() 之前所做的最后一件事。您的更改将无效。
    猜你喜欢
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    相关资源
    最近更新 更多