gpt4 book ai didi

python - 无法停止在qgraphicsview中绘制矩形

转载 作者:太空宇宙 更新时间:2023-11-03 20:28:27 25 4
gpt4 key购买 nike

在我的程序中,我可以选择一个设置 self.rectmode=1 的按钮。一旦该变量设置为 1,它就会使用 qgraphicsview 上的鼠标事件绘制矩形。按下按钮设置 self.rectmode=0 后,程序继续使用鼠标事件绘制矩形。我是否缺少一些线来结束矩形绘制事件。我的代码如下,提前致谢:

def mousePressEvent(self, event):

if (self.rectmode==1 and event.button() == Qt.LeftButton and not self._photo.pixmap().isNull()):
self.origin = event.pos()
self.rubberBand.setGeometry(QRect(self.origin, QSize()))
self.rectChanged.emit(self.rubberBand.geometry())
self.rubberBand.show()
self.changeRubberBand = True

else:
super(PhotoViewer, self).mousePressEvent(event)

def mouseMoveEvent(self, event):

if self.rectmode==1 and self.changeRubberBand:
self.rubberBand.setGeometry(QRect(self.origin, event.pos()).normalized())
self.rectChanged.emit(self.rubberBand.geometry())

else:
super(PhotoViewer, self).mouseMoveEvent(event)

def mouseReleaseEvent(self, event):

if self.rectmode==1 and event.button() == Qt.LeftButton:
self.changeRubberBand = False
self.endpoint = event.pos()
print(self.origin.x())
print(self.origin.y())
print(self.endpoint.x())
print(self.endpoint.y())

else:
super(PhotoViewer, self).mouseReleaseEvent(event)

最佳答案

在您的代码中,rectmode始终为1,我认为这就是导致问题的原因,这是一个工作示例,我还删除了变量changeRubberBand,因为同样可以仅使用变量 rectMode 即可实现:

import sys

from PyQt5.Qt import QApplication, QRect, QSize, Qt, QRubberBand, QVBoxLayout, pyqtSignal
from PyQt5.QtWidgets import QMainWindow


class PhotoViewer(QMainWindow):
rectChanged = pyqtSignal(QRect)

def __init__(self):
super().__init__()
self.origin = None
self.endpoint = None
self.rectMode = 0

self.setFixedSize(1024, 768)
self.layout = QVBoxLayout(self)

self.rubberBand = QRubberBand(QRubberBand.Rectangle, self)
self.rubberBand.hide()
self.layout.addChildWidget(self.rubberBand)

def mousePressEvent(self, event):
if self.rectMode == 0 and event.button() == Qt.LeftButton:
self.origin = event.pos()
self.rubberBand.setGeometry(QRect(self.origin, QSize()))
self.rectChanged.emit(self.rubberBand.geometry())
self.rubberBand.show()
self.rectMode = 1
else:
super(PhotoViewer, self).mousePressEvent(event)

def mouseMoveEvent(self, event):
if self.rectMode == 1:
self.rubberBand.setGeometry(QRect(self.origin, event.pos()).normalized())
self.rectChanged.emit(self.rubberBand.geometry())

else:
super(PhotoViewer, self).mouseMoveEvent(event)

def mouseReleaseEvent(self, event):
if self.rectMode == 1 and event.button() == Qt.LeftButton:
self.rectMode = 0
self.endpoint = event.pos()
print(self.origin.x())
print(self.origin.y())
print(self.endpoint.x())
print(self.endpoint.y())

else:
super(PhotoViewer, self).mouseReleaseEvent(event)


if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = PhotoViewer()
mainWindow.show()
sys.exit(app.exec_())

希望有帮助。

关于python - 无法停止在qgraphicsview中绘制矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57662961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com