简体   繁体   中英

Qt Program Hangs (Not Responding) Until Function ends then starts working again

I have a UI application in Qt, i have a couple of functions that run large scale SQL queries that returns thousands of results.

when the button that runs this query is clicked the UI windows just instantly goes to 'not responding' however i can see from console outputs that everything is still actually running in the background. As soon as the function ends the data is presented as expected and the UI is responding again and fully functional.

i know this is due to the fact that the function is looping thousands of times due to the large number of results, but i was hoping that i could have just put in a loading bar that progresses as the search does instead of just locking up the window making it look like the program has crashed. AFAIK i dont have memory leaks so does anyone have any suggestions?

oh also im thinking its not memory leaks because when i click that button task manager shows only a couple of MB of memory being used for this process and processor is by no means maxing out either

In an application, there's one thread that's responsible for handling UI events, messages, whatever you want to call them. Suppose that you have a button click event. As long as you don't return from the callback function, no other UI event can be triggered (repainting, updating, etc) and UI becomes unresponsive.

To mitigate this, you should considering performing time consuming tasks in a separate thread and once they're complete, update UI accordingly. If you need to block UI while the task is processed, you can disable your controls, display a pop up progress bar, whatever, but keep the UI thread relatively unoccupied to avoid "not responding" problem.

A simpler solution than to use threads is to use QCoreApplication::processEvents() . If your code is something like this:

void slowFunction()
{
    lostOfResults = makeSqlQuery(...); // quite fast
    for (r in lostOfResults)
        doSomethingWithResult(r); // one call is quite fast
}

If one SQL query or one doSomethingWithResult() doesn't take too much time, you can process pending events using QCoreApplication::processEvents() like this:

void slowFunction()
{
    lostOfResults = makeSqlQuery(...);
    for (r in lostOfResults) 
    {
        doSomethingWithResult(r);
        QCoreApplication::processEvents();
    }
}

Now the GUI events are processed and the program doesn't freeze. But if the SQL query alone takes a lot of time (several seconds) this doesn't help. Then you should consider separate thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM