gpt4 book ai didi

c++ - 当运行它的小部件(QDialog)在没有多线程的情况下关闭时,如何停止长循环?

转载 作者:行者123 更新时间:2023-11-28 06:36:18 25 4
gpt4 key购买 nike

我在 QDialog 中有一个相当长的 foreach 循环。它基本上看起来像这样:

foreach (xxx, xxx) {
... doSomeStuff ...
QApplication::processEvents();

if (m_cancelMapLoading) {
break;
}
}

通过单击“取消”按钮将 m_cancelMapLoading 设置为 true。 QApplication::processEvents();使这成为可能。

这工作得很好,但如果只要 foreach 循环仍在运行就关闭对话框,它就会继续运行。我尝试在关闭对话框的每个函数中将 m_cancelMapLoading 设置为 true,但这没有帮助。

我还尝试不仅测试 m_cancelMapLoading 是否为真,还尝试测试 isVisible()。这实际上停止了对话框,但它立即重新打开它,其中没有 GUI 元素。

不幸的是,QtConcurrent::run 等不能用于该函数,因为由 foreach 循环操作的数据结构不是线程安全的。

有什么方便的方法可以解决这个问题吗?

最佳答案

您可以使用 QTimer和 Qt 的父子结构在这里对您有利。超时值为零的QTimer在Qt中有特殊意义

As a special case, a QTimer with a timeout of 0 will time out as soon as all the events in the window system's event queue have been processed. This can be used to do heavy work while providing a snappy user interface:

所以你可以做类似的事情

void Dialog::beginDoingStuff()
{
m_timer = new QTimer(this);
connect(m_timer, SIGNAL(timeout()), this, SLOT(processData());
m_timer->start(0);
}

void Dialog::processData()
{
// Perform one cycle of your process here
}

这将在与对话框其余部分相同的线程中执行 processData() 函数,当对话框因关闭而销毁时,计时器将被删除(因为它的父级是对话框),这意味着处理将停止。

关于c++ - 当运行它的小部件(QDialog)在没有多线程的情况下关闭时,如何停止长循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26723538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com