問題的由來
心血來潮,想利用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;
- //...
- }