Qt_图像放大缩小拖动 图片缩小放大平移

例程为qt5图片放大缩小平移,可直接运行,采用传递给子线程显示的方式

下载:

关键代码:

void ImageShow::contextMenuEvent(QContextMenuEvent *event)
{
    QPoint pos = event->pos();
    pos = this->mapToGlobal(pos);
    QMenu *menu = new QMenu(this);
    QAction *zoomInAction = new QAction(tr("Zoom In"));
    QObject::connect(zoomInAction, &QAction::triggered, this, &ImageShow::onZoomInImage);
    menu->addAction(zoomInAction);
    QAction *zoomOutAction = new QAction(tr("Zoom Out"));
    QObject::connect(zoomOutAction, &QAction::triggered, this, &ImageShow::onZoomOutImage);
    menu->addAction(zoomOutAction);
    QAction *presetAction = new QAction(tr("Preset"));
    QObject::connect(presetAction, &QAction::triggered, this, &ImageShow::onPresetImage);
    menu->addAction(presetAction);
    menu->exec(pos);
}
void ImageShow::paintEvent(QPaintEvent *event)
{    
    QStyleOption opt;
    opt.init(this);
    QPainter painter(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &painter, this);
    if (m_Image.isNull())
        return QWidget::paintEvent(event);    
    int width = qMin(m_Image.width(), this->width());
    int height = width * 1.0 / (m_Image.width() * 1.0 / m_Image.height());
    height = qMin(height, this->height());
    width = height * 1.0 * (m_Image.width() * 1.0 / m_Image.height());    
    painter.translate(this->width() / 2 + m_XPtInterval, this->height() / 2 + m_YPtInterval);    
    painter.scale(m_ZoomValue, m_ZoomValue);    
    QRect picRect(-width / 2, -height / 2, width, height);
    painter.drawImage(picRect, m_Image);
}

你可能感兴趣的:(qt_ui)