简体   繁体   中英

How to use mouseMoveEvent on paintEvent on Qt 5?

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.

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 );
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM