QRubberBand在Qt中裁剪图像

时间:2016-06-02 10:15:20

标签: qt

我希望能够使用QRubberBand选择图像区域,然后在裁剪后将新选定区域保存到新位置。

我发现了这个answer,但我需要知道ab

mapFormGlobal(a)(b)的内容

void MainResizeWindow::mousePressEvent(QMouseEvent *event)
{
    if(ui->imageLabel->underMouse()){
        myPoint = event->pos();
        rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
        rubberBand->show();
    }
}

void MainResizeWindow::mouseMoveEvent(QMouseEvent *event)
{
    rubberBand->setGeometry(QRect(myPoint, event->pos()).normalized());
}

void MainResizeWindow::mouseReleaseEvent(QMouseEvent *event)
{
    QPixmap OriginalPix(*ui->imageLabel->pixmap());
    double sx = ui->imageLabel->rect().width();
    double sy = ui->imageLabel->rect().height();
    sx = OriginalPix.width() / sx;
    sy = OriginalPix.height() / sy;

    QPoint a = mapToGlobal(myPoint);
    QPoint b = event->globalPos();

    a = ui->imageLabel->mapFromGlobal(a);
    b = ui->imageLabel->mapFromGlobal(b);

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

 //  QPixmap OriginalPix(*ui->imageLabel->pixmap());

    QImage newImage;
    newImage = OriginalPix.toImage();


    QImage copyImage;
    copyImage = copyImage.copy(myRect);

    ui->imageLabel->setPixmap(QPixmap::fromImage(copyImage));
    ui->imageLabel->repaint();
}

我收到错误

error: 'a' was not declared in this scope
     a = ui->imageLabel->mapFromGlobal(a);
     ^

应该在mainresizewindow.h中声明它或者正确的方式

1 个答案:

答案 0 :(得分:0)

重写mouseReleaseEvent方法,如下所示:

void MainResizeWindow::mouseReleaseEvent(QMouseEvent *event)
{
    QPixmap OriginalPix(ui->imageLabel->pixmap());
    QImage newImage;
    newImage = OriginalPix.toImage();
    QImage copyImage;
    copyImage = newImage.copy(rubberBand->geometry());
    ui->imageLabel->setPixmap(QPixmap::fromImage(copyImage));
    ui->imageLabel->repaint();
}

一旦松开鼠标按钮,选择图像将被裁剪并在标签中显示给您。