Qt_log2000_定时器事件

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
访客追踪插件


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值