The problem is that the mousePressEvent does not necessarily propagate from the parent widget to the child widget (that behavior depends on each type of widget, for example QLabel if it propagates the mouse events), in addition to your strategy of overriding the mouseMoveEvent method is limited if you want Listen to the events of other widgets.
(问题在于,除了覆盖mouseMoveEvent方法的策略外,mousePressEvent不一定从父窗口小部件传播到子窗口小部件(行为取决于每种类型的窗口小部件,例如QLabel如果它传播鼠标事件)。如果您想听其他小部件的事件,则限制。)
Considering the above, a possible solution is to use an eventFilter to listen to the events of any widget, and another improvement is to use the global position instead of the local one so that when the mouse changes from QGraphicsView it is not affected by the local coordinate system.
(考虑到上述情况,一种可能的解决方案是使用eventFilter侦听任何小部件的事件,另一个改进是使用全局位置而不是本地位置,以便当鼠标从QGraphicsView更改时,它不受本地影响。坐标系。)
class MouseListener(QObject):
posChanged = pyqtSignal(QPoint)
def __init__(self, widget):
super().__init__(widget)
self._widget = widget
self._widget.setMouseTracking(True)
self._widget.installEventFilter(self)
def eventFilter(self, obj, event):
if obj is self._widget and event.type() == QEvent.MouseMove:
self.posChanged.emit(event.globalPos())
return super().eventFilter(obj, event)
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
loadUi("mainwindow.ui", self)
self.showMaximized()
self.global_pos = QCursor.pos()
for lay in (self.verticalLayout_top, self.verticalLayout_bottom):
view = GraphicsView()
listener = MouseListener(view.viewport())
listener.posChanged.connect(self.on_pos_changed)
lay.addWidget(view)
@staticmethod
def _update_bar(progress_bar, delta):
current_value = progress_bar.value()
new_value = current_value + delta
progress_bar.setValue(new_value)
def on_pos_changed(self, pos):
new_x = pos.x()
new_y = pos.y()
old_x = self.global_pos.x()
old_y = self.global_pos.y()
if new_x > old_x:
self._update_bar(self.progressBar_x_plus, new_x - old_x)
if new_x < old_x:
self._update_bar(self.progressBar_x_minus, old_x - new_x)
if new_y > old_y:
self._update_bar(self.progressBar_y_plus, new_y - old_y)
if new_y < old_y:
self._update_bar(self.progressBar_y_minus, old_y - new_y)
self.global_pos = pos
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…