主要功能:
《1》使用绘图事件处理函数,在界面上绘制一个圆
《2》按下鼠标左键+鼠标移动,实现圆的拖拽效果。
《3》使用键盘输入事件处理函数,对圆进行上下左右移动!
《4》 鼠标滑轮事件,对圆进行放大与缩小!!!!
Widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPainter>
#include <QMouseEvent>
#include <QWheelEvent>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void paintEvent(QPaintEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void keyPressEvent(QKeyEvent *event);
void wheelEvent(QWheelEvent *event);
private:
Ui::Widget *ui;
int x; //圆x坐标
int y;
int rad; //半径
bool isDragging; //标识滚轮
};
#endif // WIDGET_H
Widget.c
#include "widget.h"
#include "ui_widget.h"
#include <iostream>
#include <math.h>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
x = 100;
y = 100;
rad = 50;
isDragging = false;
}
Widget::~Widget()
{
delete ui;
}
//画圆
void Widget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
QPen pen;
pen.setColor(QColor(Qt::red));
pen.setWidth(5);
painter.setPen(pen);
painter.drawEllipse(QPoint(x, y), rad, rad);
}
//鼠标左键
void Widget::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
int distance = std::sqrt((event->x() - x) * (event->x() - x) + (event->y() - y) * (event->y() - y));
if(distance < rad)
{
isDragging = true;
}
}
}
//左键释放
void Widget::mouseReleaseEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
isDragging = false;
}
}
//鼠标移动
void Widget::mouseMoveEvent(QMouseEvent *event)
{
if(isDragging)
{
x = event->x();
y = event->y();
update();
}
}
//键盘控制
void Widget::keyPressEvent(QKeyEvent *event)
{
int move = 5; //移动步长
if(event->key() == Qt::Key_Up)
{
y -= move;
}
else if(event->key() == Qt::Key_Down)
{
y += move;
}
if(event->key() == Qt::Key_Left)
{
x -= move;
}
if(event->key() == Qt::Key_Right)
{
x += move;
}
update();
}
//滚轮
void Widget::wheelEvent(QWheelEvent *event)
{
double bili = 1.5; //放缩比例
if(event->angleDelta().y() > 0)
{
rad = rad *bili;
}
else if(event->angleDelta().y() < 0)
{
rad = rad / bili;
}
update();
}
可用于Qt事件学习后的一个小练习,还是蛮有意思的