Home > Mobile >  How to launch the QMainWindow with a fading animation?
How to launch the QMainWindow with a fading animation?

Time:12-01

I tried launching my window this way:

#include "stdafx.h"
#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);

    setWindowOpacity(0);

    QGraphicsOpacityEffect* eff = new QGraphicsOpacityEffect(this);

    QPropertyAnimation* ani = new QPropertyAnimation(eff, "windowOpacity");
    ani->setDuration(3000);
    ani->setStartValue(0);
    ani->setEndValue(1);
    ani->setEasingCurve(QEasingCurve::OutBack);
    ani->start(QPropertyAnimation::DeleteWhenStopped);
}


#include "mainwindow.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    MainWindow w;
    w.show();
    return a.exec();
}

But the window never became visible, I would like to it be initialized with a fade in effect.

What's the proper way to achieve it?

CodePudding user response:

Two issues I see. First, as originally written, your main function is going to exit immediately after opening the window. Add return a.exec(); at the end of main.

Next, you are animating QGraphicsOpacityEffect. As written, your example code has no connection between QGraphicsOpacityEffect and the window. Your animation is animating the property on the effect class, but that doesn't propagate back to the widget. There is no need to use QGraphicsOpacityEffect. Instead, just animate the widget directly:

    ui.setupUi(this);

    setWindowOpacity(0);

    // Notice that the first argument passed in is 'this' - the widget.
    // the widget is what you want to animate.
    QPropertyAnimation* ani = new QPropertyAnimation(this, "windowOpacity");
    ani->setDuration(3000);
    ani->setStartValue(0);
    ani->setEndValue(1);
    ani->setEasingCurve(QEasingCurve::OutBack);
    ani->start(QPropertyAnimation::DeleteWhenStopped);
  • Related