Skip to content

Commit

Permalink
add option to disable focus
Browse files Browse the repository at this point in the history
  • Loading branch information
GoodCoder666 committed Dec 21, 2024
1 parent ff8fcbb commit c14f198
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
16 changes: 13 additions & 3 deletions src/mapWidget/mapWidget.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
#include <QMouseEvent>
#include <QKeyEvent>

MapWidget::MapWidget(QWidget* parent, int w, int h) :
MapWidget::MapWidget(QWidget* parent, int w, int h, bool focusEnabled) :
QWidget(parent), scale(1.0), offset(0, 0), mouseDown(false), isDragging(false), width(w), height(h), focusX(-1), focusY(-1) {
setMouseTracking(true);
setFocusPolicy(Qt::StrongFocus);
setFocusEnabled(focusEnabled);
}

MapWidget::~MapWidget() {
Expand Down Expand Up @@ -110,7 +110,7 @@ void MapWidget::mouseReleaseEvent(QMouseEvent* event) {
if(isDragging) {
isDragging = false;
setCursor(Qt::ArrowCursor);
} else {
} else if(focusPolicy() != Qt::NoFocus) {
QPoint gridPos = mapToGrid(event->pos());
if(gridPos.x() >= 0 && gridPos.x() < width && gridPos.y() >= 0 && gridPos.y() < height) {
focusX = gridPos.x();
Expand All @@ -130,6 +130,16 @@ QPoint MapWidget::mapToGrid(const QPoint& pos) {
return QPoint(gridX, gridY);
}

void MapWidget::setFocusEnabled(bool enabled) {
if(enabled) {
setFocusPolicy(Qt::StrongFocus);
} else {
setFocusPolicy(Qt::NoFocus);
focusX = focusY = -1;
update();
}
}

void MapWidget::keyPressEvent(QKeyEvent* event) {
if(focusX != -1 && focusY != -1) {
switch(event->key()) {
Expand Down
3 changes: 2 additions & 1 deletion src/mapWidget/mapWidget.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ class MapWidget : public QWidget {
Q_OBJECT

public:
explicit MapWidget(QWidget* parent, int w, int h);
explicit MapWidget(QWidget* parent, int w, int h, bool focusEnabled = true);
~MapWidget();
const int width, height;
void setFocusEnabled(bool enabled);

protected:
void paintEvent(QPaintEvent* event) override;
Expand Down

0 comments on commit c14f198

Please sign in to comment.