Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
727 views
in Technique[技术] by (71.8m points)

c++ - QTimer to execute method every second

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
"; }
    public virtual connected(..) { std::cout << "Connected event
"; }
}

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

Edit: The processMessages is being called every second but I don't get any output from the events

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Where is timer declared and defined?

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.

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);
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...