本文实例为大家分享了Qt实现棋盘游戏的具体代码,供大家参考,具体内容如下
知识点
1、画背景图、线条
2、qDebug()与QString联合使用
1
|
qDebug()<<QString( "(%1,%2)" ).arg(checkX).arg(checkY); |
结果演示
widget.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public : explicit Widget(QWidget *parent = 0); ~Widget(); private : void paintEvent(QPaintEvent *ev); void mousePressEvent(QMouseEvent *ev); int startX; int startY; int widthC; int heightC; int checkX; int checkY; private : Ui::Widget *ui; }; #endif // WIDGET_H |
widget.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
#include "widget.h" #include "ui_widget.h" #include <QPainter> #include <QPaintEvent> #include <QMouseEvent> #include <QPen> #include <QMessageBox> #include <QDebug> Widget::Widget(QWidget *parent) : QWidget(parent), ui( new Ui::Widget) { ui->setupUi( this ); resize(700,400); checkX=-1; checkY=-1; } void Widget::paintEvent(QPaintEvent *ev){ //画背景图 QPainter p( this ); p.drawPixmap(rect(),QPixmap( ":/new/prefix1/image/Frame.jpg" )); QPen pen; pen.setWidth(4); //设置线宽 pen.setColor( "black" ); p.setPen(pen); //把笔交给画家 //画网格 widthC=width()/10; heightC=height()/10; startX=widthC; startY=heightC; for ( int i=0;i<9;i++){ p.drawLine(startX,startY+i*heightC,startX+8*widthC,startY+i*heightC); //画9条横线 p.drawLine(startX+i*widthC,startY,startX+i*widthC,startY+8*heightC); //画9条竖线 } //画棋子 if (checkX!=-1&&checkY!=-1){ p.drawPixmap(startX+checkX*widthC,startY+checkY*heightC,widthC,heightC,QPixmap( ":/new/prefix1/image/LuffyQ.png" )); } } //重写鼠标按下事件 void Widget::mousePressEvent(QMouseEvent *ev){ if (ev->button()==Qt::LeftButton){ //左击才显示 int x=ev->x(); int y=ev->y(); //保证不越界 if (x>=startX&&x<=startX*9&&y>=startY&&y<=startY*9){ checkX=(x-widthC)/widthC; //获取棋子X checkY=(y-heightC)/heightC; //获取棋子Y qDebug()<<QString( "(%1,%2)" ).arg(checkX).arg(checkY); } update(); } } Widget::~Widget() { delete ui; } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/taw19960426/article/details/122308574