是的,你可以通过设置透明度来同时显示两个小部件。以下是更新后的示例代码:
#include <QtWidgets>
class SlidingStackedWidget : public QStackedWidget {
public:
SlidingStackedWidget(QWidget *parent = nullptr) : QStackedWidget(parent) {
animation.setTargetObject(this);
animation.setPropertyName("slide");
animation.setEasingCurve(QEasingCurve::InOutQuad);
}
void slide(int index, bool scale = true) {
if (index < 0 || index >= count())
return;
int offset = currentIndex() > index ? width() : -width();
QWidget *currentWidget = widget(currentIndex());
QWidget *nextWidget = widget(index);
QGraphicsOpacityEffect *opacityEffectCurrent = new QGraphicsOpacityEffect(currentWidget);
QGraphicsOpacityEffect *opacityEffectNext = new QGraphicsOpacityEffect(nextWidget);
opacityEffectCurrent->setOpacity(1.0); // 当前页面完全显示
opacityEffectNext->setOpacity(1.0); // 下一个页面完全显示
currentWidget->setGraphicsEffect(opacityEffectCurrent);
nextWidget->setGraphicsEffect(opacityEffectNext);
setCurrentIndex(index);
QRect startRect = geometry();
QRect endRect = startRect.translated(offset, 0);
animation.setStartValue(startRect);
animation.setEndValue(endRect);
animation.start();
}
protected:
QVariant slide() const {
return pos();
}
void setSlide(const QVariant &pos) {
move(pos.toPoint());
}
private:
QPropertyAnimation animation;
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QMainWindow mainWindow;
SlidingStackedWidget stackedWidget(&mainWindow);
QWidget *page1 = new QWidget(&stackedWidget);
page1->setStyleSheet("background-color: red;");
QLabel* label1 = new QLabel(page1);
label1->setText("Page 1");
label1->setAlignment(Qt::AlignCenter);
label1->setFont(QFont("Arial", 30));
label1->setStyleSheet("color: white;");
QWidget *page2 = new QWidget(&stackedWidget);
page2->setStyleSheet("background-color: blue;");
QLabel* label2 = new QLabel(page2);
label2->setText("Page 2");
label2->setAlignment(Qt::AlignCenter);
label2->setFont(QFont("Arial", 30));
label2->setStyleSheet("color: white;");
stackedWidget.addWidget(page1);
stackedWidget.addWidget(page2);
QObject::connect(&stackedWidget, &SlidingStackedWidget::currentChanged,
[&](int index) {
stackedWidget.slide(index); // 滑动到指定页面
});
mainWindow.setCentralWidget(&stackedWidget);
mainWindow.show();
return app.exec();
}
现在,切换页面时,你可以同时看到两个小部件。每个小部件都设置了自己的背景颜色和文本内容,你可以根据需要进行调整。
希望这次给出的代码满足你的需求。如果还有任何疑问,请随时提问。
内容由零声教学AI助手提供,问题来源于学员提问