[英]QTimer doesn't emit timeout signal
我在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
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;
}
我究竟做錯了什么? 當我用isActive檢查時它返回1(真)。 但它根本不打印任何東西。
TestObj正在堆棧上實例化,而不是堆,因此在構造函數完成時它將超出范圍,這是在代碼執行到處理事件隊列上的事件之前。
將成員變量添加到MainWindow標頭: -
TestObj* m_testObj;
在MainWindow構造函數中創建對象: -
m_testObj = new TestObj;
請記住刪除析構函數中的對象
delete m_testObj;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.