gpt4 book ai didi

c++ - 从非成员静态函数发出信号

转载 作者:太空宇宙 更新时间:2023-11-04 11:35:22 24 4
gpt4 key购买 nike

我第一次尝试使用 QThread,我想从非成员静态函数发出信号。

我的 DataReceiver.h 文件:

#ifndef DATARECEIVER_H
#define DATARECEIVER_H

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

class DataReceiver : public QObject {
Q_OBJECT

public:
DataReceiver();

public slots:
void check();
signals:
void blink();
};

void VRPN_CALLBACK handle_analog( void* userData, const vrpn_ANALOGCB a );

#endif // DATARECEIVER_H

我的 DataReceiver.cpp 文件:

#include "datareceiver.h"
#include "vrpn_Analog.h"

DataReceiver::DataReceiver()
{

}

void DataReceiver::check()
{
bool running = true;

/* VRPN Analog object */
vrpn_Analog_Remote* VRPNAnalog;

/* Binding of the VRPN Analog to a callback */
VRPNAnalog = new vrpn_Analog_Remote("openvibe_vrpn_analog@localhost");
VRPNAnalog->register_change_handler(NULL, handle_analog);

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

void VRPN_CALLBACK handle_analog( void* userData, const vrpn_ANALOGCB a )
{
for( int i=0; i < a.num_channel; i++ )
{
if (a.channel[i] > 0)
{
emit blink();
}
}
}

handle_analog 中,我尝试发出信号,我想在另一个类中使用它。

void MainWindow::checkChannels()
{
QThread *thread = new QThread;
DataReceiver *dataReceiver = new DataReceiver();

dataReceiver->moveToThread(thread);
//connect(thread, SIGNAL(blink()), this, SLOT(nextImage()));
thread->start();
}

但是当我尝试运行时出现错误:

error: C2352: 'DataReceiver::blink' : illegal call of non-static member function

我知道我的错误在哪里,但我不知道如何改正。

最佳答案

如果没有相应的对象来发出信号,那么发出信号是没有意义的,因为您没有任何东西可以连接到它。

因此,您想要的是将指向您的DataReceiver 的指针作为userData 传递,并实现一个发出信号的公共(public)方法。然后你可以将 userData 转换为 DataReceiver 并调用它的方法。

以下不完整的代码试图说明我的意思

void DataReceiver::emitBlink() { // Should of course also be added in header.
emit blink();
}
...
/// Pass in "this" as userData
VRPNAnalog->register_change_handler(this, handle_analog);

...
void VRPN_CALLBACK handle_analog( void* userData, const vrpn_ANALOGCB a )
{
...
reinterpret_cast<DataReceiver*>(userData)->emitBlink();
...
}

关于c++ - 从非成员静态函数发出信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23219501/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com