Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hover issue in PyQt

I want to do hover. I saw an example and then write a script which will be use as I made program. I am facing one problem that hover only occur if you put mouse on the left corner of button. I want that it will happen for all the button that if i move cursor on 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_())
like image 907
Uahmed Avatar asked Dec 17 '22 03:12

Uahmed


2 Answers

Is this what you're 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 the nested button wasn't assigned to a QLayout widget. Although, I'm not sure why you're adding a button inside of a button. One thing that I've learned from working with GUI's is that it's so much easier if you modularize your code. Now you can take this custom button and apply it somewhere else.

like image 200
Jeff Avatar answered Dec 18 '22 16:12

Jeff


You should use the stylesheet as

QToolButton:hover
{
        background-color: rgb(175,175,175);
}
like image 27
bostonsqd Avatar answered Dec 18 '22 17:12

bostonsqd