繁体   English   中英

如何从QImage / QLabel中删除裁剪的矩形?

[英]How to remove cropped rect from QImage/QLabel?

我做了子分类以包括鼠标单击功能。 在这里,可以通过mousePressEventmouseMoveEventmouseReleaseEvent选择一个矩形。 当我尝试选择另一个矩形时,不会删除我之前的矩形。 它仍与我先前不想显示的绘制矩形一起显示。 我想选择并仅显示一个矩形。 我的意思是当我再按一次以选择另一个矩形时,应该删除上一个矩形。

我在这里包含了名为mouse_crop子类

mouse_crop .h如下

#ifndef MOUSE_CROP_H
#define MOUSE_CROP_H

#include <QMainWindow>
#include <QObject>
#include <QWidget>
#include <QMouseEvent>
#include <QLabel>
#include <QRubberBand>

class mouse_crop : public QLabel
{
    Q_OBJECT

public:

mouse_crop(QWidget *parent=0);
QRubberBand *rubberBand;
QPoint origin, ending;

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

signals:
    void sendMousePosition(QPoint&);
    void sendMouseEnding(QPoint&);
};

#endif // MOUSE_CROP_H`

mouse_crop.cpp如下

#include "mouse_crop.h"

mouse_crop::mouse_crop(QWidget *parent):QLabel (parent)
{

}

void mouse_crop::mousePressEvent(QMouseEvent *ev)
{
    origin = ev->pos();
    rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
    if(ev->button()== Qt::LeftButton || ev->button()== Qt::RightButton)
    {
        rubberBand->show();
        emit sendMousePosition(origin);
    }
}

void mouse_crop::mouseMoveEvent(QMouseEvent *ev)
{
    rubberBand->setGeometry(QRect(origin, ev->pos()).normalized());
}

void mouse_crop::mouseReleaseEvent(QMouseEvent *ev)
{
    ending = ev->globalPos();
    if(ev->button()== Qt::LeftButton || ev->button()== Qt::RightButton)
    {
        emit sendMouseEnding(ending);
    }
}

谁能告诉我如何解决这个问题? 提前致谢。

造成该问题的原因是,每当您按下鼠标时,您都在创建一个新的QRubberBand,而您要做的就是仅创建一个QRubberBand,将其隐藏并在必要时显示它。

mouse_crop::mouse_crop(QWidget *parent)
    : QLabel(parent)
{
    rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
    rubberBand->hide();
}

void mouse_crop::mousePressEvent(QMouseEvent *ev)
{
    origin = ev->pos();
    rubberBand->setGeometry(QRect(origin, origin));

    if(ev->button()== Qt::LeftButton || ev->button()== Qt::RightButton)
    {
        rubberBand->show();
        emit sendMousePosition(origin);
    }
}

void mouse_crop::mouseMoveEvent(QMouseEvent *ev)
{
    rubberBand->setGeometry(QRect(origin, ev->pos()).normalized());
}

void mouse_crop::mouseReleaseEvent(QMouseEvent *ev)
{
    ending = ev->globalPos();
    if(ev->button()== Qt::LeftButton || ev->button()== Qt::RightButton)
    {
        emit sendMouseEnding(ending);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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