3

Qt 5.3.2 を使用して次のコードを実行すると、残り時間が -1371648957 に設定されます。

QTimer *timer = new QTimer(this);
timer->setSingleShot(true);
timer->start(100);
qDebug() << "remaining" << timer->remainingTime();

その後、ループで残り時間を出力し続けると、負の値が増加するため、発生することtimeout()はありません。これは本当に意味がありません。

少しコンテキストを与えるために、このコードは別のスレッド内で実行され、QTimer はスレッド化されたオブジェクトのコンストラクターで作成されません。

わかりやすくするために更新されたコードを次に示します。

void MainObject::SomeMethod(){
    // main thread
    ObjectWithTimer *owt = new ObjectWithTimer();    
    QThread *someThread = new QThread();
    owt->moveToThread(someThread);
    connect(someThread, SIGNAL(started()), owt, SLOT(doStuff()));
    someThread->start();
}

void ObjectWithTimer::doStuff(){
    while(condition){
        // do various stuff
        // among other things emit SIGNALS to the main thread, that are received
        // so the event loop in the thread is running
        QTimer *timer = new QTimer(this);
        timer->setSingleShot(true);
        timer->start(100);
        qDebug() << "remaining" << timer->remainingTime();

        connect(timer, SIGNAL(timeout()), this, SLOT(onClientTimeoutTest()));
    }
}
void ObjectWithTimer::onClientTimeoutTest(){
    // this method is of course never fired, since the remaining time never reaches 0
}

emitメインスレッドが受信したことを通知できるため、タイマーの作成が別のスレッドで正しく実行され、スレッド内の Qts イベントループが機能していることを確認しました。

また、このようにタイマーを設定しても違いはありません

timer->setSingleShot(true);
timer->setInterval(100);
timer->start();

秒数を 100000 または 0 に変更すると、アプリケーションを再起動すると残り時間が -1374002988 にわずかに変化しますが、長さは変わりません。

また、ライン上のデバッガーで確認したところtimer->remainingTime()、内部inter変数は正しく 100 に設定されています。

これはメモリアドレスかそのようなものでしょうか?

4

1 に答える 1