如何在Qt 5的paintEvent上使用mouseMoveEvent? [英] How to use mouseMoveEvent on paintEvent on Qt 5?

查看:57
本文介绍了如何在Qt 5的paintEvent上使用mouseMoveEvent?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Qt和c ++的新手,所以遇到了一些困难.我正在尝试创建一个小部件,该小部件可以获取mouseMoveEvent的位置,并在鼠标位置的像素图上绘制一个椭圆.在下面您可以看到代码:

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.

你能帮我吗?

此致

加百利.

推荐答案

根据

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.

...

访问功能:

QPoint pos()const void

移动(int x,int y)

无效移动(const QPoint&)

当我们看到不需要的数据时,可能的解决方案是创建一个变量,该变量存储通过 QMouseEvent 获取的位置的值,并通过函数 update() ,此外还是第一次应该没有椭圆,因此我们检查位置是否已通过Qcode 的 isNull()函数分配,如下所示:

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

这篇关于如何在Qt 5的paintEvent上使用mouseMoveEvent?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆