我是 QT 的新手。我想弄清楚 QTimer 是如何工作的。我想在每次滴答时打印一些东西。但我无法让它工作。
测试对象.cpp:
#include "testobj.h"
#include <QTimer>
#include <iostream>
using namespace std;
TestObj::TestObj()
{
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(onTick()));
timer->start(100);
cout << "Timer started" << endl;
}
void TestObj::onTick()
{
cout << "test" << endl;
}
测试对象.h:
#ifndef TESTOBJ
#define TESTOBJ
#include <QObject>
class TestObj: public QObject
{
Q_OBJECT
public:
TestObj();
public slots:
void onTick();
};
#endif // TESTOBJ
主窗口.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "testobj.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
TestObj obj;
}
MainWindow::~MainWindow()
{
delete ui;
}
我做错了什么?当我检查 isActive 时它返回 1 (true)。但它根本不打印任何内容。
最佳答案
TestObj 在栈上而不是堆上被实例化,所以当构造函数完成时它会超出范围,这是在代码执行轮到处理事件队列上的事件之前。
在MainWindow header中添加一个成员变量:-
TestObj* m_testObj;
在 MainWindow 构造函数中创建对象:-
m_testObj = new TestObj;
记得在析构函数中删除对象
delete m_testObj;
关于c++ - QTimer 不发出超时信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34181022/