繁体   English   中英

PyQt中的悬停问题

[英]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);
}

您可能想要focusblur ,而不是enterleave只会在鼠标实际进入或离开按钮的边界时触发,并且可能只是短持续时间的脉冲而不是切换。 focusblur将与悬停切换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM