2012-02-21 75 views
4

我想做悬停。我看到一个例子,然后编写一个脚本,这个脚本将用于我制作的程序。如果将鼠标放在按钮的左上角,我只会遇到悬停问题。我希望它会发生所有的按钮,如果我将光标移动到按钮上,那么它应该改变。悬停问题PyQt

这里是我的代码:

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_()) 

回答

9

这是你在找什么

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_()) 

在你的代码中的一个按钮有一个按钮和嵌套的按钮没有被分配到一个QLayout部件。尽管我不确定为什么要在按钮内添加按钮。我从使用GUI学到的一件事是,如果你模块化你的代码,它会容易得多。现在您可以将此自定义按钮应用到其他地方。

+0

谢谢杰夫这是什么,我正在寻找,谢谢 – Uahmed 2012-04-09 14:00:01

0

你可能想focusblur,而不是enterleave当鼠标实际进入或离开按钮的边界才会触发,将可能只是短时间冲动而不是切换。 focusblur将随着悬停切换。

+0

我想改变按钮的颜色,因为它的鼠标来就可以 – Uahmed 2012-02-22 21:32:12

+0

您可以利用QSS样式表和应用不同的风格做到这一点的要容易得多':悬停'属性。查看http://developer.qt.nokia.com/doc/qt-4.8/stylesheet.html和http://developer.qt.nokia.com/doc/qt-4.8/stylesheet-reference.html – synthesizerpatel 2012-02-23 00:48:15

+0

感谢回复但我怎么能使用,我试图.setStyleSheet(“悬停:蓝色;”) 但它没有为我工作 – Uahmed 2012-02-23 01:04:50

2

您应该使用样式表作为

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