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

✿问题的由来


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

✿实验代码


 粗糙的实验代码:
void Widget::on_pushButton_clicked()
{
   QTimer *timerOpacity = new QTimer(this);
   connect(timerOpacity,SIGNAL(timeout()),this,SLOT(changeOpacity()));
   timerOpacity->start(100);
}

void Widget::changeOpacity()
{
    if (opalevel > 8) return;
    double opacity[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->widget opacity:"<<ui->widget->windowOpacity();
    qDebug()<<"opalevel = "<< opalevel <<" ui->stackedWidget opacity:"<<ui->stackedWidget->windowOpacity();
    qDebug()<<"opalevel = "<< opalevel <<" ui opacity : "<< this->windowOpacity()<<endl;
}

✿实验失败


现象是主窗体的有淡入的效果,即透明度有变化,但是子窗体没有,opacity始终为1 
Log :
opalevel =  0  ui->widget opacity: 1 
opalevel =  0  ui->stackedWidget opacity: 1 
opalevel =  0  ui opacity  0.898039 
......

opalevel =  8  ui->widget opacity: 1 
opalevel =  8  ui->stackedWidget opacity: 1 
opalevel =  8  ui opacity  0.0980392 

✿失败原因


void QWidget::setWindowOpacity(qreal opacity)
{
    Q_D(QWidget);
    if (!isWindow())
        return;
//...
}

✿解决方案


     QGraphicsOpacityEffect

        
// in the constructor
opacityEffect = new QGraphicsOpacityEffect;
ui->widget->setGraphicsEffect(opacityEffect);
...
// in changeOpacity()
opacityEffect->setOpacity(opacity[opalevel]);

✿效果图

   Qt :非window子窗体的透明度设置_第1张图片

你可能感兴趣的:(UI,qt,Signal)