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;
}