跳转到内容
新建笔记

Qt 旋转木马切页:坐标、快照与中断规则

旋转木马式切页需要把“页面顺序”和“当前画面上的深度”分开处理:页面索引决定绕环的位置,动画进度决定整个环转过多少角度,深度则决定绘制次序、尺寸与透明度。CarouselEffect 是效果名称,并非 Qt 自带的一个类。

本文给出一个四页 Qt Widgets 原型。它在切换时抓取页面快照,用二维位置、缩放与遮挡表达环形深度,完成后恢复真正的 QStackedWidget 页面。快照阶段显示的是缩小的卡片概览,不提供交互,也不是真正的三维透视投影;页面中的视频或 OpenGL 内容需要另外处理。

对于 N 个页面,页 i 相对于开始页 c 的角度为:

θi(t)=2πN(i−c−dt),0≤t≤1\theta_i(t)=\frac{2\pi}{N}\left(i-c-dt\right),\qquad 0\le t\le1

其中 d = 1 表示下一页,d = -1 表示上一页。Qt 动画传来的 t 已经过缓动曲线变换。定义:

xi=xc+Rsin⁡θi,zi=1+cos⁡θi2,si=0.48+0.52zi.x_i=x_c+R\sin\theta_i,\quad z_i=\frac{1+\cos\theta_i}{2},\quad s_i=0.48+0.52z_i.

这里 z 是范围 [0, 1] 的视觉深度参数,不是有物理单位的真实相机坐标。前方 θ=0 时,页面居中且缩放为 1;背面 θ=π 时,页面居中且缩放为 0.48。绘制时先画较小的 z,再画较大的 z,避免后方页面覆盖前方页面。

四页、从页面 A 向下一页 B 切换A 的角度与位置B 的角度与位置
t = 00°,前方中央90°,右侧
t = 0.5−45°,左前方45°,右前方
t = 1−90°,左侧0°,前方中央

一次相邻切页应旋转 2π/N,四页时为 90°;原先按 π 旋转的描述只适合两页对置的特殊情况。将 x = cos(angle) × radius 与“角度 0 时页面位于正中”混用,也会导致起点不符。先画这三个时间点,比调节动画时长更容易发现坐标约定错误。

页面、快照层与动画各自负责什么

跳转到“页面、快照层与动画各自负责什么”
flowchart TD
Input[上一页或下一页] --> Capture[记录起始页并抓取所有页面]
Capture --> Overlay[快照层覆盖页面]
Overlay --> Tick[每帧计算位置、深度和尺寸]
Tick --> Sort[由远到近绘制]
Sort --> Tick
Tick --> Done[动画完成]
Done --> Select[选择目标真实页面]
Select --> Hide[隐藏快照层]

原型采用明确的中断规则:动画中重复点击不排队;调用 cancel() 留在原页面;窗口改尺寸时立即完成到目标页;外部直接切页或移除页面时取消当前快照。打开减少动态效果选项则立即切页。这样每种输入都有确定结果。

保存为 main.cpp。快照层和动画都由 Carousel 拥有;目标页使用 QPointer,防止目标被删除后继续访问。卡片按快照原有宽高比缩放,不把页面文字拉伸。绘图只请求 update(),不在每帧递归调用 repaint()。

main.cpp
#include <QApplication>
#include <QColor>
#include <QHBoxLayout>
#include <QLabel>
#include <QPainter>
#include <QPointer>
#include <QPushButton>
#include <QResizeEvent>
#include <QStackedWidget>
#include <QVariantAnimation>
#include <QVBoxLayout>
#include <algorithm>
#include <cmath>
#include <vector>
class CarouselOverlay : public QWidget {
public:
explicit CarouselOverlay(QWidget *parent) : QWidget(parent) {
setObjectName("carouselOverlay");
setAutoFillBackground(true);
QPalette colors = palette();
colors.setColor(QPalette::Window, QColor("#edf1f5"));
setPalette(colors);
hide();
}
std::vector<QPixmap> cards;
int startIndex = 0;
int direction = 1;
qreal progress = 0;
protected:
void paintEvent(QPaintEvent *) override {
if (cards.empty()) return;
constexpr qreal pi = 3.14159265358979323846;
const qreal step = 2 * pi / cards.size();
struct Card { int index; qreal x, depth; };
std::vector<Card> order;
for (int i = 0; i < static_cast<int>(cards.size()); ++i) {
const qreal angle = (i - startIndex - direction * progress) * step;
order.push_back({i, std::sin(angle), (1 + std::cos(angle)) / 2});
}
std::stable_sort(order.begin(), order.end(), [](const Card &a, const Card &b) {
return a.depth < b.depth;
});
QPainter painter(this);
painter.setRenderHint(QPainter::SmoothPixmapTransform);
const QSizeF front(width() * 0.48, height() * 0.70);
for (const auto &card : order) {
const qreal scale = 0.48 + 0.52 * card.depth;
const QSizeF size = QSizeF(cards[card.index].size()).scaled(
front, Qt::KeepAspectRatio) * scale;
const QPointF center(width() / 2.0 + width() * 0.26 * card.x,
height() / 2.0 - height() * 0.12 * (1 - card.depth));
const QRectF target(center.x() - size.width() / 2,
center.y() - size.height() / 2,
size.width(), size.height());
painter.setOpacity(0.55 + 0.45 * card.depth);
painter.drawPixmap(target, cards[card.index], cards[card.index].rect());
}
}
};
class Carousel : public QStackedWidget {
public:
explicit Carousel(QWidget *parent = nullptr) : QStackedWidget(parent) {
setObjectName("carousel");
overlay_ = new CarouselOverlay(this);
animation_ = new QVariantAnimation(this);
animation_->setObjectName("carouselAnimation");
animation_->setDuration(360);
animation_->setStartValue(0.0);
animation_->setEndValue(1.0);
animation_->setEasingCurve(QEasingCurve::InOutCubic);
connect(animation_, &QVariantAnimation::valueChanged, this, [this](const QVariant &v) {
overlay_->progress = v.toReal();
overlay_->update();
});
connect(animation_, &QVariantAnimation::finished, this, [this] { finish(); });
connect(this, &QStackedWidget::currentChanged, this, [this] {
if (busy_) cancel(); // An external navigation request wins.
});
connect(this, &QStackedWidget::widgetRemoved, this, [this] {
if (busy_) cancel();
});
}
void setReducedMotion(bool enabled) {
reducedMotion_ = enabled;
if (enabled && busy_) finish();
}
bool transition(int direction) {
if (busy_ || count() < 2 || (direction != -1 && direction != 1)) return false;
const int start = currentIndex();
const int target = (start + direction + count()) % count();
target_ = widget(target);
if (reducedMotion_) {
setCurrentIndex(target);
return true;
}
overlay_->cards.clear();
for (int i = 0; i < count(); ++i) {
widget(i)->resize(size());
overlay_->cards.push_back(widget(i)->grab());
}
overlay_->startIndex = start;
overlay_->direction = direction;
overlay_->progress = 0;
overlay_->setGeometry(rect());
overlay_->show();
overlay_->raise();
busy_ = true;
animation_->start();
return true;
}
void cancel() {
animation_->stop();
busy_ = false;
target_.clear();
overlay_->hide();
overlay_->cards.clear();
}
protected:
void resizeEvent(QResizeEvent *event) override {
if (busy_) finish(); // Finish before invalidating snapshot geometry.
QStackedWidget::resizeEvent(event);
overlay_->setGeometry(rect());
}
private:
void finish() {
animation_->stop();
const QPointer<QWidget> destination = target_;
cancel();
if (destination && indexOf(destination) >= 0) setCurrentWidget(destination);
}
CarouselOverlay *overlay_{};
QVariantAnimation *animation_{};
QPointer<QWidget> target_;
bool busy_ = false;
bool reducedMotion_ = false;
};
int main(int argc, char **argv) {
QApplication app(argc, argv);
QWidget window;
auto *layout = new QVBoxLayout(&window);
auto *carousel = new Carousel(&window);
const QString colors[] = {"#bfdcf2", "#c8e7d2", "#f7dec0", "#dacdf2"};
for (int i = 0; i < 4; ++i) {
auto *page = new QWidget;
page->setStyleSheet(QString("background: %1;").arg(colors[i]));
auto *pageLayout = new QVBoxLayout(page);
auto *label = new QLabel(QString("Page %1").arg(i + 1), page);
label->setAlignment(Qt::AlignCenter);
label->setStyleSheet("font-size: 28px; color: #213348;");
pageLayout->addWidget(label);
carousel->addWidget(page);
}
layout->addWidget(carousel);
auto *buttons = new QHBoxLayout;
auto *previous = new QPushButton("Previous", &window);
auto *next = new QPushButton("Next", &window);
buttons->addWidget(previous);
buttons->addWidget(next);
layout->addLayout(buttons);
QObject::connect(previous, &QPushButton::clicked, carousel, [carousel] { carousel->transition(-1); });
QObject::connect(next, &QPushButton::clicked, carousel, [carousel] { carousel->transition(1); });
window.resize(720, 430);
window.show();
return app.exec();
}

QWidget::grab() 返回用于演示的快照;QVariantAnimation 驱动数值变化;真实页面的切换仍由 QStackedWidget 完成。快照接口、数值动画、堆叠页面

配套 CMakeLists.txt:

CMakeLists.txt
cmake_minimum_required(VERSION 3.21)
project(carousel_demo LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
find_package(Qt6 6.5 REQUIRED COMPONENTS Widgets)
add_executable(carousel_example main.cpp)
target_link_libraries(carousel_example PRIVATE Qt6::Widgets)

先确认前进、后退和首尾循环都选择正确页面,再检查 0、0.5、1 三个进度点的绘制顺序。继续验证动画中点击、取消、缩放窗口、移除目标页和外部切页,确保快照层不会残留。高 DPI 显示器、真实触摸屏、视频和原生子窗口的截图行为需要在目标设备上验证。

若页面数量很多,不宜一次抓取所有大页面;可以只保留可见邻居的快照,并在内容变化时失效重建。若要求真正的三维相机与透视遮挡,应使用适合三维渲染的场景,而不是继续给二维缩放公式补零散修正。手势输入可接入 手势与鼠标切页,但导航状态仍由切页组件统一管理。