Multithreading QT编程,QT并发运行函数

Multithreading QT编程,QT并发运行函数,multithreading,qt,qtconcurrent,qfuture,Multithreading,Qt,Qtconcurrent,Qfuture,我有一个程序,它的类MainWindow继承自QMainWindow。 我想在一个新线程中运行一个特定的函数 因为我不能从QThread继承,所以最好的解决方案是使用QtConcurrent。 我将QtConcurrent结果存储在QFuture中,但如QT文档中所述,QtConcurrent的结果不能被QFuture::cancel取消 我看到了一些类似于我的问题,但答案是创建一个从QThread继承的类,我不能。 那么解决方案是什么呢? 这是我的密码: mainwindow.h: using

我有一个程序,它的类
MainWindow
继承自
QMainWindow
。 我想在一个新线程中运行一个特定的函数

因为我不能从
QThread
继承,所以最好的解决方案是使用
QtConcurrent
。 我将
QtConcurrent
结果存储在
QFuture
中,但如QT文档中所述,
QtConcurrent
的结果不能被
QFuture::cancel
取消

我看到了一些类似于我的问题,但答案是创建一个从
QThread
继承的类,我不能。 那么解决方案是什么呢? 这是我的密码:

mainwindow.h:

using namespace  std;

class MainWindow : public QMainWindow
{
    Q_OBJECT


public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    ...


private:
    Ui::MainWindow *ui;
    ...
    QFuture<void> future;
    QFutureWatcher< void > futureWatcher;
    QPushButton *stop_pushButton_=new QPushButton;

private slots:
    ...
    void on_graph_pushButton_clicked();
    void generateGraph();
    void stopPushButtonClicked();
    };

当我点击
graph\u按钮时,
generatedGraph
会在一个新线程中被调用,但当我点击
stop\u按钮时,
future
不会停止,
generatedGraph
函数会完全执行。

,只要它有很长的执行时间,并且您希望在单独的线程中调用它。因此,您可以使用
bool abortGraphGenerating
标志,并使用
break
退出循环。谢谢,它从外部库运行另一个函数,执行时间很长,我无法通过添加标志来更改库函数……为什么不创建一个既继承主窗口又继承QThread的包装类呢,调用该函数。请阅读有关
QThread
的文档,从类继承不是在另一个线程中运行某些东西的好做法!当涉及到线程时,您必须首先考虑将要读/写的数据,并将其相应地划分为不同的类。MohammadKanan:谢谢,它可能会起作用,但没有更简单的方法吗?
void MainWindow::stopPushButtonClicked()
{
    futureWatcher.setFuture(future);
    futureWatcher.cancel();
    futureWatcher.waitForFinished();
}

   ...
void MainWindow::on_graph_pushButton_clicked()
{
    loadingOn();
    future = QtConcurrent::run(this,&MainWindow::generateGraph);
}

void MainWindow::generateGraph()
{
    InsertLogs::getInstance()->printStatus(USER_GENERATE_GRAPH);
    GenGraph* gr=new GenGraph;
    connect(this,&MainWindow::loadingOffSignal,this,&MainWindow::loadingOff);
    graphType_=gr->generateGraph(persons_comboBox_->currentText(),
                      ui->graphResource1_comboBox->currentText(),
                      ui->graphResource2_comboBox->currentText(),
                      ui->graphType_comboBox->currentText());

    InsertLogs::getInstance()->printSuccess(SYSTEM_GENERATE_GRAPH);

    emit loadingOffSignal();
}