问题的由来
心血来潮,想利用QTimer 配合
setWindowOpacity()方法来实现一个窗体淡入的效果。
✿实验代码
粗糙的实验代码:
[cpp] view plain copy print ?
- 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;
- }
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
✿失败原因
[cpp] view plain copy print ?
- void QWidget::setWindowOpacity(qreal opacity)
- {
- Q_D(QWidget);
- if (!isWindow())
- return;
-
- }
void QWidget::setWindowOpacity(qreal opacity)
{
Q_D(QWidget);
if (!isWindow())
return;
//...
}
✿解决方案
QGraphicsOpacityEffect
[cpp] view plain copy print ?
-
- opacityEffect = new QGraphicsOpacityEffect;
- ui->widget->setGraphicsEffect(opacityEffect);
- ...
-
- opacityEffect->setOpacity(opacity[opalevel]);
// in the constructor
opacityEffect = new QGraphicsOpacityEffect;
ui->widget->setGraphicsEffect(opacityEffect);
...
// in changeOpacity()
opacityEffect->setOpacity(opacity[opalevel]);
✿效果图