Answer the question
In order to leave comments, you need to log in
Why doesn't the if construct occur in a PyQt event?
I need to write a program in PyQt so that when you hover over a button, it disappears and appears in another random place. The mouseMoveEvent event has an if construct that only occurs when the mouse button is held down, although mouse tracking is enabled. What is the problem? Why doesn't the if construction happen when just hovering, without holding down the button?
import sys
from random import randrange
from PyQt5.QtWidgets import QWidget, QApplication, QPushButton
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(300, 300, 600, 600)
self.btn = QPushButton(self)
self.btn.setText('Нажми меня')
self.btn.resize(100, 50)
self.btn.move(250, 250)
self.btn_x = 250
self.btn_y = 250
self.setMouseTracking(True)
def mouseMoveEvent(self, event):
if self.btn_x < event.x() < self.btn_x + 100 and self.btn_y < event.y() < self.btn_y + 50:
self.btn_x, self.btn_y = randrange(500), randrange(500)
self.btn.move(self.btn_x, self.btn_y)
if __name__ == '__main__':
app = QApplication(sys.argv)
wnd = Window()
wnd.show()
app.exit(app.exec())
Answer the question
In order to leave comments, you need to log in
Add mouseMoveEvent() to the code as the first line:
print(event.x(), event.y(), self.btn_x < event.x() < self.btn_x + 100, self.btn_y < event.y() < self.btn_y + 50)
self.btn.setMouseTracking(True)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question