qt有一个事件循环,允许您监视各种事件,如键盘、鼠标等。因此,当您使用睡眠时,您会阻止它,从而导致gui冻结,如果您有耗时的任务,策略是将其划分为较少的任务,如果我们可以或在新线程中执行它,并通过信号将结果传输到gui线程,请对它们进行权衡。在下面的例子中,我展示了一个简单的实现。
#include <QtWebEngineWidgets>
#include <iostream>
class Worker: public QObject
{
Q_OBJECT
public:
using QObject::QObject;
public slots:
void start_task(){
std::this_thread::sleep_for(std::chrono::seconds(30));
std::clog << "Done sleeping" << std::endl;
emit finished();
}
signals:
void finished();
};
class Thread final : public QThread {
Q_OBJECT
public:
using QThread::QThread;
~Thread() override {
finish(); wait();
}
public slots:
void finish() {
quit(); requestInterruption();
}
};
int main(int argc, char *argv[])
{
QApplication qtapp(argc, argv);
QMainWindow window;
window.setFixedSize({800, 600});
QWebEngineView *webview = new QWebEngineView();
window.setCentralWidget(webview);
window.show();
Thread thread;
QObject::connect(QApplication::instance(), &QApplication::aboutToQuit, &thread, &Thread::finish);
thread.start();
Worker worker;
worker.moveToThread(&thread);
QObject::connect(&worker, &Worker::finished, webview, [webview](){
qDebug()<< "finished";
webview->load({"https://www.google.com"});
});
QMetaObject::invokeMethod(&worker, "start_task", Qt::QueuedConnection);
return qtapp.exec();
}
#include "main.moc"