Qt开发记录15——QGraphicsView控件中图片处理(90度旋转、截图等)后居中显示

东郭腾
2023-12-01

场景

GraphicsView 定义如下

GraphicsView m_graph = new GraphicsView(ui->label_img);

m_graph->setGeometry(ui->label_img->rect());
m_graph->setSceneRect(m_graph->PixItem()->boundingRect());
m_graph->setAlignment(Qt::AlignCenter);
m_graph->show();

ui->label_img是QLabel控件

QLabel *label_img;

GraphicsView 实现类

GraphicsView::GraphicsView(QWidget *parent) :
    QGraphicsView(parent)
{
    this->setAttribute(Qt::WA_DeleteOnClose);
    this->setBackgroundBrush(QBrush(Qt::gray));
    // 矩形框项
    selector = new ShapeItem;
    // 表示Graphics View中的场景
    m_scene = new QGraphicsScene(this);
    // QPixmap类是一个幕下图像的表现,可以用作一个绘制设备
    m_item = new PixmapItem;
    this->setScene(m_scene);
    m_scene->addItem(m_item);
    this->setRenderHint(QPainter::Antialiasing);
    this->setMouseTracking(true);
}

GraphicsView::~GraphicsView()
{
    SafeDelete(m_item);
    SafeDelete(m_scene);
    SafeDelete(selector);
}

图片处理后居中显示

/**
 * @brief 顺时针旋转90度
 */
void Picture::ClockwiseRotate90()
{
    // 将图片置为已处理状态
    if (!inChange){
        inChange = true;
    }

    // 入栈克隆
    push_showImg_to_record();

    // opencv图片处理
    transpose(m_showImg, m_showImg);
    flip(m_showImg, m_showImg, 1);

	// 显示图片
    showImgToItem();

	// undo/redo
    QUndoCommand *command = new CommandImage(this, "顺时针旋转90度");
    m_undoStack->push(command);
}
/**
 * @brief Picture::showImgToItem 展示图片到控件
 */
void Picture::showImgToItem()
{
    QElapsedTimer mstimer;

    // 类型转换
    Mat dst;
    m_effect->toBlur(m_showImg, dst);
    QPixmap p_showImg = Mat2Pixmap(dst);
    dst.release();

    // 显示图片
    m_item->setPixmap(p_showImg);
    m_graph->setSceneRect(m_graph->PixItem()->boundingRect());
}

核心代码是

m_graph->setSceneRect(m_graph->PixItem()->boundingRect());

即必须在setPixmap后重新设置scene尺寸

 类似资料: