Dec-09-2021, 12:40 PM
I think it is a bad idea using setGeometry() to size and position your button in the window. I also think it is a bad idea passing the size and position as a parameter when you create the button. The ​common practice to use a geometry manager to place widgets in a window.
I don't think the button should have a button_visibility() method and I don't think the button should bind the clicked signal to call this method. What good is a button that hides itself? Buttons should not do things like set their size or bind their clicked events. Buttons should be generic reusable things. The application should use the button API to bind the events.
This is how I would write your code. I use PySide instead of PyQt, so there are some minor differences related to that. I also removed the style sheets and anything that is not absolutely required to demonstrate the issue related to the post topic. And just for fun I changed the hover event to not only emit a signal but change the button icon.
I don't think the button should have a button_visibility() method and I don't think the button should bind the clicked signal to call this method. What good is a button that hides itself? Buttons should not do things like set their size or bind their clicked events. Buttons should be generic reusable things. The application should use the button API to bind the events.
This is how I would write your code. I use PySide instead of PyQt, so there are some minor differences related to that. I also removed the style sheets and anything that is not absolutely required to demonstrate the issue related to the post topic. And just for fun I changed the hover event to not only emit a signal but change the button icon.
import sys import PySide6.QtWidgets as QtWidgets import PySide6.QtCore as QtCore import PySide6.QtGui as QtGui class HoverButton(QtWidgets.QPushButton): """A Pushbutton that changes it's icon when you hover""" hover = QtCore.Signal(bool) def __init__(self, parent, icon, hover_icon): super().__init__(parent) self.icon = icon self.hover_icon = hover_icon self.setMouseTracking(True) self.setIcon(self.icon) def enterEvent(self, event): self.setIcon(self.hover_icon) self.hover.emit(True) def leaveEvent(self, event): self.setIcon(self.icon) self.hover.emit(False) class Window(QtWidgets.QWidget): """A window that demonstrates how to use my hover button""" def __init__(self): super().__init__() play_button = HoverButton( self, QtGui.QIcon("ttt_x.png"), QtGui.QIcon("ttt_o.png") ) # Bind events outside the button play_button.hover.connect(lambda flag: print("Hover", flag)) play_button.clicked.connect(lambda flag: play_button.setVisible(False)) layout = QtWidgets.QVBoxLayout(self) layout.addWidget(play_button) app = QtWidgets.QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec())