当然,请参考下面的示例代码:
#include <QtWidgets>
class CustomStackedWidget : public QStackedWidget
{
public:
CustomStackedWidget(QWidget* parent = nullptr) : QStackedWidget(parent)
{
setStyleSheet("background-color: white;"); // 设置背景颜色为白色,可根据需要进行调整
currentPageIndex = 0;
startPos = QPoint();
offset = 0;
}
protected:
void mousePressEvent(QMouseEvent* event) override
{
startPos = event->pos();
}
void mouseMoveEvent(QMouseEvent* event) override
{
if (event->buttons() & Qt::LeftButton)
{
int deltaX = event->x() - startPos.x();
offset = deltaX;
int nextPageIndex = currentPageIndex + (deltaX > 0 ? -1 : 1);
if (nextPageIndex >= 0 && nextPageIndex < count())
{
QWidget* currentPage = widget(currentPageIndex);
QWidget* nextPage = widget(nextPageIndex);
nextPage->move(deltaX, 0);
currentPage->move(deltaX - width(), 0);
}
}
}
void mouseReleaseEvent(QMouseEvent*) override
{
int threshold = width() / 3; // 移动超过宽度的1/3则切换页面
if (qAbs(offset) >= threshold)
{
int nextPageIndex = currentPageIndex + (offset > 0 ? -1 : 1);
animateToPage(nextPageIndex);
}
else
{
animateToPage(currentPageIndex); // 恢复原始位置
}
startPos = QPoint();
offset = 0;
}
private:
void animateToPage(int nextPageIndex)
{
if (nextPageIndex < 0 || nextPageIndex >= count())
return;
QWidget* currentPage = widget(currentPageIndex);
QWidget* nextPage = widget(nextPageIndex);
QPropertyAnimation* animation = new QPropertyAnimation(this, "geometry");
animation->setDuration(300); // 动画持续时间,可根据需要进行调整
animation->setEasingCurve(QEasingCurve::OutQuad); // 缓动曲线,可根据需要进行调整
animation->setStartValue(geometry());
QRect targetRect = geometry();
targetRect.moveLeft(-width()); // 下一页的位置在左侧(当前页的前面)
animation->setEndValue(targetRect);
connect(animation, &QPropertyAnimation::valueChanged, this, [this](const QVariant& value) {
int currentValue = value.toInt();
updatePosition(currentValue);
});
connect(animation, &QPropertyAnimation::finished, this, [this, nextPageIndex]() {
setCurrentIndex(nextPageIndex);
currentPage->move(0, 0); // 恢复当前页的位置
delete sender(); // 删除动画对象
});
animation->start();
}
void updatePosition(int value)
{
QWidget* currentPage = widget(currentPageIndex);
QWidget* nextPage = widget(currentPageIndex + (offset > 0 ? -1 : 1));
int deltaX = width() + value;
/* 如果你希望实现淡入淡出效果,可以使用下面的代码代替上一行代码:
* float opacityFactor = qAbs((float)value / width());
* currentPage->setWindowOpacity(1.0 - opacityFactor);
* nextPage->setWindowOpacity(opacityFactor);
*/
currentPage->move(deltaX, 0);
nextPage->move(value, 0);
}
private:
int currentPageIndex;
QPoint startPos;
int offset;
};
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
CustomStackedWidget stackedWidget;
QLabel* label1 = new QLabel("Page 1");
label1->setAlignment(Qt::AlignCenter);
// 创建其他页面的控件,例如label2、label3等
stackedWidget.addWidget(label1);
// 添加其他页面的控件,例如stackedWidget.addWidget(label2)、stackedWidget.addWidget(label3)等
stackedWidget.show();
return app.exec();
}
这是一个简单的示例,展示了如何使用QStackedWidget和QPropertyAnimation实现左右滑动效果。你可以根据自己的需求进一步扩展和优化代码。
内容由零声教学AI助手提供,问题来源于学员提问