[英]How to use mouseMoveEvent on paintEvent on Qt 5?
I'm new on Qt and c++, so I'm having some difficulties.我是 Qt 和 C++ 的新手,所以我遇到了一些困难。 I'm trying to create a widget that can get the mouseMoveEvent position and draw an ellipse on my pixmap on mouse position.
我正在尝试创建一个可以获取 mouseMoveEvent 位置并在鼠标位置的像素图上绘制椭圆的小部件。 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.加布里埃尔。
pos : QPoint
位置 : 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
QPoint pos() const void
move(int x, int y)
移动(int x,int y)
void move(const QPoint &)
无效移动(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:由于我们看到这个数据我们不想要它,一个可能的解决方案是创建一个变量来存储通过
QMouseEvent
获取的位置的值,并通过函数update()
更新绘画,另外第一次应该有的 Widget没有椭圆,所以我们检查位置是否已通过QPoint
的函数isNull()
分配,如下所示:
*.h *。H
private:
QPoint mPoint;
*.cpp *.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 );
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.