python实现画板功能并操作数据库

'''
实现简单画板功能并存储线段信息
'''
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()


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值