Qt: Fix 100% CPU usage while downloading files

The wonders of having fast internet, you never realize when this happens
because it completes too quickly...
This commit is contained in:
Stenzek
2024-09-20 21:46:09 +10:00
parent 5f80cb1188
commit d07c7e4b68
4 changed files with 58 additions and 31 deletions

View File

@@ -8,8 +8,11 @@
#include "common/types.h"
#include <QtCore/QByteArray>
#include <QtCore/QCoreApplication>
#include <QtCore/QEventLoop>
#include <QtCore/QMetaType>
#include <QtCore/QString>
#include <QtCore/QTimer>
#include <QtGui/QIcon>
#include <QtWidgets/QWidget>
#include <functional>
@@ -121,4 +124,30 @@ bool SaveWindowGeometry(std::string_view window_name, QWidget* widget, bool auto
/// Restores a window's geometry from configuration. Returns false if it was not found in the configuration.
bool RestoreWindowGeometry(std::string_view window_name, QWidget* widget);
/// CPU-friendly way of blocking the UI thread while some predicate holds true.
template<typename Predicate>
[[maybe_unused]] static void ProcessEventsWithSleep(QEventLoop::ProcessEventsFlags flags, const Predicate& pred,
int sleep_time_ms = 10)
{
if (sleep_time_ms == 0)
{
while (pred())
QCoreApplication::processEvents(flags);
}
if (!pred())
return;
QEventLoop loop;
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, &timer, [&loop, &pred]() {
if (pred())
return;
loop.exit();
});
timer.start(sleep_time_ms);
loop.exec(flags);
}
} // namespace QtUtils