1. 程式人生 > 實用技巧 >Qt_Demo3:實現棋盤

Qt_Demo3:實現棋盤

1 簡介

參考視訊:https://www.bilibili.com/video/BV1XW411x7NU?p=53

說明:實現一個8*8的棋盤,點選棋盤的任意位置顯示一個表情,並打印出當前的座標(相對棋盤)。介面如下:

2 實現過程

(1)畫棋盤的線

我們把當前視窗均分為10份,得到一個棋盤方格的橫縱線的大小,記為gridX,gridY,另外記橫軸起始座標為startX=gridX,縱軸起始座標為startY=gridY。

先畫出橫線,一共9條,第一條橫線的起始座標為(startX, startY),終點座標為(startX+8*gridX, startY);

第二條橫線的起始座標為(startX, startY+gridY),終點座標為(startX+8*gridX, startY+gridY);

以此類推,可得出全部的橫線的起始和終點座標。

同理,畫豎線也是一樣的道理:

第一條豎線的起始座標為(startX, startY),終點座標為(startX, startY+8*gridY);

第二條豎線的起始座標為(startX+gridX, startY),終點座標為(startX+gridX, startY+8*grid);

(2)畫棋子

我們先獲取當前座標,通過event->x(),event->y獲得;

接著需要判斷座標是否在棋盤範圍內:x >= startX && x <= startX+8*gridX&& y >= startY && y <= startX+8*gridY;

接著算出x和y的座標:chessX = (x - startX) / gridX; chessY = (y - startY) / gridY;

然後進行繪製:p.drawPixmap(startX+chessX*gridX, startY+chessY*gridY, gridX, gridY, QPixmap("../image/face.png"));

3 程式碼及測試

下面給出完整程式碼:

widget.cpp

 #include "widget.h"
#include "ui_widget.h"
#include <QPaintEvent>
#include <QMouseEvent>
#include <QPainter>
#include <QPen>
#include <QDebug> Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this); chessX = -;
chessY = -;
} Widget::~Widget()
{
delete ui;
} void Widget::paintEvent(QPaintEvent *event)
{
gridX = width()/;
gridY = height()/;
startX = gridX;
startY = gridY; QPainter p(this);
QPen pen;
pen.setWidth();
p.setPen(pen); //畫棋盤
for (int i = ; i <= ; i++) {
//畫橫線
p.drawLine(startX, startY+gridY*i, startX+*gridX, startY+gridY*i);
//畫豎線
p.drawLine(startX+i*gridX, startY, startX+i*gridX, startY+gridY*);
}
//畫棋子
if(chessX != - && chessY != -) {
p.drawPixmap(startX+chessX*gridX, startY+chessY*gridY, gridX, gridY, QPixmap("../image/face.png"));
} } void Widget::mousePressEvent(QMouseEvent *event)
{
//獲取點選的座標
int x = event->x();
int y = event->y();
// 要保證點選點在棋盤範圍裡面
if(x >= startX && x <= startX+*gridX
&& y >= startY && y <= startX+*gridY) {
// 棋盤的位置轉換轉換為座標下標值
// 類似於a[i][j]的i和j
chessX = (x - startX) / gridX;
chessY = (y - startY) / gridY;
qDebug() << chessX << chessY;
//更新視窗,間接呼叫paintEvent()
update();
}
}

widget.h

 #ifndef WIDGET_H
#define WIDGET_H #include <QWidget> namespace Ui {
class Widget;
} class Widget : public QWidget
{
Q_OBJECT public:
explicit Widget(QWidget *parent = );
~Widget(); void paintEvent(QPaintEvent *event);
void mousePressEvent(QMouseEvent *event); private:
Ui::Widget *ui; int startX;
int startY;
int gridX;
int gridY;
int chessX;
int chessY; }; #endif // WIDGET_H

執行測試:

注意看左下角列印的座標,就是我們當前棋子所在棋盤的座標。