gpt4 book ai didi

c++ - Qt C++ QTimer 不调用处理程序

转载 作者:太空宇宙 更新时间:2023-11-04 16:13:00 24 4
gpt4 key购买 nike

我的 Qt C++ 中的 QTimer 有问题,在我的代码中没有调用 timeoutHandler()。谁能告诉我为什么以及如何解决它?

测试.h

class Test : public QObject
{
Q_OBJECT
private:
static bool timeOuted;
public:
explicit Test(QObject *parent = 0);
virtual ~Test();
public slots:
static void handleTimeout();
};

测试.cpp

void Test::run()
{
QTimer::singleShot(3000, this, SLOT(handleTimeout()));
while(!timeOuted);
if(timeOuted)
{
timeOuted = false;
}
else
{
/* some work */
}
}

bool Test::timeOuted = false;

void Test::handleTimeout()
{
static int i = 0;
timeOuted = true;
qDebug() << "TimeOuted " << i++;
}

最佳答案

QTimer 需要 Qt 事件循环才能工作。当您进入 while(!timeOuted); 时,您会无休止地阻塞当前线程,并且 Qt 的事件循环没有机会采取任何操作(例如调用计时器的处理程序)。以下是您应该如何操作:

测试.h:

class Test : public QObject
{
Q_OBJECT
public:
explicit Test(QObject *parent = 0);
virtual ~Test();

void run(); // <-- you missed this
private slots: // <-- no need to make this slot public
void handleTimeout(); // <-- why would you make it static?!
};

测试.cpp:

void Test::run()
{
QTimer::singleShot(3000, this, SLOT(handleTimeout()));
}

void Test::handleTimeout()
{
static int i = 0;
qDebug() << "TimeOuted " << i++;

/* some work */
}

关于c++ - Qt C++ QTimer 不调用处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26141989/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com