学习了事件、绘图。做个练习,在窗口画出一个棋盘,鼠标点下的格子显示图片
源代码:
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPaintEvent>
#include <QMouseEvent>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
protected:
void paintEvent(QPaintEvent *);
void mousePressEvent(QMouseEvent *);
private:
Ui::Widget *ui;
int gridW; //棋盘水平方向一个格子的宽度
int gridH; //高度
int startX; //棋盘起点X坐标
int startY; //Y坐标
int chessX,chessY; //棋盘下标
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QPainter>
#include <QPen>
#include <QDebug>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
this->resize(600,600);
chessX=-1;
chessY=-1;
}
void Widget::paintEvent(QPaintEvent *)
{
//窗口均分10份
gridW=this->width()/10;
gridH=this->height()/10;
//棋盘起点坐标,即左上角坐标
startX=gridW;
startY=gridH;
//常见画家,指定窗口为绘图设备
QPainter p(this);
// 背景图
//p.drawPixmap(rect(),QPixmap("../1.jpg"));
//画笔
QPen pen;
pen.setWidth(4);
p.setPen(pen);
//画棋盘
for(int i=0;i<=8;++i)
{
//横线
p.drawLine(startX,startY+i*gridH,startX+8*gridW,startY+i*gridH);
//竖线
p.drawLine(startX+i*gridW,startY,startX+i*gridW,startY+8*gridH);
}
//画棋子
if(chessX!=-1&&chessY!=-1)
{
p.drawPixmap(startX+chessX*gridW,startY+chessY*gridH,
gridW,gridH,
QPixmap("../1.jpg"));
}
}
void Widget::mousePressEvent(QMouseEvent *e)
{
//获取点击的坐标
int x=e->x();
int y=e->y();
//在棋盘范围你内点击有效
if(x>=startX&&y>=startY&&x<=startX+8*gridW&&y<=startY+8*gridH)
{
//棋盘位置转换成坐标下标值
//类似a[i][j]的i,j
chessX=(x-startX)/gridW;
chessY=(y-startY)/gridH;
qDebug()<<chessX<<chessY;
//更新
update();
}
}
Widget::~Widget()
{
delete ui;
}