简体   繁体   中英

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM