How to use mouseMoveEvent on paintEvent on Qt 5?

感情迁移 提交于 2021-02-13 17:44:19

问题


I'm new on Qt and c++, so I'm having some difficulties. I'm trying to create a widget that can get the mouseMoveEvent position and draw an ellipse on my pixmap on mouse position. Below you can see the code:

#include "myimage.h"
#include <QPainter>
#include <QPen>
#include <QColor>
#include <QMouseEvent>
#include <QDebug>

Myimage::Myimage(QWidget *parent) : QWidget(parent)
{
    setMouseTracking(true); // E.g. set in your constructor of your widget.
}



// Implement in your widget
void Myimage::mouseMoveEvent(QMouseEvent *event)
{
    qDebug() << event->pos();

}

void Myimage::paintEvent(QPaintEvent * event)
{
    event->accept();
    QPixmap pixmap2("/home/gabriel/Qt_interfaces/OpenCVTests/Webcam_PyQt5/Images/Court_top_View.jpg");

    QRect rectangle(0, 0, width()-1, height()-1);

    QPainter painter(this);
    painter.drawRect(rectangle);
    painter.drawPixmap(5, 5, width()-10, height()-10, pixmap2);


    painter.drawEllipse(pos(), 10 ,10 );
}

The mouse position is being printed on console, but no ellipse on image.

Could you help me?

Regards,

Gabriel.


回答1:


According to the doc:

pos : QPoint

This property holds the position of the widget within its parent widget.

If the widget is a window, the position is that of the widget on the desktop, including its frame.

...

Access functions:

QPoint pos() const void

move(int x, int y)

void move(const QPoint &)

As we see this data we do not want it, a possible solution is to create a variable that stores the value of the position obtaining through QMouseEvent and update the painting through the function update(), in addition the first time the Widget there should be no ellipse so we check that the position has been assigned through the function isNull() of QPoint, as I show below:

*.h

private:
    QPoint mPoint;

*.cpp

Myimage::Myimage(QWidget *parent)
    : QWidget(parent)
{
    setMouseTracking(true);
}

void Myimage::mouseMoveEvent(QMouseEvent *event)
{
    mPoint = event->pos();
    update();
}

void Myimage::paintEvent(QPaintEvent *)
{
    QPixmap pixmap2("/home/gabriel/Qt_interfaces/OpenCVTests/Webcam_PyQt5/Images/Court_top_View.jpg");

    QRect rectangle(0, 0, width()-1, height()-1);

    QPainter painter(this);
    painter.drawRect(rectangle);
    painter.drawPixmap(5, 5, width()-10, height()-10, pixmap2);

    if(!mPoint.isNull()){

        painter.drawEllipse(mPoint, 10 ,10 );
    }
}


来源:https://stackoverflow.com/questions/45248410/how-to-use-mousemoveevent-on-paintevent-on-qt-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!