Problem with Hover in PyQt

I want to make a hang. I saw an example, and then I will write a script that will be used as I did the program. I ran into one problem that freezes only when you mouse over the left corner of the button. I want this to happen for the whole button, if I find the cursor on the button, then it should change.

Here is my code:

from PyQt4 import QtGui, QtCore from PyQt4.QtCore import pyqtSignal import os,sys class HoverButton(QtGui.QToolButton): def enterEvent(self,event): print("Enter") button.setStyleSheet("background-color:#45b545;") def leaveEvent(self,event): button.setStyleSheet("background-color:yellow;") print("Leave") app = QtGui.QApplication(sys.argv) widget = QtGui.QWidget() button = QtGui.QToolButton(widget) button.setMouseTracking(True) buttonss = HoverButton(button) button.setIconSize(QtCore.QSize(200,200)) widget.show() sys.exit(app.exec_()) 
+4
source share
3 answers

This is what you are looking for

 from PyQt4 import QtGui, QtCore from PyQt4.QtCore import pyqtSignal import os,sys class Main(QtGui.QWidget): def __init__(self, parent=None): super(Main, self).__init__(parent) layout = QtGui.QVBoxLayout(self) # layout of main widget button = HoverButton(self) button.setIconSize(QtCore.QSize(200,200)) layout.addWidget(button) # set your button to the widgets layout # this will size the button nicely class HoverButton(QtGui.QToolButton): def __init__(self, parent=None): super(HoverButton, self).__init__(parent) self.setMouseTracking(True) def enterEvent(self,event): print("Enter") self.setStyleSheet("background-color:#45b545;") def leaveEvent(self,event): self.setStyleSheet("background-color:yellow;") print("Leave") app = QtGui.QApplication(sys.argv) main = Main() main.show() sys.exit(app.exec_()) 

In your code, you had a button in a button, and a nested button was not assigned to a QLayout widget. Although, I'm not sure why you are adding a button inside a button. One thing that I learned from working with the GUI is that it is much easier if you modulate your code. Now you can use this custom button and apply it elsewhere.

+9
source

You should use a stylesheet as

 QToolButton:hover { background-color: rgb(175,175,175); } 
+2
source

You probably need focus and blur , and not enter and leave will only work when the mouse really enters or leaves the border of the button and is likely to be just short pulses, not switches. focus and blur will switch with hovering.

0
source

Source: https://habr.com/ru/post/1397663/


All Articles