我在Qt C++中遇到QTimer问题,在我的代码中没有调用timeoutHandler().谁能告诉我为什么以及如何解决它?
Test.h
class Test : public QObject
{
Q_OBJECT
private:
static bool timeOuted;
public:
explicit Test(QObject *parent = 0);
virtual ~Test();
public slots:
static void handleTimeout();
};
Run Code Online (Sandbox Code Playgroud)
TEST.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++;
}
Run Code Online (Sandbox Code Playgroud)
QTimer需要Qt事件循环才能工作.当你进入时while(!timeOuted);,你无休止地阻止当前线程,Qt的事件循环没有机会采取任何行动(比如为计时器调用你的处理程序).这是你应该怎么做的:
Test.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?!
};
Run Code Online (Sandbox Code Playgroud)
TEST.CPP:
void Test::run()
{
QTimer::singleShot(3000, this, SLOT(handleTimeout()));
}
void Test::handleTimeout()
{
static int i = 0;
qDebug() << "TimeOuted " << i++;
/* some work */
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1017 次 |
| 最近记录: |