我正在编写一个c++ qt程序。所以我有两节课。在mainwindow中,我有一个函数,该函数在单击按钮时触发,并在另一个线程上运行第二个类中的函数。当我第一次调用这个函数时,一切正常,但是当我第二次运行这个函数时,这个函数已经被调用了两次等等。
这是我的代码: mainwindow.h
#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_Hmainwindow.cpp
#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
#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_Hsecondclass.cpp
#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);
}发布于 2022-05-10 19:48:06
您应该只调用QObject::connect(...)一次,每次输入on_pushButton_3_clicked()时,您都要创建另一个连接。将connect调用移动到MainWindow构造函数,或者移到只发生一次的其他地方。
https://stackoverflow.com/questions/72190920
复制相似问题