我曾考虑过给回调添加其他参数,但是看起来太复杂了(创建自己的修改后的QTimer对象等)。

在阅读完QTimer docs之后,我想到的另一件事是保存timerID并检查,但由于回调中没有内容,我不知道要检查什么:/

如果有人对特殊用例感兴趣:
https://github.com/Bluscream/pyTSon_plugins/blob/master/scripts/antiAFK/init.py#L35

最佳答案

我至少可以想到两种方法:
首先,您可以通过将发件人投射到插槽中来检索指向QTimer的指针:

class MyClass : public QObject
{
    Q_OBJECT
public:
    MyClass(QObject * parent = 0);
    <...>
private Q_SLOTS:
    void onTimerFired();
private:
    void doSomethingAndStartTimer();
private:
    int m_firstTimerId;
    int m_secondTimerId;
};

void MyClass::doSomethingAndStartTimer()
{
    <...>
    QTimer *timer = new QTimer(this);
    m_firstTimerId = timer->timerId();
    connect(timer, SIGNAL(timeout()), this, SLOT(onTimerFired()));
    timer->start();
    <..>
}

void MyClass::onTimerFired()
{
    QTimer * timer = qobject_cast<QTimer*>(sender());
    if (timer) {
        if (timer->timerId() == m_firstTimerId) {
            <...> // Process it somehow
        }
        else if (timer->timerId() == m_secondTimerId) {
            <...> // Process it some other way
        }
    }
}
其次,您可以放弃显式的QTimer用法,而使用startTimer以及重新实现类的timerEvent方法,该方法接收QTimerEvent,您可以从中获取计时器ID
class MyClass : public QObject
{
    Q_OBJECT
public:
    MyClass(QObject * parent = 0);
    <...>
private:
    virtual void timerEvent(QTimerEvent * event);
private:
    void doSomethingAndStartTimer();
private:
    int m_firstTimerId;
    int m_secondTimerId;
};

void MyClass::doSomethingAndStartTimer()
{
    <...>
    int interval = 100; // 100 msec
    m_firstTimerId = startTimer(interval);
    <...>
}

void MyClass::timerEvent(QTimerEvent * event)
{
    if (event->timerId() == m_firstTimerId) {
        <...> // process it somehow
    }
    else if (event->timerId() == m_secondTimerId) {
        <...> // process it some other way
    }
}
documentation中针对QTimer提到了第二种方法:

关于c++ - 有什么方法可以识别调用了哪个QTimer?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48924190/

10-11 21:32