完成了五子棋的界面的绘制,写个博客总结一下收获。
其实也就四步。
除了第四步里,获取鼠标位置有个坑,其他都没什么难度。
这个坑也就是获取鼠标位置时,发现mouseMoveEvent并没有响应
原来MouseMoveEvent为了不太耗资源在默认状态下是要鼠标按下才能捕捉到。要想鼠标不按下时的移动也能捕捉到,需要setMouseTracking(true);
QWidget中直接setMouseTracking(true);即可。
但若是在QMainWindow,需再多加一句
ui->centralWidget->setMouseTracking(true);
setMouseTracking(true);
ui->centralWidget->setMouseTracking(true);
其他的代码里注释都解释清楚了,就不多说了。
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setFixedSize(750,750);//设置窗口大小
setWindowTitle("五子棋");
}
void MainWindow::paintEvent(QPaintEvent* event)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true); //抗锯齿
//画背景色
QPalette palette ;
palette.setColor(QPalette::Background,QColor("#B1723C"));
this->setAutoFillBackground(true);
this->setPalette(palette);
//画棋盘线条
painter.setPen(QPen(Qt::Black,1,Qt::SolidLine));
for (int i = 0; i < BoardLength; i++)
{
painter.drawLine(BoardMargin+BoardOneSize*i, BoardMargin, BoardMargin+BoardOneSize*i, BoardMargin+(BoardLength-1)*BoardOneSize);
painter.drawLine(BoardMargin, BoardMargin+BoardOneSize*i, BoardMargin+(BoardLength-1)*BoardOneSize, BoardMargin+BoardOneSize*i);
}
//画棋盘里的五个小黑点
painter.setBrush(QBrush(Qt::black,Qt::SolidPattern));
painter.drawRect(BoardMargin+3*BoardOneSize-5,BoardMargin+3*BoardOneSize-5,10,10);
painter.drawRect(BoardMargin+11*BoardOneSize-5,BoardMargin+3*BoardOneSize-5,10,10);
painter.drawRect(BoardMargin+11*BoardOneSize-5,BoardMargin+11*BoardOneSize-5,10,10);
painter.drawRect(BoardMargin+3*BoardOneSize-5,BoardMargin+11*BoardOneSize-5,10,10);
painter.drawRect(BoardMargin+7*BoardOneSize-5,BoardMargin+7*BoardOneSize-5,10,10);
//画棋子
QBrush brush; //设置画刷
painter.setPen(Qt::NoPen); //去掉pen,避免画出的棋子边缘带线条
for (int i = 0; i < BoardLength; i++) {
for (int j = 0; j < BoardLength; j++) {
if (Board[i][j] != 0) {
if (Board[i][j] == Black)
brush.setColor(Qt::black);
else if (Board[i][j] == White)
brush.setColor(Qt::white);
brush.setStyle(Qt::SolidPattern);
painter.setBrush(brush);
//x,y坐标都减去15是为了让棋子中心落在交点处
painter.drawEllipse(i*BoardOneSize + BoardMargin - 15, j * BoardOneSize + BoardMargin - 15, 30, 30);
}
}
}
//根据鼠标移动画出红色小方框
//presentRowx是鼠标当前所指向的行,presentcoly是鼠标当前指向的列
//if判断鼠标是否在棋盘内
if (presentRowx>=0&&presentcoly>=0&&presentRowx<=BoardLength&&presentcoly<=BoardLength)
{
painter.setPen(QPen(Qt::red,2,Qt::SolidLine));
//根据行号列号计算出落子位置
int centerx = BoardMargin+presentRowx*BoardOneSize;
int centery = BoardMargin+presentcoly*BoardOneSize;
painter.drawLine(centerx-20,centery-20,centerx-10,centery-20);
painter.drawLine(centerx+10,centery-20,centerx+20,centery-20);
painter.drawLine(centerx-20,centery-20,centerx-20,centery-10);
painter.drawLine(centerx-20,centery+10,centerx-20,centery+20);
painter.drawLine(centerx-20,centery+20,centerx-10,centery+20);
painter.drawLine(centerx+20,centery+20,centerx+10,centery+20);
painter.drawLine(centerx+20,centery+20,centerx+20,centery+10);
painter.drawLine(centerx+20,centery-10,centerx+20,centery-20);
}
}