2014-04-22 67 views
0

我试图添加到我的GUI在Qt代码从vrpn服务器接收数据。我需要不断地将数据从这个服务器发送到应用程序,并在接收到一些信息时在界面中调用操作(方法)。如何从后台工作线程使用QThread Qt GUI如何调用方法

但我有无尽循环while (running)问题。我发现解决方案是使用QThread从服务器接收数据,但我无法弄清楚如何从服务器接收一些数据时从QT类中使用方法。

我试过化妆工人这样,但我不知道,如何从另一个类调用方法时,我收到从服务器的一些数据(或者如果它是在所有可能的/或存在更好的方法):

#include "Worker.h" 

#include <iostream> 
#include "vrpn_Analog.h" 


void VRPN_CALLBACK vrpn_analog_callback(void* user_data, vrpn_ANALOGCB analog) 
{ 
    for (int i = 0; i < analog.num_channel; i++) 
    { 
     if (analog.channel[i] > 0) 
     {     
      THERE I WANT CALL METHOD nextImage(), which I have in QT class mainwindow 
     } 

    } 
} 

// --- CONSTRUCTOR --- 
Worker::Worker() { 

} 

// --- DECONSTRUCTOR --- 
Worker::~Worker() { 

} 

// --- PROCESS --- 
// Start processing data. 
void Worker::process() { 

    /* flag used to stop the program execution */ 
    bool running = true; 

    /* VRPN Analog object */ 
    vrpn_Analog_Remote* VRPNAnalog; 

    /* Binding of the VRPN Analog to a callback */ 
    VRPNAnalog = new vrpn_Analog_Remote("[email protected]"); 
    VRPNAnalog->register_change_handler(NULL, vrpn_analog_callback); 

    /* The main loop of the program, each VRPN object must be called in order to process data */ 
    while (running) 
    { 
     VRPNAnalog->mainloop(); 
    } 
} 

我是使用QT的新手,所以我会很感激任何帮助。

回答

1

将信号callback添加到Worker并将指针传递给注册函数(将作为user_data传递)。

void VRPN_CALLBACK vrpn_analog_callback(void* user_data, vrpn_ANALOGCB analog) 
{ 
    for (int i = 0; i < analog.num_channel; i++) 
    { 
     if (analog.channel[i] > 0) 
     {     
      Worker* worker = std::reinterpret_cast<Worker>(user_data); 
      worker ->callback(i, analog.channel[i]); 
     } 

    } 
} 

void Worker::process() { 

    /* flag used to stop the program execution */ 
    bool running = true; 

    /* VRPN Analog object */ 
    vrpn_Analog_Remote* VRPNAnalog; 

    /* Binding of the VRPN Analog to a callback */ 
    VRPNAnalog = new vrpn_Analog_Remote("[email protected]"); 
    VRPNAnalog->register_change_handler(this, vrpn_analog_callback);//add the pointer here 

    /* The main loop of the program, each VRPN object must be called in order to process data */ 
    while (running) 
    { 
     VRPNAnalog->mainloop(); 
    } 
} 

然后到任何你想要独立于你的主窗口中,您可以连接工作者的回调信号。

connect(worker, &Worker::callback, this, &MainWindow::nextImage); 

说了这么多,我建议使用QTimer设置超时0调用VRPNAnalog->mainloop();所以工人的事件回路可以在一段时间运行一次。

0

那里我想要调用方法NEXTIMAGE(),我有QT类主窗口

您可以使用QMetaObject::invokeMethod

QMetaObject::invokeMethod(mainwindow, "nextImage");