使用Qt中的鼠标事件裁剪QImage

Cropping a QImage using Mouse Events in Qt

本文关键字:事件 裁剪 QImage 鼠标 Qt 使用      更新时间:2023-10-16

我需要裁剪QLabel上显示的QImage。我想用鼠标事件来完成,比如在图像上拖动一个矩形,然后在releaseevent上,图像应该裁剪到矩形的大小。我已经实现了这个代码:

void surf_detection::mousePressEvent(QMouseEvent *ev)
{
if(ui->label_2->underMouse()){
    cout <<"Entered Press"<<endl;
    origin = ev->pos();
    //if (!rubberBand)
        rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
        rubberBand->show();
}
}
void surf_detection::mouseMoveEvent(QMouseEvent *ev)
{
rubberBand->setGeometry(QRect(origin, ev->pos()).normalized());                                                                                                              
}
void surf_detection::mouseReleaseEvent(QMouseEvent *ev)
{
QPoint a = mapToGlobal(origin);
QPoint b = ev->globalPos();
a = ui->label_2->mapFromGlobal(a);
b = ui->label_2->mapFromGlobal(b);
rubberBand->hide();
QPixmap OriginalPix(*ui->label_2->pixmap());
double sx = ui->label_2->rect().width();
double sy = ui->label_2->rect().height();
sx = OriginalPix.width() / sx;
sy = OriginalPix.height() / sy;
a.x = int(a.x * sx);
b.x = int(b.x * sx);
a.y = int(a.y * sy);
b.y = int(b.y * sy);
QRect myRect(a,b);
QImage newImage;
newImage = OriginalPix.toImage();
QImage copyImage;
copyImage = copyImage.copy(myRect);
ui->label_2->setPixmap(QPixmap::fromImage(copyImage));
ui->label_2->repaint();
}

但这个代码在上给了我错误

a.x = int(a.x * sx);
b.x = int(b.x * sx);
a.y = int(a.y * sy);
b.y = int(b.y * sy);

错误:成员函数的使用无效(您忘记了"()"吗?)

a.x=int(a.x*sx);^

我该如何解决此问题?

通过监听编译器:

a.setX(int(a.x() * sx));