[英]Qt Slot not being Called
I got a program in which I connect with a QSignalMapper multiple signal from object to a slot in the main program: 我有一个程序,在其中我将QSignalMapper多个信号从对象连接到主程序中的一个插槽:
class A()
{
private:
QSignalMapper * signalMapperRead_;
std::vector<Service*> services_;
public:
void initConnection()
{
signalMapperRead_ = new QSignalMapper();
connect(signalMapperRead_, SIGNAL(mapped(int)), this, SLOT(readyToSendToService(int)));
for ( size_t i = 0 ; i < services_.size() ; ++i )
{
connect(services_.at(i), SIGNAL(readyToSendToServer()), signalMapperRead_, SLOT(map()));
signalMapperRead_->setMapping(services_.at(i), (int)i);
}
}
int run()
{
initConnection();
for(;;)
{
//do stuff;
}
}
};
int main()
{
QApplication app(argc, argv);
A * a = new A();
a->run();
return app.exec
}
then, as the program is a kind of server i make him loop, and waiting for new client, ... 那么,因为程序是一种服务器,我让他循环,等待新客户,...
But the slot is never called. 但是从来没有调用过这个插槽。 I am thinking that maybe it's because the program is always in the loop and never check if a signal has been emitted. 我想也许是因为程序总是在循环中,从不检查信号是否已经发出。
Can you please help me 你能帮我么
Don't use your own loop, create a QApplication and call its exec() method. 不要使用自己的循环,创建QApplication并调用其exec()方法。
You have to call QApplication::exec() for Qt to deliver signals. 您必须为Qt调用QApplication :: exec()来传递信号。
Edit for changed code: Just remove the for(;;)-Loop, it's uneccessary. 编辑已更改的代码:只需删除for(;;) - 循环,这是不必要的。 QApplication::exec() has its own loop. QApplication :: exec()有自己的循环。
But the slot is never called. 但是从来没有调用过这个插槽。
The Qt documentation about QApplication::exec
says: 有关QApplication::exec
的Qt文档说:
Enters the main event loop and waits until exit() is called [...]. 进入主事件循环并等待直到调用exit()[...]。 It is necessary to call this function to start event handling. 必须调用此函数来启动事件处理。 The main event loop receives events from the window system and dispatches these to the application widgets. 主事件循环从窗口系统接收事件并将这些事件分派给应用程序窗口小部件。 [...] Generally, no user interaction can take place before calling exec() . [...] 通常,在调用exec()之前不能进行任何用户交互 。 [...] [...]
This means that it's the exec
method that takes care of the signal-slot system. 这意味着它是负责信号槽系统的exec
方法。 You are calling A::run
(before the exec
function) which contains an for(;;)
infinite loop which will block the real loop from being executed leading to your signals to be lost. 你正在调用A::run
(在exec
函数之前),它包含一个for(;;)
无限循环,它将阻止执行实际循环,导致你的信号丢失。
I have found a work-around. 我找到了解决办法。 Beside I am not sure it's very efficient, my solution is to start a QEventLoop
at every cycle of my for(;;)
loop, and I made this QEventLoop
quit on a QTimer
timeout 除了我不确定它是非常有效的,我的解决方案是在我的for(;;)
循环的每个循环启动一个QEventLoop
,并且我在QTimer
超时时退出了QEventLoop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.