[英]Hover issue in 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_())
這就是你要找的東西
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中學到的一件事是,如果你模塊化你的代碼就會容易得多。 現在,您可以使用此自定義按鈕並將其應用到其他位置。
你應該使用樣式表作為
QToolButton:hover
{
background-color: rgb(175,175,175);
}
您可能想要focus
和blur
,而不是enter
和leave
只會在鼠標實際進入或離開按鈕的邊界時觸發,並且可能只是短持續時間的脈沖而不是切換。 focus
和blur
將與懸停切換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.