frei blau
frei blau

Reputation: 13

QTimer doesn't emit timeout signal

I'm rather new in QT. I'm trying to figure out how QTimer works. I want to print something each time it ticks. But I can't get it working.

testobj.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;
}

testobj.h:

#ifndef TESTOBJ
#define TESTOBJ

#include <QObject>

class TestObj: public QObject
{
    Q_OBJECT

public:
    TestObj();

public slots:
    void onTick();
};

#endif // TESTOBJ

mainwindow.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;
}

What am I doing wrong? It returns 1 (true) when i check with isActive. But it doesn't print anything at all.

Upvotes: 1

Views: 486

Answers (1)

TheDarkKnight
TheDarkKnight

Reputation: 27611

TestObj is being instantiated on the stack, not the heap, so it will go out of scope when the constructor is finished, which is before code execution gets round to processing events on the event queue.

Add a member variable to the MainWindow header: -

 TestObj* m_testObj;

Create the object in the MainWindow constructor: -

m_testObj = new TestObj;

Remember to delete the object in the destructor

delete m_testObj;

Upvotes: 4

Related Questions