Qt:键盘事件、定时器事件、关闭事件

1.鼠标事件,在终端输出键盘按下键
2.计时器事件,在exe文件上输出计时

目录:
在这里插入图片描述

mywidget.h

#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>

namespace Ui {
class MyWidget;
}

class MyWidget : public QWidget
{
    Q_OBJECT

public:
    explicit MyWidget(QWidget *parent = 0);
    ~MyWidget();
    //定时器id
    int timeId;
    int timeId2;
protected:
    //键盘按下事件
    void keyPressEvent(QKeyEvent *);
    //计时器事件
    void timerEvent(QTimerEvent *);

private:
    Ui::MyWidget *ui;
};

#endif // MYWIDGET_H

mywidget.cpp

#include "mywidget.h"
#include "ui_mywidget.h"
#include <QKeyEvent>
#include <QTimerEvent>
#include <QDebug>
MyWidget::MyWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MyWidget)
{
    ui->setupUi(this);
    this->timeId=this->startTimer(1000);//以毫秒为单位,每个1s触发一次
    this->timeId2=this->startTimer(500);//每个0.5s触发一次
}

//键盘事件,在终端输出键盘按下键
void MyWidget::keyPressEvent(QKeyEvent *e){
   qDebug()<< static_cast<char>(e->key());
}

//计时器事件,在exe文件上输出计时
void MyWidget::timerEvent(QTimerEvent *e){
    static int second=0;
    if(this->timeId==e->timerId()){
        ui->label->setText(QString("<center><h1>time1:%1</h1></center>").arg(second++));
//        if(second==5)//在5s时,停止计时
//            this->killTimer(timeId);
    }
    else if(this->timeId2==e->timerId()){
        ui->label_2->setText(QString("<center><h1>time2:%1</h1></center>").arg(second++));
//        if(second==5)//在5s时,停止计时
//            this->killTimer(timeId);
    }
}

MyWidget::~MyWidget()
{
    delete ui;
}

效果:
在这里插入图片描述
在这里插入图片描述
3.关闭事件,点击右上角关闭,弹出对话框(是否关闭)
在这里插入图片描述
mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
protected:
    //关闭事件
    void closeEvent(QCloseEvent *);

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtSerialPort/QSerialPort>
#include <QDebug>
#include <QMessageBox>//(对话框)你确定关闭吗?
#include <QCloseEvent>//关闭事件

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}
//关闭事件
void MainWindow::closeEvent(QCloseEvent *e){
    int ret=QMessageBox::question(this,"question","真的关闭吗?!(0.0)");
    if(ret==QMessageBox::Yes){
        //关闭窗口
        //处理关闭窗口事件,接受事件,事件就不会往下再传递
        e->accept();
    }else{
        //不关闭窗口
        //忽略事件,事件继续给 父组件 传递
        e->ignore();
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值