【问题标题】:QRubberBand to crop image in QtQRubberBand 在 Qt 中裁剪图像
【发布时间】:2019-02-28 21:28:20
【问题描述】:

我希望能够使用QRubberBand来选择图像的一个区域,然后在裁剪后将新选择的区域保存在新的地方。

我找到了这个answer,但我需要知道mapFormGlobal(a)(b) 中的ab 是什么

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声明的地方或者正确的方式是什么

【问题讨论】:

  • 在您链接的答案中,ab 声明在您发布的两行上方
  • 但是当我运行代码时,我发现错误'a'没有在这个范围内声明 a = ui->imageLabel->mapFromGlobal(a);
  • 你是否也复制了QPoint a = mapToGlobal(myPoint); QPoint b = event->globalPos();这两行?
  • 确定我说的。我用所有代码编辑问题
  • 这没有意义。在此之前您是否收到其他错误,例如 QPoint undeclared?

标签: qt


【解决方案1】:

改写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();
}

只要您松开鼠标按钮,选择图像就会被裁剪并显示在标签中。

【讨论】:

  • QPixmap OriginalPix(*ui->imageLabel->pixmap());???正确的是:QPixmap OriginalPix(ui->imageLabel->pixmap());
猜你喜欢
  • 1970-01-01
  • 2011-10-24
  • 2015-02-02
  • 2017-05-22
  • 1970-01-01
  • 2011-09-12
  • 2014-11-30
  • 2011-01-01
  • 2011-01-01
相关资源
最近更新 更多