【问题标题】:QTimer doesn't emit timeout signalQTimer 不发出超时信号
【发布时间】:2015-12-09 22:20:43
【问题描述】:

我是 QT 的新手。我试图弄清楚 QTimer 是如何工作的。我想在每次打勾时打印一些东西。但我无法让它工作。

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

主窗口.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(真)。但它根本不打印任何东西。

【问题讨论】:

    标签: c++ qt


    【解决方案1】:

    TestObj 是在堆栈而不是堆上实例化的,因此当构造函数完成时,它将超出范围,这是在代码执行轮到处理事件队列上的事件之前。

    在 MainWindow 标头中添加一个成员变量:-

     TestObj* m_testObj;
    

    在 MainWindow 构造函数中创建对象:-

    m_testObj = new TestObj;
    

    记得在析构函数中删除对象

    delete m_testObj;
    

    【讨论】:

    • 另外,(如果我没记错的话)它需要在对象树上,否则它不会触发。所以TestObj 需要以某种方式成为MainWindow 的父级(通过构造函数参数,或通过调用setParent),否则timerEvent 不会被触发。
    • @phyatt,我不认为这是正确的。只要对象派生自 QObject 并包含 Q_OBJECT 宏,就可以了。
    • QTimer 不需要父母。不过,它可以避免在 dtor 中删除。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多