单击按钮时,我想执行长时间的任务。我想要这个任务来阻止UI,因为应用程序在任务完成之前无法运行。但是,我想向用户指出发生了什么,因此我有一个BusyIndicator
(在渲染线程上运行),并且在操作开始之前设置为显示。但是,它从不呈现。为什么?Qt Quick中的阻止操作
main.cpp中:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QDateTime>
#include <QDebug>
class Task : public QObject
{
Q_OBJECT
Q_PROPERTY(bool running READ running NOTIFY runningChanged)
public:
Task() : mRunning(false) {}
Q_INVOKABLE void run() {
qDebug() << "setting running property to true";
mRunning = true;
emit runningChanged();
// Try to ensure that the scene graph has time to begin the busy indicator
// animation on the render thread.
Q_ASSERT(QMetaObject::invokeMethod(this, "doRun", Qt::QueuedConnection));
}
bool running() const {
return mRunning;
}
signals:
void runningChanged();
private:
Q_INVOKABLE void doRun() {
qDebug() << "beginning long, blocking operation";
QDateTime start = QDateTime::currentDateTime();
while (start.secsTo(QDateTime::currentDateTime()) < 2) {
// Wait...
}
qDebug() << "finished long, blocking operation";
qDebug() << "setting running property to false";
mRunning = false;
emit runningChanged();
}
bool mRunning;
};
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
Task task;
engine.rootContext()->setContextProperty("task", &task);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
#include "main.moc"
main.qml:
import QtQuick 2.6
import QtQuick.Window 2.2
import Qt.labs.controls 1.0
Window {
width: 600
height: 400
visible: true
Shortcut {
sequence: "Ctrl+Q"
onActivated: Qt.quit()
}
Column {
anchors.centerIn: parent
spacing: 20
Button {
text: task.running ? "Running task" : "Run task"
onClicked: task.run()
}
BusyIndicator {
anchors.horizontalCenter: parent.horizontalCenter
running: task.running
onRunningChanged: print("BusyIndicator running =", running)
}
}
}
调试输出看起来是正确的事件顺序方面:
setting running property to true
qml: BusyIndicator running = true
beginning long, blocking operation
finished long, blocking operation
setting running property to false
qml: BusyIndicator running = false
我只是不明白为什么你坚持锁定主线程?只需使用工作线程并在执行时将事件阻塞到UI。大多数操作系统会给你一个“应用程序没有响应”,如果你阻塞主线程,通常会要求用户终止或立即终止。 – dtech
我正在使用GUI线程,因为我不需要切换到单独的线程。我没有遇到过“应用程序没有响应”的消息。 – Mitch
除非它是涉及UI元素的操作,否则您绝对可以通过工作线程异步执行它。经验法则是每个需要超过25毫秒的操作应该以这种方式处理。你不会得到“没有回应”,因为你知道发生了什么事情,并且当操作系统未能传递给应用程序事件循环的输入事件发生时,你会远离接触应用程序,你会得到它。绝对不是你想要传递给客户的东西。 – dtech