'''
实现简单画板功能并存储线段信息
'''
import sys
import time
import pymysql.cursors
from PyQt5.QtWidgets import (QApplication, QWidget)
from PyQt5.QtGui import (QPainter, QPen)
from PyQt5.QtCore import Qt
connect = pymysql.Connect(
host='localhost',
port=3306,
user='edu',
passwd='123456',
db='test',
charset='utf8'
)
# 获取游标
cursor = connect.cursor()
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
#resize设置宽高,move设置位置
self.resize(400, 300)
self.move(100, 100)
self.setWindowTitle("简单的画板1.0")
#setMouseTracking设置为False,否则不按下鼠标时也会跟踪鼠标事件
self.setMouseTracking(False)
#设置两个变量接收移动中的点的x、y坐标
self.pos_x = 20
self.pos_y = 20
def paintEvent(self, event):
painter = QPainter()
painter.begin(self)
pen = QPen(Qt.black, 2, Qt.SolidLine)
painter.setPen(pen)
#定点(20, 20) 到 (self.pos_x, self.pos_y)之间画线
painter.drawLine(20, 20, self.pos_x, self.pos_y)
painter.end()
def mouseMoveEvent(self, event):
'''
按住鼠标移动事件:更新pos_x和pos_y的值
调用update()函数在这里相当于调用paintEvent()函数
每次update()时,之前调用的paintEvent()留下的痕迹都会清空
'''
self.pos_x = event.pos().x()
self.pos_y = event.pos().y()
self.update()
line_end_x = event.pos().x()
line_end_y = event.pos().y()
# 先看一下有没有线段信息,没有则创建
sql = "SELECT count(*) FROM line WHERE line_name = '%s' "
data = ('line1',)
cursor.execute(sql % data)
rowcount = cursor.fetchall()[0][0]
print('共查找出', rowcount, '条数据')
if (rowcount == 0):
# 插入数据
sql = "INSERT INTO line (line_name, line_start_x, line_start_y,line_end_x,line_end_y) VALUES ( '%s', '%d','%d','%d' ,'%d' )"
data = ('line1', 20, 20, 20, 20)
cursor.execute(sql % data)
connect.commit()
print('成功插入', cursor.rowcount, '条数据')
else:
sql = "UPDATE line SET line_end_x = %d,line_end_y=%d,update_time='%s' WHERE line_name = '%s' "
now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
print(now)
data = (line_end_x, line_end_y, now, 'line1',)
cursor.execute(sql % data)
connect.commit()
print('成功修改', cursor.rowcount, '条数据')
if __name__ == "__main__":
app = QApplication(sys.argv)
pyqt_learn = Example()
pyqt_learn.show()
app.exec_()
# 关闭连接
cursor.close()
connect.close()
python实现画板功能并操作数据库
最新推荐文章于 2024-06-27 14:13:38 发布