1、效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4c6a36f3fd8b88ea745adfd31a44e228.png)
2、chess.cpp
#include "chess.h"
Chess::Chess(QWidget *parent)
: QWidget(parent)
{
Init();
}
Chess::~Chess()
{
}
void Chess::paintEvent(QPaintEvent *){
QPainter painter(this);
QRect rec(QPoint(0,0),QPoint(this->width(),this->height()));
QPixmap pix(bgFilename);
qDebug()<<bgFilename<<endl;
painter.drawPixmap(rec,pix);
QPen pen1;
pen1.setStyle(lineStyle);
pen1.setColor(lineColor);
pen1.setWidth(lineWidth);
painter.setPen(pen1);
for(int i=0;i<=8;i++){
painter.drawLine(startx,starty+i*gridheight,9*gridwidth,starty+i*gridheight);
painter.drawLine(startx+i*gridwidth,starty,startx+i*gridwidth,starty+8*gridheight);
}
QString chessFilename;
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
if(chessData[i][j]==White){
chessFilename = "../png/white.png";
}
else if (chessData[i][j]==Black) {
chessFilename = "../png/black.gif";
}
else {
chessFilename.clear();
continue;
}
painter.drawPixmap(startx+i*gridwidth,starty+j*gridheight,gridwidth,gridheight,QPixmap(chessFilename));
}
}
}
void Chess::resizeEvent(QResizeEvent *event){
gridwidth = event->size().width()/GRIDCOLINT;
gridheight =event->size().height()/GRIDCOLINT;
startx = gridwidth;
starty = gridheight;
qDebug()<<"x::"<<startx<<"y::"<<starty;
}
void Chess::mousePressEvent(QMouseEvent *event){
int x=event->x();
int y=event->y();
if(x>=startx && (x<=startx+8*gridwidth)){
if(y>=starty && (y<=starty+8*gridheight)){
int i=0,j=0;
i = (x-startx)/gridwidth;
j = (y-starty)/gridheight;
qDebug()<<"i:"<<i<<"j"<<j<<endl;
chessData[i][j] = Black;
this->update();
}
}
}
void Chess::Init(){
bgFilename.clear();
bgFilename = "../png/2.jpg";
lineColor = Qt::red;
lineStyle = Qt::SolidLine;
lineWidth = 3;
memset(chessData,0,sizeof(int)*64);
chessData[3][3]=Black;chessData[4][4]=Black;
chessData[4][3]=White;chessData[3][4]=White;
}
void Chess::ChangeBackgroundImage(const QString filename){
this->bgFilename=filename;
}
void Chess::ChangeLine(const QColor color, Qt::PenStyle style, const int width){
this->lineColor = color;
this->lineStyle = style;
this->lineWidth = width;
}
3、chess.h
#ifndef CHESS_H
#define CHESS_H
#include <QWidget>
#include <QPainter>
#include <QPen>
#include <QDebug>
#include <QResizeEvent>
#include <QMouseEvent>
#define GRIDCOLINT 10
class Chess : public QWidget
{
Q_OBJECT
public:
Chess(QWidget *parent = 0);
~Chess();
enum ChessType{Empyty = 0,White,Black};
int chessData[8][8];
void ChangeBackgroundImage(const QString filename);
void ChangeLine(const QColor color,Qt::PenStyle style,const int width);
protected:
void paintEvent(QPaintEvent *);
void resizeEvent(QResizeEvent *event);
void mousePressEvent(QMouseEvent *);
private:
QString bgFilename;
QColor lineColor;
Qt::PenStyle lineStyle;
int lineWidth;
int gridwidth,gridheight,startx,starty;
void Init();
};
#endif