2012-02-21 116 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); 
}