M
M
Molodoy422020-10-28 16:09:44
Python
Molodoy42, 2020-10-28 16:09:44

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

1 answer(s)
A
Andy_U, 2020-10-28
@Molodoy42

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)

and make sure that while you move the mouse over the window, lines with output go to the console, and when the mouse is over the button, they immediately stop. The button starts tracking the mouse...
If you add a line to __init__: then everything will work. PS But you can still select the button with a tab and press Enter...
self.btn.setMouseTracking(True)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question