I want to write a simple Application which launches a thread to do some computations. The worker thread should periodically send signals to the MainWindow to inform it about the current state of progress. In order to implement the worker thread, I subclass QThread
and reimplement the run
method. When I compile the program using QTCreator, I always get these two errors:
In the Header file of Worker
, which implements the working thread:
.../worker.h:7: error: undefined reference to `vtable for Worker'
In the Source file of MainWindow
, when I try to connect the Worker
signal to the MainWindow
slot:
.../worker.cpp:23: error: undefined reference to `Worker::updateLabelSig(int)'
Worker.h
#ifndef WORKER_H
#define WORKER_H
#include <QThread>
#include <vector>
class Worker : public QThread
{
Q_OBJECT
void run() override;
private:
void computeNumbers();
std::vector<int> foundNumbers;
int upperLimit;
signals:
void updateLabelSig(int);
};
#endif // WORKER_H
Worker.cpp
#include "worker.h"
void Worker::run(){
exec();
computeNumbers();
}
void Worker::computeNumbers(){
upperLimit=1e5;
foundNumbers.push_back(1);
for(int i=2; i<upperLimit; i++){
/////////////do some calculations and emit regular signals to inform main window///////////////////
if(i%10000==0)
emit updateLabelSig(i);
}
}
In the MainWindow class, I have a button which should launch the thread if clicked:
MainWindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPushButton>
#include <QLabel>
#include "worker.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_mainbutton_clicked()
{
Worker* w=new Worker;
QObject::connect(w,SIGNAL(Worker::updateLabelSig(int)),this,SLOT(updateLabel(int)));
w->start();
}
void MainWindow::updateLabel(int i){
findChild<QLabel*>("mainlabel")->setText(QString("Numbers searched so far: ")+QString::number(i));
}