首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >QTConcurrent多次触发信号

QTConcurrent多次触发信号
EN

Stack Overflow用户
提问于 2022-05-10 17:50:03
回答 1查看 85关注 0票数 -1

我正在编写一个c++ qt程序。所以我有两节课。在mainwindow中,我有一个函数,该函数在单击按钮时触发,并在另一个线程上运行第二个类中的函数。当我第一次调用这个函数时,一切正常,但是当我第二次运行这个函数时,这个函数已经被调用了两次等等。

这是我的代码: mainwindow.h

代码语言:javascript
复制
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "secondclass.h"

#include <QFutureWatcher>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

public slots:
    void slot(QString text);
private slots:
    void on_pushButton_clicked();

private:
    Ui::MainWindow *ui;
    secondClass* secondclass;
    QFutureWatcher<void>* futureWatcher;
};
#endif // MAINWINDOW_H

mainwindow.cpp

代码语言:javascript
复制
#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFuture>
#include <QFutureWatcher>
#include <QtConcurrent/QtConcurrent>
#include <iostream>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , secondclass(new secondClass())
{
    ui->setupUi(this);
    connect(secondclass, &secondClass::signal, this, &MainWindow::slot);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    auto futureWatcher = new QFutureWatcher<void>(this);
    connect(futureWatcher, &QFutureWatcher<void>::finished, futureWatcher, &QFutureWatcher<void>::deleteLater);
    futureWatcher->setFuture(QtConcurrent::run( [=]{ secondclass->func();}));
}

void MainWindow::slot(QString text)
{
    std::cout << text.toStdString() << std::endl;
}

secondclass.h

代码语言:javascript
复制
#ifndef SECONDCLASS_H
#define SECONDCLASS_H

#include <QObject>

class secondClass : public QObject
{
    Q_OBJECT
public:
    secondClass();
    void func();

signals:
    void signal(QString text);
};

#endif // SECONDCLASS_H

secondclass.cpp

代码语言:javascript
复制
#include "secondclass.h"
#include <QString>
#include <sstream>
#include <iostream>

secondClass::secondClass()
{
}

QString text;
std::ostringstream ss;

void secondClass::func()
{
    text.clear();
    ss << "Test\n";
    std::cout << "Test thread" << std::endl;
    text = QString::fromStdString(ss.str());
    signal(text);
}
EN

回答 1

Stack Overflow用户

发布于 2022-05-10 19:48:06

您应该只调用QObject::connect(...)一次,每次输入on_pushButton_3_clicked()时,您都要创建另一个连接。将connect调用移动到MainWindow构造函数,或者移到只发生一次的其他地方。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72190920

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档