定时器事件
//设置多少毫秒调用一次 1s=1000timerId = 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=1000timerId = 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();}
}