gpt4 book ai didi

c++ - Qt GUI 数学应用程序在计算时挂出 GUI

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:57:52 26 4
gpt4 key购买 nike

我的应用程序有一个简单的 GUI = 我必须为我的数学函数设置一些输入参数,然后单击“计算”按钮,函数启动。数学函数是用纯 C 语言编写的,因此没有对象,只有函数。

看起来像这样:

#include "mymath.h"

class myMath : public QMainWindow
{
Q_OBJECT

// ...
void compute();
};

void myMath::compute()
{
//get parameters from gui
call_C_fun();
// save results to GUI
}

此代码的主要问题是,当我单击“计算”时(它会进行大量计算,最多需要 5 分钟左右)它会挂起我的 GUI,所以我不能做任何其他事情(我可以​​'甚至看不到我的 GUI,窗口在计算运行时被“卡住”。函数完成后,它在 QLabels 上打印出结果,GUI 再次“活跃”。我该如何解决这个问题?我不知道当计算需要时间时,我不希望我的 GUI 被“卡住”。有什么想法吗?我考虑过 QThread - 但我在线程方面有点新,所以请提供简单易用的 -理解新手的答案:)

最佳答案

将计算分解到另一个线程,如下所示:-

// This is the object that will run the computation on a different thread
class Computation : public QObject
{
signals:
void Finished();
public slots:
void Compute();
};

然后在主窗口类中创建另一个线程并开始运行:-

class MyMath : public QMainWindow
{
public:
void StartComputation();
};


MyMath::StartComputation()
{
QThread* pThread = new QThread;
Computation* pComputation = new Computation;

// move computation to the new thread
pCompuation->moveToThread(pThread);

// Note Qt5 connection style

// ensure the computation starts when the thread starts
connect(pThread, &QThread::started, pComputation, &Computation::Compute);
// when computation is finished, quit the thread
connect(pComputation, &Compute::Finished, pThread, &QThread::quit);
// have the thread tidy up when finished
connect(pThread, &QThread::finished, pThread, &QThread::deleteLater);
// start it!
pThread->start();
}

关于c++ - Qt GUI 数学应用程序在计算时挂出 GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19095821/

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