如果按下的是左键,则调用self.create_point(event.pos())方法来在鼠标当前位置创建一个点。
如果按下的键是回车键(即键值为Qt.Key_Return),则弹出一个输入对话框让用户输入x和y坐标。
from PyQt5.QtWidgets import QApplication, QWidget,QInputDialog
from PyQt5.QtGui import QPainter, QBrush
from PyQt5.QtCore import Qt, QPoint
?
?
class Canvas(QWidget):
def __init__(self):
super().__init__()
?
self.points = [] # 存储所有创建的点
?
self.setMinimumSize(400, 400) # 设置画布大小
?
def paintEvent(self, event):
qp = QPainter()
qp.begin(self)
qp.setRenderHint(QPainter.Antialiasing) # 设置抗锯齿
?
# 绘制点
brush = QBrush(Qt.black)
qp.setBrush(brush)
for point in self.points:
qp.drawEllipse(point, 5, 5)
?
qp.end()
?
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.create_point(event.pos())
?
def keyPressEvent(self, event):
if event.key() == Qt.Key_Return:
input_dialog = QInputDialog()
input_dialog.setWindowTitle("输入坐标")
input_dialog.setLabelText("请输入x和y坐标(空格分隔):")
?
if input_dialog.exec():
input_str = input_dialog.textValue().split()
if len(input_str) == 2:
try:
x, y = map(int, input_str)
pos = QPoint(x, y)
self.create_point(pos)
except ValueError:
pass
?
def create_point(self, pos):
self.points.append(pos)
self.update()
?
?
if __name__ == '__main__':
app = QApplication([])
canvas = Canvas()
canvas.show()
app.exec_()