QTimer每秒执行一次方法 [英] QTimer to execute method every second
问题描述
我正在学习Qt,正在阅读Qt Wiki上的Threads,Events和QObjects,并遵循Wiki的建议,即如何在一段时间内处理某些工作,但不适用于我的特定情况。这是我当前要实现的目标的简单示例。
I'm learning Qt and I was reading about Threads, Events and QObjects from Qt wiki, and followed the wiki recommendations on how to handle some work in a while condition but its not working for my specific case. Here's a simple example of what I'm currently trying to achieve.
class FooEvents : public FooWrapper {
public virtual serverTime(..) { std::cout << "Server time event\n"; }
public virtual connected(..) { std::cout << "Connected event\n"; }
}
class Foo : public QObject {
private:
FooAPI *client;
public:
Foo(FooEvents *ev, QObject *parent = 0) : client(new FooApi(ev)) { .. }
private slots:
void processMessages() {
if (state is IDLE)
reqFooAPiServerTime();
select(client->fd()+1, ...);
if (socket is ready for read)
client.onReceive();
}
public:
void connect(...) {
if (connection) {
QObject::connect(&timer, SIGNAL(timeout()), this, SLOT(processMessages()));
timer.start(1000); // I don't get the output from FooEvents
}
}
}
这很简单,但我认为这说明了我的情况。为什么这不起作用,还有什么其他替代方法可以处理这种情况?谢谢。
This is a very simple but I think it illustrates my case. Why is this not working and what other alternatives to I have to handle this case? Thanks.s
编辑:每秒都会调用processMessages,但事件没有得到任何输出
The processMessages is being called every second but I don't get any output from the events
推荐答案
在何处声明和定义 timer
?
如果它是 Foo :: connect()
的本地内容,它将被销毁,直到有机会火。大概只需要成为 Foo
类的成员对象。
If it's local to Foo::connect()
it'll be destroyed before it ever has a chance to fire. Presumably it just needs to be a member object of the Foo
class.
还要记住, QObject
提供了它自己的计时器简单接口-只需覆盖受保护的虚拟 timerEvent()
函数并调用QObject的 startTimer()
开始获取这些计时器事件。在这种情况下,它们没有结束接收计时器事件的时间,而是最终在覆盖的 timerEvent()
函数中结束:
Also keep in mind that QObject
provides it's own simple interface to a timer - just override the protected virtual timerEvent()
function and call QObject's startTimer()
to start getting those timer events. In this case instead of having a slot to receive the timer events, they will just end up at the overridden timerEvent()
function:
protected:
void timerEvent(QTimerEvent *event) {
processMessages();
}
public:
void connect( /* ... */ ) {
// ...
startTimer(1000);
}
这篇关于QTimer每秒执行一次方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!