2014-04-22 68 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");