qt create 直接在ui文件中设置tabwidget切换时无动画直接移植技术动
时间: 2024-02-05 13:14:01 浏览: 170
如果您想在Qt Creator中设置TabWidget切换时有动画效果,可以使用QStackedWidget和QPropertyAnimation类来实现。
1. 创建一个QStackedWidget并将其添加到窗口中
在Qt Designer中,将QStackedWidget拖放到窗口中。在代码中,您可以使用以下代码将其添加到窗口中:
```
ui->stackedWidget->addWidget(page1);
ui->stackedWidget->addWidget(page2);
ui->stackedWidget->addWidget(page3);
```
2. 为TabWidget添加点击事件
在Qt Designer中,您可以为TabWidget添加单击事件。在代码中,您可以使用以下代码为TabWidget添加单击事件:
```
connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(onTabChanged(int)));
```
3. 实现切换时的动画效果
在onTabChanged函数中,您可以使用QPropertyAnimation类来实现动画效果。以下是一个示例代码:
```
void MainWindow::onTabChanged(int index) {
int currentIndex = ui->stackedWidget->currentIndex();
if (index != currentIndex) {
QWidget *currentWidget = ui->stackedWidget->widget(currentIndex);
QWidget *nextWidget = ui->stackedWidget->widget(index);
int width = ui->stackedWidget->width();
int height = ui->stackedWidget->height();
QPropertyAnimation *animation1 = new QPropertyAnimation(currentWidget, "geometry");
animation1->setDuration(500);
animation1->setStartValue(QRect(0, 0, width, height));
animation1->setEndValue(QRect(-width, 0, width, height));
QPropertyAnimation *animation2 = new QPropertyAnimation(nextWidget, "geometry");
animation2->setDuration(500);
animation2->setStartValue(QRect(width, 0, width, height));
animation2->setEndValue(QRect(0, 0, width, height));
QParallelAnimationGroup *group = new QParallelAnimationGroup;
group->addAnimation(animation1);
group->addAnimation(animation2);
ui->stackedWidget->setCurrentIndex(index);
group->start(QAbstractAnimation::DeleteWhenStopped);
}
}
```
这段代码将当前窗口和下一个窗口添加到QPropertyAnimation类中,并使用QParallelAnimationGroup类将它们同时执行。这将导致当前窗口向左移动,而下一个窗口向右移动,从而创建切换时的动画效果。
阅读全文
相关推荐


















