问题的由来

 

心血来潮,想利用QTimer 配合setWindowOpacity()方法来实现一个窗体淡入的效果。

实验代码

粗糙的实验代码:

  1. voidWidget::on_pushButton_clicked()
  2. {
  3. QTimer*timerOpacity=newQTimer(this);
  4. connect(timerOpacity,SIGNAL(timeout()),this,SLOT(changeOpacity()));
  5. timerOpacity->start(100);
  6. }
  7.  
  8. voidWidget::changeOpacity()
  9. {
  10. if(opalevel>8)return;
  11. doubleopacity[9]={0.9,0.8,0.7,0.6,0.5,0.4,0.3,0.2,0.1};
  12. ui->stackedWidget->setWindowOpacity(opacity[opalevel]);
  13. ui->widget->setWindowOpacity(opacity[opalevel]);
  14. this->setWindowOpacity(opacity[opalevel]);
  15.  
  16. qDebug()<<"opalevel="<<opalevel<<"ui->widgetopacity:"<<ui->widget->windowOpacity();
  17. qDebug()<<"opalevel="<<opalevel<<"ui->stackedWidgetopacity:"<<ui->stackedWidget->windowOpacity();
  18. qDebug()<<"opalevel="<<opalevel<<"uiopacity:"<<this->windowOpacity()<<endl;
  19. }

 

 

实验失败

现象是主窗体的有淡入的效果,即透明度有变化,但是子窗体没有,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
 

失败原因

  1. voidQWidget::setWindowOpacity(qrealopacity)
  2. {
  3. Q_D(QWidget);
  4. if(!isWindow())
  5. return;
  6. //...
  7. }

 

解决方案

QGraphicsOpacityEffect

  1. //intheconstructor
  2. opacityEffect=newQGraphicsOpacityEffect;
  3. ui->widget->setGraphicsEffect(opacityEffect);
  4. ...
  5. //inchangeOpacity()
  6. opacityEffect->setOpacity(opacity[opalevel]);

 

效果图

 

Qt :非window子窗体的透明度设置_淡入