我是Qt的新手,我正在努力让一个简单的插槽/信号工作。
在我的Qt应用程序中,当我按下按钮时,我有一个长时间运行的任务。为了保持gui响应,我在一个线程中开始这项工作。当线程完成其任务时,我希望它显示一个消息框。我首先尝试在我的线程中显示消息框,但很快发现这只能从gui线程中获取。然后我尝试在线程的末尾发出一个信号,表示消息框应该弹出,但从不调用相应的插槽。
//MainWindow.h:
#include <QMainWindow>
#include "myclass.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_my_button_clicked();
void handleComplete(std::string endMsg);
private:
Ui::MainWindow *ui;
MyClass mymember;
std::thread myThread;
};
// MainWindow.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QWidget::setWindowFlags(Qt::CustomizeWindowHint);
connect(&mymember, &MyClass::workComplete, this, &MainWindow::handleComplete);
}
void MainWindow::on_my_button_clicked() {
myThread = std::thread([&] {
std::string endMsg = mymember.DoWork();
emit mymember.workComplete(endMsg);
//QMessageBox::information(this, "Work Complete", QString::fromStdString(endMsg)); // first attempt
});
}
void MainWindow::handleComplete(std::string endMsg){
QMessageBox::information(this, "Work Complete", QString::fromStdString(endMsg));
}
MyClass继承自QObject,包含QObject宏,并且信号定义为void workComplete(std::string endmsg);
如何在线程末尾弹出消息框(最好不在MyClass.DoWork()
方法中发出信号)?
EDIT ::
//myclass.h
class MyClass : public QObject
{
Q_OBJECT
signals:
void workComplete(std::string endMsg);
public:
std::string DoWork();
};