paintEvent不会在Qt

时间:2019-11-21 06:26:35

标签: c++ qt paintevent

我尝试使用此示例在QVideoWidget上绘制矩形。

How to draw rectangle on custom video widget t in QT?

但是当我释放鼠标按钮时,它没有像预期的那样调用paintEvent方法。以下是我的代码。

videowidget.h

#ifndef VIDEOWIDGET_H
#define VIDEOWIDGET_H

#include <QVideoWidget>

class QRubberBand;

class VideoWidget:public QVideoWidget
{
public:
    VideoWidget(QWidget *parent = nullptr);

protected:
    void mouseMoveEvent(QMouseEvent *ev);
    void mousePressEvent(QMouseEvent *ev);
    void mouseReleaseEvent(QMouseEvent *ev);
    void paintEvent(QPaintEvent *ev);

private:
    QRubberBand *rubberBand;
    QPoint origin;
    QRect rect;
};

#endif // VIDEOWIDGET_H

videowidget.cpp

#include "videowidget.h"
#include <QDebug>
#include <QMouseEvent>
#include <QRubberBand>
#include <QStyleOptionRubberBand>
#include <QPainter>

VideoWidget::VideoWidget(QWidget *parent)
    : QVideoWidget(parent),rubberBand(nullptr){

}

void VideoWidget::mouseMoveEvent(QMouseEvent *event)
{
    qDebug()<<"Mouse move event occured";
    rubberBand->setGeometry(QRect(origin,event->pos()).normalized());
    QVideoWidget::mouseMoveEvent(event);
}

void VideoWidget::mousePressEvent(QMouseEvent *event)
{
    qDebug()<<"Mouse Press event occured";
    origin = event->pos();
    if (!rubberBand)
        rubberBand = new QRubberBand( QRubberBand::Rectangle, this->parentWidget());
    rubberBand->setGeometry(QRect(origin, QSize()));
    rubberBand->show();
    QVideoWidget::mousePressEvent(event);
}


void VideoWidget::mouseReleaseEvent(QMouseEvent *event)
{
    qDebug()<<"Mouse Release event occured";
    rect = rubberBand->geometry();
    update();
    QVideoWidget::mouseReleaseEvent(event);

}

void VideoWidget::paintEvent(QPaintEvent *ev)
{
    qDebug()<<"paint event occured";
    QVideoWidget::paintEvent(ev);
    QPainter painter(this);
    painter.save();
    painter.setBrush(Qt::red);
    if(!rect.isNull())
       painter.drawRect(rect);
    painter.restore();
}

和我的主窗口,其中将videowidget添加为子窗口小部件。为简单起见,省略了部分代码。

Home::Home(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Home)
{
    ui->setupUi(this);

    //initializing variables
    videoWidget =new VideoWidget(this);
    ui->gridLayout->addWidget(videoWidget);
    ............

}

在这个问题Why QWidget::paintEvent doesn't get called?中,我发现这与小部件的大小有关,但无法弄清楚。有人可以告诉原因吗?

0 个答案:

没有答案