1.声明
void wheelEvent(QWheelEvent *event) override;
2.实现(方便复制、测试起见用静态变量)
#include <mutex>
void MainWindow::wheelEvent(QWheelEvent *event)
{
static QLabel *label = new QLabel("Zoom Level: 100%", this);
static int zoomLevel = 100; // 初始缩放等级为100%
{ // init
static std::once_flag winner_flag;
std::call_once(winner_flag,[&,this](){
label->setAlignment(Qt::AlignCenter);
setCentralWidget(label);
resize(400, 300);
});
}
// 检查滚轮的方向
if (event->angleDelta().y() > 0) {
zoomLevel += 10; // 向上滚动放大
} else {
zoomLevel -= 10; // 向下滚动缩小
}
zoomLevel = qMax(10, zoomLevel); // 设置最小缩放等级为10%
label->setText(QString("Zoom Level: %1%").arg(zoomLevel));
}
结果: