Running code in the main loop

前端 未结 3 1781
予麋鹿
予麋鹿 2020-12-20 18:19

I need a way to run an update function of my own in the main thread. I couldn\'t find a signal that would tick me every time the main loop runs.

Am I doing this wr

3条回答
  •  有刺的猬
    2020-12-20 19:04

    Alternatively, if you want to execute your code every time the event loop runs you can use the slot method invocation via the queued connection:

    class EvtLoopTicker : public QObject
    {
        Q_OBJECT
    public:
    
        EvtLoopTicker(QObject *pParent = nullptr)
            : QObject(pParent)
        {}
    
    public slots:
    
        void launch()
        {
            tickNext();
        }
    
    private slots:
    
        void tick()
        {
            qDebug() << "tick";
    
            // Continue ticking
            tickNext();
        }
    
    private:
    
        void tickNext()
        {
            // Trigger the tick() invokation when the event loop runs next time
            QMetaObject::invokeMethod(this, "tick", Qt::QueuedConnection);
        }
    
    };
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        EvtLoopTicker ticker;
        ticker.launch();
    
        return a.exec();
    }
    

提交回复
热议问题