單擊按鈕時,我想執行長時間的任務。我想要這個任務來阻止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