简体   繁体   English

将工作线程信号与 MainWindow 插槽 (Qt5) 连接时出错

[英]Error connecting Worker Thread signal with MainWindow slot (Qt5)

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.工作线程应该定期向 MainWindow 发送信号以通知它当前的进度状态。 In order to implement the worker thread, I subclass QThread and reimplement the run method.为了实现工作线程,我QThread并重新实现了run方法。 When I compile the program using QTCreator, I always get these two errors:当我使用 QTCreator 编译程序时,总是出现以下两个错误:

In the Header file of Worker , which implements the working thread:Worker的头文件中,它实现了工作线程:

.../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:MainWindow的源文件中,当我尝试将Worker信号连接到MainWindow插槽时:

.../worker.cpp:23: error: undefined reference to `Worker::updateLabelSig(int)'

Worker.h工人.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工人.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 类中,我有一个按钮,如果单击该按钮应该启动线程:

MainWindow.cpp :主窗口.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));
}

Ok, it turned out that I simply needed to rerun qmake in order to get things to work.好吧,事实证明我只需要重新运行qmake才能使事情正常工作。 When I first wrote the header file worker.h I forgot to add the Q_OBJECT macro which I added later.当我第一次编写头文件worker.h我忘记添加后来添加的Q_OBJECT宏。 However, I didn't run qmake .但是,我没有运行qmake

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM