Home > OS >  QTConcurrent triggers a signal multiple times
QTConcurrent triggers a signal multiple times

Time:05-12

I am writing a c qt program. So I have 2 classes: mainwindow and Algorithm. In mainwindow I have a function that fires when a button is clicked and it runs a function from the Algorithms class on another thread. When I call the function for the first time, everything is ok: PackingFinished() is called once, but when I run the function for the second time, the function is already called twice etc.

Here is my code:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

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

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 PackingFinished();

private slots:
    void on_pushButton_3_clicked();

signals:

private:
    Ui::MainWindow *ui;
    Algorithms* algorithms;
};
#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtConcurrent/QtConcurrent>
#include <iostream>
using namespace std;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , algorithms(new Algorithms())
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::on_pushButton_3_clicked()
{    
    auto future = QtConcurrent::run( [=]{ algorithms->PackBytes(); });

    connect(algorithms, &Algorithms::packingFinished, this, &MainWindow::PackingFinished);

}
void MainWindow::PackingFinished()
{
    cout << "Test" << endl;
}

Algorithms.h

#ifndef PACKINGALGORITHMS_H
#define PACKINGALGORITHMS_H

#include <QObject>

class PackingAlgorithms : public QObject
{
    Q_OBJECT
public:
    Algorithms();
    void PackBytes();

signals:
    void packingFinished();
};

#endif // PACKINGALGORITHMS_H

Algorithms.cpp

#include "Algorithms.h"

#include <iostream>
using namespace std;

Algorithms::Algorithms()
{
}
void PackBytes()
{
     packingFinished();
}

CodePudding user response:

You should only call QObject::connect(...) once, every time you enter on_pushButton_3_clicked() you're creating another connection. Move the connect call to the MainWindow constructor, or somewhere else where it will only occur one time.

  •  Tags:  
  • c qt
  • Related