Qt学习记录2
Qt; C++ 11; Qt定时器事件;
学习Qt将近2个月了,现在对学习所得进行记录。本文是log2000计划的一部分
实验环境:
Qt5.8.0 支持C++ 11
ubuntu 14.04 64bit
如果,我想要一个弹窗出现5s然后消失?
首先在Qt Creator中新建一个project,取默认的mainwindow类型
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
第一个方法:引入定时器事件
QTimerEvent
类
MainWindow带这个定时器功能
首先在mainwindow.h中写一个保护函数protected: void timerEvent(QTimerEvent *t);
然后选中它,右键 -> refactor(重构)-> 在mainwindow.cpp中添加定义
然后可以看到在mainWindow.cpp中自动生成了void MainWindow::timerEvent(QTimerEvent *t) { }
这时在构造函数中加入startTimer
ui(new Ui::MainWindow)//constructed function { ui->setupUi(this); startTimer(5000);//5s }
并在刚才自动生成的
timerEvent
中加入close
void MainWindow::timerEvent(QTimerEvent *t) { close(); }
可以看到,窗口在弹出5s后消失。
第二个方法:使用事件,写一个QTimer
在main.cpp中加入#include<QTime> #include<QTimer>
然后在main函数中
int main(int argc, char *argv[]) { QApplication a(argc, argv); QTimer * timer=new QTimer; MainWindow w; QObject::connect(timer,&QTimer::timeout,&w,&MainWindow::close); timer->start(5000); w.show(); int result=a.exec(); delete timer;//prevent memory leakage return result; //return a.exec();//main message loop }
可以运行。
如第一篇学习记录的思路,如果在函数中加入Timer而不是在main中?
#include "mainwindow.h" #include <QApplication> #include<QTime> #include<QTimer> MainWindow * f(){ QTimer t; MainWindow *w=new MainWindow; QObject::connect(&t,&QTimer::timeout,w,&MainWindow::close);//signal connect with mainwindow-close() w->show(); t.start(5000); //(*w).show();//is also ok return w; } int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow *m = f(); //return a.exec();//main message loop int result=a.exec(); delete m; return result; }
弹出的窗口并不会消失,这是因为QTimer的对象被释放了。
visitor tracker