我怎样才能从 mainWindow class (Principal) 加入一个 Thread 运行 函数?

How can I join a Thread running a function from the mainWindow class (Principal)?

我在编译项目时收到此错误消息:

"Can not convert 'Principal::setValues' from type 'void*(Principal::)(void*)' to type 'void*()(void)' " ...

enter code here 
void* Principal:: setValues(void*){
    QString velocidadCARGA=QString::number(VelocidadCargador);    
    QString velocidadLAVA=QString::number(VelocidadLavado);
    ui->Velocidad_Carga->setText(velocidadCARGA);
    ui->Velocidad_Lavado->setText(velocidadLAVA);
    ui->lbl_CantidadActual_Banda_Principal->setNum(botellasCargadas);
    return NULL;
}


void Principal::on_Start_Cargador_clicked(){
    pthread_t hilo3;
    pthread_create(&hilo3,NULL,setValues,NULL);//error in this line.
    pthread_join(hilo3,NULL);
}

Principal::setValues是一个成员函数,所以它的类型不符合pthread_create.

要求的函数类型

要在线程中启动成员函数,您可以声明一些静态方法并将 this 对象传递给它:

class Principal
{
...
static void* setValuesThread(void *data);
...
}

void* Principal::setValuesThread(void *data)
{
    Principal *self = reinterpret_cast<Principal*>(data);
    self->setValues();
    return NULL;
}

// your code
void Principal::setValues()
{
    QString velocidadCARGA=QString::number(VelocidadCargador);    
    QString velocidadLAVA=QString::number(VelocidadLavado);
    ui->Velocidad_Carga->setText(velocidadCARGA);
    ui->Velocidad_Lavado->setText(velocidadLAVA);
    ui->lbl_CantidadActual_Banda_Principal->setNum(botellasCargadas);
}

void Principal::on_Start_Cargador_clicked()
{
    pthread_t hilo3;
    pthread_create(&hilo3, NULL, Principal::setValuesThread, this);
    pthread_join(hilo3,NULL);
}

但是如果 Principal 是一个 Qt 小部件(我想它是),则此代码将不起作用,因为在 Qt 中您只能从主线程访问小部件。

如果您想在工作线程中进行一些繁重的计算,然后将结果传递给您的小部件,您可以使用 QThread 和 Qt signals/slots 机制。

一个简单的例子:

class MyThread : public QThread
{
    Q_OBJECT
public:
    MyThread(QObject *parent = 0);

    void run();

signals:
    void dataReady(QString data);
}

void MyThread::run()
{
    QString data = "Some data calculated in this worker thread";
    emit dataReady(data);
}

class Principal
{
...
public slots:
   void setData(QString data);
}

void Principal::setData(QString data)
{
    ui->someLabel->setText(data);
}

void Principal::on_Start_Cargador_clicked()
{
    MyThread *thread = new MyThread;
    connect(thread, SIGNAL(dataReady(QString)), this, SLOT(setData(QString()));
    connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
    thread->start();
}

这里有一些Qt多线程技术的相关文章:

http://doc.qt.io/qt-5/thread-basics.html

http://doc.qt.io/qt-5/threads-technologies.html