问题的由来
心血来潮,想利用QTimer 配合setWindowOpacity()方法来实现一个窗体淡入的效果。
实验代码
粗糙的实验代码:
- voidWidget::on_pushButton_clicked()
- {
- QTimer*timerOpacity=newQTimer(this);
- connect(timerOpacity,SIGNAL(timeout()),this,SLOT(changeOpacity()));
- timerOpacity->start(100);
- }
- voidWidget::changeOpacity()
- {
- if(opalevel>8)return;
- doubleopacity[9]={0.9,0.8,0.7,0.6,0.5,0.4,0.3,0.2,0.1};
- ui->stackedWidget->setWindowOpacity(opacity[opalevel]);
- ui->widget->setWindowOpacity(opacity[opalevel]);
- this->setWindowOpacity(opacity[opalevel]);
- qDebug()<<"opalevel="<<opalevel<<"ui->widgetopacity:"<<ui->widget->windowOpacity();
- qDebug()<<"opalevel="<<opalevel<<"ui->stackedWidgetopacity:"<<ui->stackedWidget->windowOpacity();
- qDebug()<<"opalevel="<<opalevel<<"uiopacity:"<<this->windowOpacity()<<endl;
- }
实验失败
现象是主窗体的有淡入的效果,即透明度有变化,但是子窗体没有,opacity始终为1。
Log :
opalevel =0ui->widget opacity: 1
opalevel =0ui->stackedWidget opacity: 1
opalevel =0ui opacity0.898039
......
opalevel =8ui->widget opacity: 1
opalevel =8ui->stackedWidget opacity: 1
opalevel =8ui opacity0.0980392
失败原因
- voidQWidget::setWindowOpacity(qrealopacity)
- {
- Q_D(QWidget);
- if(!isWindow())
- return;
- //...
- }
解决方案
QGraphicsOpacityEffect
- //intheconstructor
- opacityEffect=newQGraphicsOpacityEffect;
- ui->widget->setGraphicsEffect(opacityEffect);
- ...
- //inchangeOpacity()
- opacityEffect->setOpacity(opacity[opalevel]);
效果图