Important: Please read the Qt Code of Conduct -

How to render a gif while a function is running?

  • Hi,
    I'm new in this forum and I hope to write in the right section.
    I'm writing an application with Qt and I have the Login page. In this page, when I click the "loginButton" it starts a request to the server.
    This request is inside the on_loginButton_clicked() slot.
    If the server is on, there are no problems.
    Otherwise, I would like to insert a loading gif, in order to give a feedback to the user during the attempt.
    The problem is that, with QCoreApplication::processevents() the gif is showed but it is static. It "starts" only when the slot is finished.
    I read a lot of thing, maybe I can solve with a Qthread but I don't know where I can insert it.

    I attach here the important parts of the slot:

    void LoginWindow::on_loginButton_clicked() {
    	ui.notifyLabel->hide();  // here I set the gif
    	movie = new QMovie(":/images/loading.gif");
    	if (!movie->isValid()) {
    		auto error = movie->lastErrorString();
    	//[.....] Connection with server

    Thank you for your help!

  • @leonardort
    What sort of calls are going on inside your
    //[.....] Connection with server
    ? I'm guessing they are "blocking"? Do you have some asynchronous option? Or can you push that out to a thread? Or use Qt network calls which do signals & slots?

  • This post is deleted!

  • @JonB
    I have the creation of a socket, connection to it and the send of a packet.
    Yes they are "blocking" but I want that the loading gif starts BEFORE starting all these operations.

  • Lifetime Qt Champion

    @leonardort Loading GIF before starting these operations will not change anything as blocking calls block event loop which is needed to play the GIF. If you can't switch to an assynchronous API move your blocking operations to a thread as @JonB suggested.s

  • @jsulm Do you mean a normal thread or a Qthread?
    So, your suggestion is to put the connection with server into a thread, not the movie->start(). Right?
    Can you give me a small example?

  • Lifetime Qt Champion

    @leonardort said in How to render a gif while a function is running?:

    Do you mean a normal thread or a Qthread?

    QThread is simply a class which manages a thread.

    You would need to move all these blocking calls into a thread.
    Please start here, you will find examples also:

  • @jsulm ok, thank you very much.
    Using threads something change. The problem is that in a first moment I updated some labels in the UI in the slot, while now I have to manage it with a return code.

Log in to reply