自学内容网 自学内容网

Qt键盘按下事件和定时器事件及事件的接收和忽略

定时器事件

//设置多少毫秒调用一次 1s=1000
timerId = this->startTimer(1000);

timerId2 = this->startTimer(500);
void MyWidget::timerEvent(QTimerEvent* t)
{
static int sec = 0;
//通过判断当前ID来实现不同定时器的调用时间
if(t->timerId() == this->timerId){

//隔一秒调用
QString text = QString("<center><h1>time out:%1</center></h1>").arg(sec++);
//鼠标进入事件时这个需要注销否则进入提示会被覆盖
//this->setText(text);
ui.label->setText(text);

if (sec == 5) {
//停止闹钟
this->killTimer(timerId);
}

}else if(t->timerId() == this->timerId2){
//隔0.5秒调用
QString text = QString("<center><h1>time out:%1</center></h1>").arg(sec++);
ui.label_2->setText(text);

if (sec == 30) {
//停止闹钟
this->killTimer(timerId2);
}
}
}

在这里插入图片描述

键盘按下事件

void MyWidget::keyPressEvent(QKeyEvent *e)
{
//打印的是ASCII
//qDebug() << e->key();
//这样是正常的
qDebug() << (char)e->key();
}

在这里插入图片描述
左键按下按钮由当前类处理,右键按下事件交给父组件处理
在这里插入图片描述
全部代码
MyButton

#include "MyButton.h"

MyButton::MyButton(QWidget *parent)
: QPushButton(parent)
{}

MyButton::~MyButton()
{}

void MyButton::mousePressEvent(QMouseEvent * ev)
{
//如果是左键按下,接收了按下事件,就不会往下传就不好触发mywidget的cliked信号
if (ev->button() == Qt::LeftButton) {
qDebug() << "按钮被左键按下";
//事件接收后就会往下传递
// 一般在closeevent关闭事件使用
//ev->ignore();//忽略,事件继续往下传递,传递给父组件,比如这个类在mywidget的pushbutton提升,mywidget就是父组件

}
else
{
//如果是右键按下不做处理
QPushButton::mousePressEvent(ev);
//事件的忽略,事件继续往下传递
}
//往下传递而触发父类发射cliked信号触发mywidget连接槽函数
//QPushButton::mousePressEvent(ev);
}

MyWidget

#pragma execution_character_set("utf-8")
#include "MyWidget.h"
#include <qdebug.h>

MyWidget::MyWidget(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
//设置多少毫秒调用一次 1s=1000
timerId = this->startTimer(1000);

timerId2 = this->startTimer(500);

connect(ui.pushButton,&QPushButton::clicked,
[=]() {
qDebug() << "按钮被按下";
}
);
}

MyWidget::~MyWidget()
{}

void MyWidget::keyPressEvent(QKeyEvent *e)
{
//打印的是ASCII
//qDebug() << e->key();
//这样是正常的
qDebug() << (char)e->key();
}

void MyWidget::timerEvent(QTimerEvent* t)
{
static int sec = 0;
//通过判断当前ID来实现不同定时器的调用时间
if(t->timerId() == this->timerId){

//隔一秒调用
QString text = QString("<center><h1>time out:%1</center></h1>").arg(sec++);
//鼠标进入事件时这个需要注销否则进入提示会被覆盖
//this->setText(text);
ui.label->setText(text);

if (sec == 5) {
//停止闹钟
this->killTimer(timerId);
}

}else if(t->timerId() == this->timerId2){
//隔0.5秒调用
QString text = QString("<center><h1>time out:%1</center></h1>").arg(sec++);
ui.label_2->setText(text);

if (sec == 30) {
//停止闹钟
this->killTimer(timerId2);
}
}

}

void MyWidget::mousePressEvent(QMouseEvent* ev)
{
qDebug() <<"MyWidget::mousePressEvent被触发";
}

//关闭事件
void MyWidget::closeEvent(QCloseEvent* ev)
{
int ret = QMessageBox::question(this,"question","是否关闭窗口");
if (ret == QMessageBox::Yes) {
//关闭窗口
//处理关闭窗口事件,接收事件,事件就不会在往下传递
ev->accept();
}
else
{
//不关闭窗口
//忽略事件,事件继续给父组件传递
ev->ignore();
}
}

在这里插入图片描述
在这里插入图片描述


原文地址:https://blog.csdn.net/weixin_74239923/article/details/143083750

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!