【问题标题】:Qtimer iterationsQtimer 迭代次数
【发布时间】:2017-01-09 01:26:20
【问题描述】:

也许我想多了,但在迭代和 qtimer 方面需要一些帮助。我有以下 QTimer 代码和函数(我已尽量简化它,如果某些语法错误,请见谅):

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(whateverfunction()));
    timer -> start();

void MainWindow::whateverfunction()
{
checksomething();
if (checksomething() == 1)
{
dosomething1(); //function I want to run ONLY the first time checksomething() = 1
dosomething2(); //function I want to run the second,third,fourth,etc. time checksomething() = 1
}
else
{
donothing(); //if this function is run the count resets, meaning dosomething1() should be run again if checksomething() == 1 again-- but only the first time.
}
}

我怎样才能完成上述任务?我曾尝试引入一个控制变量,但每次通过 QTimer 运行此函数时,它都会重置。谢谢!

【问题讨论】:

  • 使控制变量成为MainWindow 的私有成员,而不是whateverfunction 中的自动变量。

标签: c++ qt


【解决方案1】:

我建议使用 std::call_once 来结束对 dosomething1() 的调用

std::once_flag flag;

void MainWindow::whateverfunction()
{
checksomething();
if (checksomething() == 1)
{
    std::call_once(flag, [this](){
        dosomething1();
    };
    dosomething2();
}
}

【讨论】:

    猜你喜欢
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多