1、打开图片,并显示在QLabel上
void MainWindow::on_pB_ts_clicked()
{
QString filePath= QFileDialog::getOpenFileName(this,u8"选择图像" , "",
u8"Images (*.png *.bmp *.jpg *.tif *.GIF )" );
if(filePath.isEmpty())
return;
QImage image(filePath);
QPixmap pixmap = QPixmap::fromImage(image);
QSize drawSize = ui->label_img->size();
QPixmap fitPix = pixmap.scaled(drawSize, Qt::KeepAspectRatio);
ui->label_img->setPixmap(fitPix);
}
2、实现鼠标双击QLabel全屏显示图像
使用事件过滤器实现
在 mainwindow.h中添加:
protected:
bool eventFilter(QObject *obj, QEvent *event) override;
在 mainwindow.cpp的构造函数
ui->label_img->installEventFilter(this); //为 Label 安装事件过滤器
实现 eventFilter:
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if (obj == ui->label_img && event->type() == QEvent::MouseButtonDblClick) {
toggleFullScreen(); // 双击全屏
return true; // 事件已处理
}
// 全屏窗口的 Label 也被双击时,退出全屏
if (obj == m_fullScreenLabel && event->type() == QEvent::MouseButtonDblClick) {
toggleFullScreen(); // 双击退出全屏
return true;
}
return QMainWindow::eventFilter(obj, event);
}
// 全屏切换核心函数
void MainWindow::toggleFullScreen()
{
if (!m_isFullScreen) {
// ===== 进入全屏 =====
// 检查是否有图像显示
if (ui->label_img->pixmap() == nullptr || ui->label_img->pixmap()->isNull())
return;
// 获取当前显示的图像
QPixmap currentPixmap = *(ui->label_img->pixmap());
// 获取屏幕尺寸
QDesktopWidget *desktop = QApplication::desktop();
QRect screenRect = desktop->screenGeometry();
// 创建全屏窗口(无边框、置顶)
m_fullScreenWindow = new QWidget(nullptr, Qt::Window | Qt::FramelessWindowHint);
m_fullScreenWindow->setStyleSheet("background-color: black;");
m_fullScreenWindow->setGeometry(screenRect);
// 创建全屏用的 QLabel
m_fullScreenLabel = new QLabel(m_fullScreenWindow);
m_fullScreenLabel->setAlignment(Qt::AlignCenter);
// 缩放图像适应屏幕(保持宽高比)
QSize scaledSize = currentPixmap.size().scaled(screenRect.size(), Qt::KeepAspectRatio);
m_fullScreenLabel->setPixmap(currentPixmap.scaled(scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation));
m_fullScreenLabel->setFixedSize(scaledSize);
// 布局:将 Label 居中放置
QVBoxLayout *layout = new QVBoxLayout(m_fullScreenWindow);
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(m_fullScreenLabel, 1, Qt::AlignCenter);
// 也为全屏 Label 安装事件过滤器,捕获双击退出
m_fullScreenLabel->installEventFilter(this);
// 显示全屏窗口
m_fullScreenWindow->showFullScreen();
m_isFullScreen = true;
} else {
// ===== 退出全屏 =====
// 关闭并删除全屏窗口
if (m_fullScreenWindow) {
m_fullScreenWindow->close();
delete m_fullScreenWindow;
m_fullScreenWindow = nullptr;
m_fullScreenLabel = nullptr;
}
m_isFullScreen = false;
}
}