void MainWindow::mousePressEvent(QMouseEvent* event)//鼠標設置障礙物起始,終點 { if(event->button()==Qt::LeftButton&&mode==0)//障礙物 { int j=(event->y()-50)/25-1,i=(event->x()-200)/25; _MAP[i][j]=!_MAP[i][j]; update(); },將鼠標點擊變爲框選完整代碼
时间: 2024-03-17 13:40:51 浏览: 65
完整代码如下:
```cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMouseEvent>
#include <QPainter>
const int MAP_WIDTH = 20;
const int MAP_HEIGHT = 20;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
setFixedSize(600, 600);
setWindowTitle("A* Path Finding");
mode = 0;
isSelecting = false;
memset(_MAP, 0, sizeof(_MAP));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::mousePressEvent(QMouseEvent* event)
{
if (event->button() == Qt::LeftButton && mode == 0)
{
int j = (event->y() - 50) / 25 - 1;
int i = (event->x() - 200) / 25;
// 判断鼠标是否在地图区域内
if (i >= 0 && i < MAP_WIDTH && j >= 0 && j < MAP_HEIGHT)
{
// 记录下鼠标的起点,并将 isSelecting 标记为 true
startPoint = endPoint = QPoint(i, j);
isSelecting = true;
update();
}
}
}
void MainWindow::mouseMoveEvent(QMouseEvent* event)
{
if (isSelecting)
{
int j = (event->y() - 50) / 25 - 1;
int i = (event->x() - 200) / 25;
// 判断鼠标是否在地图区域内
if (i >= 0 && i < MAP_WIDTH && j >= 0 && j < MAP_HEIGHT)
{
// 记录下鼠标的终点,并调用 update 函数进行界面更新
endPoint = QPoint(i, j);
update();
}
}
}
void MainWindow::mouseReleaseEvent(QMouseEvent* event)
{
if (event->button() == Qt::LeftButton && mode == 0 && isSelecting)
{
// 标记为框选结束
isSelecting = false;
// 获取框选的矩形
int left = qMin(startPoint.x(), endPoint.x());
int top = qMin(startPoint.y(), endPoint.y());
int right = qMax(startPoint.x(), endPoint.x());
int bottom = qMax(startPoint.y(), endPoint.y());
// 将框选的矩形内的格子设置为障碍物
for (int i = left; i <= right; i++)
{
for (int j = top; j <= bottom; j++)
{
if (i >= 0 && i < MAP_WIDTH && j >= 0 && j < MAP_HEIGHT)
{
_MAP[i][j] = true;
}
}
}
update();
}
}
void MainWindow::paintEvent(QPaintEvent* event)
{
QPainter painter(this);
// 绘制地图
painter.setPen(Qt::black);
painter.setBrush(Qt::white);
for (int i = 0; i < MAP_WIDTH; i++)
{
for (int j = 0; j < MAP_HEIGHT; j++)
{
if (_MAP[i][j])
{
painter.fillRect(QRect(i * 25 + 200, j * 25 + 50, 25, 25), Qt::black);
}
else
{
painter.drawRect(QRect(i * 25 + 200, j * 25 + 50, 25, 25));
}
}
}
// 绘制框选的矩形
if (isSelecting)
{
painter.setPen(Qt::red);
painter.setBrush(Qt::NoBrush);
painter.drawRect(QRect(startPoint, endPoint));
}
}
```
这个代码实现了在地图上鼠标框选多个格子,并将其设置为障碍物的功能。你可以在窗口中按下鼠标左键并拖动鼠标来进行框选。
阅读全文