问题描述
在 Qt 中,我试图设置一个 QTimer
每秒调用一个名为更新"的函数.这是我的 .cpp 文件:
In Qt I'm trying to set a QTimer
that calls a function called "update" every second. Here is my .cpp file:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTimer>
#include "QDebug"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(1000);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::update()
{
qDebug() << "update";
}
和主要:
#include <QtGui/QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
项目正在构建,但它不执行更新,因为更新"行没有显示在任何地方...有人看到我做错了什么吗?
The project is being build, but it doesn't execute update, since the line "update" is not showing anywhere... Does anybody see what I´m doing wrong?
推荐答案
最好让
QTimer
的父级使用 Qt 的内存管理系统.
It's good practice to give a parent to your
QTimer
to use Qt's memory management system.
update()
是一个 QWidget 函数 - 这是您要调用的函数吗?http://qt-project.org/doc/qt-4.8/qwidget.html#更新.
update()
is a QWidget function - is that what you are trying to call or not? http://qt-project.org/doc/qt-4.8/qwidget.html#update.
如果数字 2 不适用,请确保您尝试触发的函数在标头中声明为插槽.
If number 2 does not apply, make sure that the function you are trying to trigger is declared as a slot in the header.
最后,如果这些都不是您的问题,那么了解您是否遇到任何运行时连接错误会很有帮助.
Finally if none of these are your issue, it would be helpful to know if you are getting any run-time connect errors.
这篇关于如何使用 QTimer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!