首页 > 编程语言 >C++系列三:QT-事件处理

C++系列三:QT-事件处理

时间:2023-09-12 21:11:37浏览次数:55  
标签:事件处理 Qt pt void C++ 事件 Key event QT

目录

介绍:

  1. GUI应用程序是由事件(event)驱动的,点击鼠标,按下按键,窗口大小改变等等
  2. 按事件的来源,可以将事件划分为3类:
    自生事件(spontaneous event):由窗口系统产生,如:QKeyEvent、QMouseEvent。自生事件会进入系统队列,等待事件循环的处理。
    发布事件(posted event):是由Qt应用程序产生,如:QTimerEvent。使用QCoreApplication::postEvent()产生发布事件,等待事件循环的处理。
    发送事件(sent event):有QT或其他程序定向发送的事件。使用QCoreApplication::sendEvent()产生发送事件,有对象的event()函数直接处理。
  3. Qt的主事件循环(QCoreApplication::exec())从事件队列中获取原生的系统事件,将它们转换为QEvent,并将转换后的事件发送给QObject。任何QObject派生的类都可以处理事件

来源参考:

  1. 阿西拜编程:https://www.bilibili.com/video/BV1km4y1k7CW/
  2. 流程:https://zhuanlan.zhihu.com/p/638582691
  3. Widget:https://doc.qt.io/qt-6/qwidget.html#protected-slots

事件类:

rect():返回需要绘制的区域的矩形范围;
region():返回需要绘制的区域的 QRegion 对象;
isAccepted():返回一个布尔值,表示是否接受该事件;
accept():标记该事件为已接受,阻止事件进一步传递;
ignore():忽略该事件,允许事件继续传递。

案例1:

protected:
virtual void closeEvent(QCloseEvent *event) override;//窗口关闭时
virtual void paintEvent(QPaintEvent *event) override;//用于触发绘图操作
virtual void keyPressEvent(QKeyEvent *event) override;//键盘点击
virtual void mousePressEvent(QMouseEvent *event) override;//鼠标点击
void Widget::mousePressEvent(QMouseEvent *event)
{
    if(event->button()!=Qt::LeftButton)
        return;
    QPoint pt=event->pos();//相对widget的位置
    QPointF relaPt=event->position();
    QPointF winPt=event->scenePosition();
    QPointF globPt=event->globalPosition();//相对屏幕的绝对位置
    QString str=QString::asprintf("pos()=(%d,%d)",pt.x(),pt.y());
    str+=QString::asprintf("\nposition()=(%.0f,%.0f)",relaPt.x(),relaPt.y());
    str+=QString::asprintf("\nscenePosition()=(%.0f,%.0f)",winPt.x(),winPt.y());
    str+=QString::asprintf("\nglobalPos()=(%.0f,%.0f)",globPt.x(),globPt.y());

    ui->labMove->setText(str);
    ui->labMove->adjustSize();
    ui->labMove->move(event->pos());
    QWidget::mousePressEvent(event);
}
void Widget::keyPressEvent(QKeyEvent *event)
{
    QPoint pt=ui->btnMove->pos();
    if((event->key()==Qt::Key_A)||(event->key()==Qt::Key_Left))
        ui->btnMove->move(pt.x()-20,pt.y());

    if((event->key()==Qt::Key_D)||(event->key()==Qt::Key_Right))
        ui->btnMove->move(pt.x()+20,pt.y());

    if((event->key()==Qt::Key_W)||(event->key()==Qt::Key_Up))
        ui->btnMove->move(pt.x(),pt.y()-20);

    if((event->key()==Qt::Key_S)||(event->key()==Qt::Key_Down))
        ui->btnMove->move(pt.x(),pt.y()+20);

    QWidget::keyPressEvent(event);
}
void Widget::paintEvent(QPaintEvent *event)//背景加载
{
    Q_UNUSED(event);
    QPainter painter(this);
    painter.drawPixmap(0,0,width(),this->height(),
                       QPixmap(":/pics/images/background.jpg"));
}
void Widget::closeEvent(QCloseEvent *event)
{
    QMessageBox::StandardButton result=QMessageBox::question(
                this,"消息框","确定要退出吗?",
                QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel);

    if(result==QMessageBox::Yes)
        event->accept();
    else
        event->ignore();
}



案例2:
//MyButton.h:
#include <QPushButton>  
#include <QMouseEvent>  

class MyButton : public QPushButton
{
    Q_OBJECT

public:
    explicit MyButton(QWidget* parent = nullptr) : QPushButton(parent) {}

protected:
    void mousePressEvent(QMouseEvent* event) override
    {
        if (event->button() == Qt::LeftButton) {
            // 处理鼠标左键点击事件  
            qDebug() << "LeftButton clicked";
        }
        else if (event->button() == Qt::RightButton) {
            // 处理鼠标右键点击事件  
            qDebug() << "RightButton clicked";
        }
    }
};

//MainWindown.cpp:
QVBoxLayout* vlay = new QVBoxLayout();
QPushButton* btn = new QPushButton("demo",this);
MyButton* btn1 = new MyButton(this);
btn1->setText("demo2");

vlay->addWidget(btn);
vlay->addWidget(btn1);
this->setLayout(vlay);

connect(btn, &QPushButton::clicked, []() {
    qDebug("demo1111");
    });

标签:事件处理,Qt,pt,void,C++,事件,Key,event,QT
From: https://www.cnblogs.com/zhouyitty/p/17697824.html

相关文章

  • Qt 中使用mplayer播放音乐不能是中文歌名
    错误代码:Qt中Filenotfound:'./music/��ͤ��.mp3'如果在Qt中无法正确识别包含中文字符的文件名,可能是因为默认的文件编码不支持中文字符解决方案:本人前两种方案均不可解决问题,方案三解决问题。方案1:使用Unicode路径:将文件路径从字符串字面值转换为Unicode字符。例如,使用QSt......
  • QTableView部分基本使用、与数据库搭建
    创建一个QSqlTableModel来管理数据库表格的数据,可以在后续步骤中使用这个模型来与表格内容进行交互。QSqlTableModel*model=newQSqlTableModel;model->setTable("your_table_name");//设置表格名称model->select();//从数据库中选择数据设置QTableView模型:将QSqlTableMo......
  • 纯C++代码理解Qt中的信号和槽函数
    槽函数的调用是一个多步骤的过程:1.连接(Connect)首先,通过使用QObject::connect()函数来建立信号和槽之间的连接。QObject::connect(sender,SIGNAL(signalName(args)),receiver,SLOT(slotName(args)));这里的sender和receiver是QObject派生的对象,而signalName和slotName则分......
  • 三分钟读完《Essential C++》
    #include<iostream>#include<string>#include<vector>#include<memory>#include<algorithm>#include<mutex>#include<condition_variable>#include<atomic>#include<tuple>#include<map>#in......
  • bilibili B站:makefile 编译Linux C/C++项目快速入门
    视频摘自:https://www.bilibili.com/video/BV1vg41177zT    ......
  • C++模板介绍
    C++模板C++模板是一种强大的泛型编程工具,它允许我们编写通用的代码,可以用于处理多种不同的数据类型。模板允许我们在编写代码时将类型作为参数进行参数化,从而实现代码的重用性和灵活性。在C++中,模板由关键字template开始,并且后面跟着模板参数列表。模板参数可以是类型参数......
  • 教你2种方法,将iOS设备通过MQTT协议连接到华为云物联网平台
    本文分享自华为云社区《如何将iOS设备通过MQTT协议连接到华为云物联网平台:Flutter和Swift两种方法》,作者:张俭。前言当今时代,物联网技术正逐步改变我们的生活和工作方式。华为云IoTDA服务,为开发者提供了一个开放、稳定、可靠的基础设施,以便实现设备与云端的无缝连接和双向通......
  • c++高精度模板
    #include<iostream>#include<stdio.h>#include<string.h>#include<math.h>#include<algorithm>#include<string>#include<vector>#include<list>usingnamespacestd;constintmaxn......
  • RK3568开发笔记(八):开发板烧写buildroot固件(支持hdmi屏),搭建Qt交叉编译开发环境,编译一个D
    前言  前面发现开发板用ubuntu固件发现空间不够,本篇使用buildroot固件,来实现目标板运行qt界面应用。<br>烧写buildroot固件  这部分更详细的参照《RK3568开发笔记(六):开发板烧写ubuntu固件(支持mipi屏)》的步骤,本质上烧写都是一样的,只是不同的update.img。步骤一:下载镜像  ......
  • RK3568开发笔记(八):开发板烧写buildroot固件(支持hdmi屏),搭建Qt交叉编译开发环境,编译一个D
    前言  前面发现开发板用ubuntu固件发现空间不够,本篇使用buildroot固件,来实现目标板运行qt界面应用。 烧写buildroot固件  这部分更详细的参照《RK3568开发笔记(六):开发板烧写ubuntu固件(支持mipi屏)》的步骤,本质上烧写都是一样的,只是不同的update.img。步骤一:下载......