qt - 如何加入运行 mainWindow 类(Principal)中的函数的线程?

标签 qt function compiler-errors pthreads qt-creator

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

“无法将 'Principal::setValues' 从类型 'void*(Principal::)(void*)' 转换为类型 '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 信号/插槽机制。

一个简单的例子:
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

关于qt - 如何加入运行 mainWindow 类(Principal)中的函数的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32556587/

相关文章:

c++ - 一个非常奇怪的C++行为

android-studio - Android studio 2.3.2上JNI编译错误

qt - 我可以在 Qt 中制作 Material 抽屉导航和 FAB 吗?

qt - 如何在 QML 中模拟 C 风格的 "ifdef"宏?

javascript - 无操作的 JavaScript 约定是什么?

javascript - 我的 JavaScript 函数由于某种原因无法运行

java - 从long到int的可能的有损转换,找不到错误

c++ - Qt - 对非 opengl 小部件的影响

c++ - 调整窗口大小,使主要小部件具有特定大小

javascript - 为什么这个内部函数返回未定义?