各位高手好,我现在遇到一个问题:我在一个窗口(mainwindow)里又开了一个新窗口(clock),这个新窗口受QT定时器控制不断显示当前时间,另外我还加了一条调试语句,让这个新窗口也同时向终端输出当前时间。我发现,在把这个新窗口关闭后,它怎么还在不断向终端输出时间?除非我把整个程序都关闭它才停下来,我想知道怎么才能把这个新窗口(和它的定时器)彻底关掉而不是非要把整个程序都关闭才行?
下面是我的代码:三个cpp文件(clock.cpp、mainwindow.cpp、main.cpp),两个头文件(mainwindow.h、clock.h):
clock.h:
#include<qapplication.h>
#include<qsound.h>
#include<qlabel.h>
#include<qdatetime.h>
#include<qstring.h>
#include<qnamespace.h>
#include<qfont.h>
#include<qtimer.h>
class Clock:public QWidget
{
Q_OBJECT
public:
Clock(QWidget *parent=0,const char *name=0);
public slots:
void rePaintTime();
private:
QTime nowTime;
QString time;
QLabel *label;
};
/*clock.cpp:*/
#include"clock.h"
#include <QPushButton>
#include <QHBoxLayout>
#include <QDialogButtonBox>
#include <QDebug>
Clock::Clock(QWidget *parent,const char *name)
{
label = new QLabel("",this); //定义一个标签
QPushButton *quitButton = new QPushButton(tr("&Quit"));
QDialogButtonBox *buttonBox = new QDialogButtonBox;
QHBoxLayout *hlayout = new QHBoxLayout;
buttonBox->addButton(quitButton,QDialogButtonBox::RejectRole);
hlayout->addWidget(buttonBox,0,0);
setLayout(hlayout);
QTimer *timer = new QTimer(this); //定义一个定时器
connect(timer,SIGNAL(timeout()),this,SLOT(rePaintTime()));//把时耗中断信号和获取时间函数连接
connect(quitButton,SIGNAL(clicked()),this,SLOT(close())); //关闭
label->resize(100,100); //定义标签的大小尺寸的
label->setFont(QFont("Times",18,QFont::Bold)); //设定标签显示字符串的格式为18号粗体
nowTime = QTime::currentTime(); //获取当前时间
time = nowTime.toString();//把时间转换为字符串格式
label->setText(time); //把字符串格式的时间显示在标签上
timer->start(1000); //每一秒读一次
}
//重新获取时间的函数 每一秒执行一次
void Clock::rePaintTime()
{
nowTime = QTime::currentTime(); //获取内核当前时间
time = nowTime.toString(); //转换时间格式为字符串格式
label->setText(time); //让标签显示字符串格式的时间
qDebug()<<time; //这条是我为了暴露出问题专门加的。
}
/*mainwindow.h*/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QtGui>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow();
private slots:
void startClock();
};
#endif
/*mainwindow.cpp*/
#include "clock.h"
#include "mainwindow.h"
MainWindow::MainWindow()
{
QWidget *window = new QWidget;
QPushButton *button1 = new QPushButton("&clock");
QHBoxLayout *hlayout = new QHBoxLayout;
hlayout->addWidget(button1);
connect(button1, SIGNAL(clicked()), this, SLOT(startClock()));
window->setLayout(hlayout);
window->show();
}
void MainWindow::startClock()
{
Clock *clocker = new Clock();
clocker->show();
}
/*main.cpp*/
#include"mainwindow.h"
int main(int argc,char **argv)
{
QApplication app(argc,argv);
MainWindow k;
k.show();
return app.exec();
}