How to draw a rectangle and adjust its shape by drag and drop in PyQt5(如何在 PyQt5 中通过拖放来绘制矩形并调整其形状)
问题描述
我正在尝试通过拖放在 PyQt5 创建的 GUI 上绘制一个矩形.我设法做到了,但是释放鼠标左键时会绘制矩形.
I'm trying to draw a rectangle on GUI created by PyQt5 by drag and drop. I managed to do that, but the rectangle is drawn when the mouse left key is released.
我想做的就是这样link:
- 按下鼠标左键时,开始绘制矩形.
- 拖动时,通过鼠标移动调整矩形形状.
- 松开鼠标左键后,确定矩形形状.
我该如何实现呢?提前致谢.
How can I implement this? Thanks in advance.
这是我的代码.
# -*- coding: utf-8 -*-
import sys
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtGui import QPainter
class MyWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.setGeometry(30,30,600,400)
self.pos1 = [0,0]
self.pos2 = [0,0]
self.show()
def paintEvent(self, event):
width = self.pos2[0]-self.pos1[0]
height = self.pos2[1] - self.pos1[1]
qp = QPainter()
qp.begin(self)
qp.drawRect(self.pos1[0], self.pos1[1], width, height)
qp.end()
def mousePressEvent(self, event):
self.pos1[0], self.pos1[1] = event.pos().x(), event.pos().y()
print("clicked")
def mouseReleaseEvent(self, event):
self.pos2[0], self.pos2[1] = event.pos().x(), event.pos().y()
print("released")
self.update()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MyWidget()
window.show()
app.aboutToQuit.connect(app.deleteLater)
sys.exit(app.exec_())
推荐答案
你不必使用mouseReleaseEvent
函数,而是每次调用的mouseMoveEvent
函数鼠标移动了,我修改了代码让它更简单.
You do not have to use the mouseReleaseEvent
function, but the mouseMoveEvent
function that is called each time the mouse is moved, and I have modified the code to make it simpler.
class MyWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.setGeometry(30,30,600,400)
self.begin = QtCore.QPoint()
self.end = QtCore.QPoint()
self.show()
def paintEvent(self, event):
qp = QtGui.QPainter(self)
br = QtGui.QBrush(QtGui.QColor(100, 10, 10, 40))
qp.setBrush(br)
qp.drawRect(QtCore.QRect(self.begin, self.end))
def mousePressEvent(self, event):
self.begin = event.pos()
self.end = event.pos()
self.update()
def mouseMoveEvent(self, event):
self.end = event.pos()
self.update()
def mouseReleaseEvent(self, event):
self.begin = event.pos()
self.end = event.pos()
self.update()
这篇关于如何在 PyQt5 中通过拖放来绘制矩形并调整其形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 PyQt5 中通过拖放来绘制矩形并调整其形状
基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01