简体   繁体   English

QTimer不发出超时信号

[英]QTimer doesn't emit timeout signal

I'm rather new in QT. 我在QT比较新。 I'm trying to figure out how QTimer works. 我想弄清楚QTimer是如何工作的。 I want to print something each time it ticks. 我想在每次打字时打印一些东西。 But I can't get it working. 但我无法让它发挥作用。

testobj.cpp: 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: testobj.h:

#ifndef TESTOBJ
#define TESTOBJ

#include <QObject>

class TestObj: public QObject
{
    Q_OBJECT

public:
    TestObj();

public slots:
    void onTick();
};

#endif // TESTOBJ

mainwindow.cpp: 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. 当我用isActive检查时它返回1(真)。 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. TestObj正在堆栈上实例化,而不是堆,因此在构造函数完成时它将超出范围,这是在代码执行到处理事件队列上的事件之前。

Add a member variable to the MainWindow header: - 将成员变量添加到MainWindow标头: -

 TestObj* m_testObj;

Create the object in the MainWindow constructor: - 在MainWindow构造函数中创建对象: -

m_testObj = new TestObj;

Remember to delete the object in the destructor 请记住删除析构函数中的对象

delete m_testObj;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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