10.9 Qt事件处理机制

时间:2024-10-10 08:43:01

键盘按键调整label移动

#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QKeyEvent>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);


}

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

void Widget::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
    case 'W':
    case 'w':
    {
        if(ui->label->y()<=-ui->label->height())
        {
            ui->label->move(ui->label->x(),this->height());
        }
        ui->label->move(ui->label->x(),ui->label->y()-5);
        break;
    }


    case 'A':
    case 'a':
    {
        if(ui->label->x()<=-ui->label->width())
        {
            ui->label->move(this->width(),ui->label->y());
        }
        ui->label->move(ui->label->x()-5,ui->label->y());
        break;
    }

    case 'S':
    case 's':
    {
        if(ui->label->y()>=this->height())
        {
            ui->label->move(ui->label->x(),-ui->label->height());
        }
        ui->label->move(ui->label->x(),ui->label->y()+5);
        break;
    }



    case 'D':
    case 'd':

    {
        if(ui->label->x()>=this->width())
        {
            ui->label->move(-ui->label->width(),ui->label->y());
        }
        ui->label->move(ui->label->x()+5,ui->label->y());
        break;
    }
    }
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    qDebug()<<QPoint(event->x(),event->y());
}

void Widget::mousePressEvent(QMouseEvent *event)
{
    if(event->button()==Qt::LeftButton)
    {
        qDebug()<<"鼠标左键按下";
    }
}



鼠标拖动窗口

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    this->setWindowFlag(Qt::FramelessWindowHint);
}

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

void Widget::mousePressEvent(QMouseEvent *event)
{
    temp=event->globalPos()-this->pos();
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons()==Qt::LeftButton)
    {
        this->move(event->globalPos()-temp);
    }
}