在Qt Designer中鼠标悬停

时间:2012-09-08 20:31:55

标签: qt qt4 pyqt qt-designer

我在Qt Designer中创建了gui,然后使用pyuic4将其转换为python。现在我想在按钮上捕获鼠标悬停事件。

class window_b(QtGui.QDialog):
    def __init__(self,parent=None):
        super(window_b, self).__init__(parent)
        window_a.setEnabled(False)
        self.ui = Ui_Form_window_b()
        self.ui.setupUi(self)
        self.setFocusPolicy(QtCore.Qt.StrongFocus)
    def mouseMoveEvent (self,event):
        source= self.sender()
        #print source.name()
        # The action I want to do when the mouse is over the button:
        source.setStyleSheet("background-color:#66c0ff;border-radiu‌​s: 5px;")

我在窗口小部件上放了mouseMoveEvent方法,我想检测Dialog上哪个按钮发送了mouseOver事件。我试过了source.name()但它却抛出了这个错误

print source.name()
AttributeError: 'NoneType' object has no attribute 'name'

任何建议。

1 个答案:

答案 0 :(得分:2)

sender()仅对信号有用,但鼠标悬停是一个事件而非信号(实际上是2个事件:QEvent.EnterQEvent.Leave)。

为了能够处理接收它们的按钮之外的事件,您需要将window_b实例安装为每个按钮的事件过滤器。

class window_b(QtGui.QDialog):
    def __init__(self,parent=None):
        super(window_b, self).__init__(parent)
        window_a.setEnabled(False)
        self.ui = Ui_Form_window_b()
        self.ui.setupUi(self)
        self.setFocusPolicy(QtCore.Qt.StrongFocus)

        # Get all the buttons (you probably don't want all of them)
        buttons = self.findChildren(QtGui.QAbstractButton)
        for button in buttons:
            button.installEventFilter(self)

    def eventFilter(self, obj, event):
        if event.type() == QtCore.QEvent.Enter:
            print("mouse entered %s" % obj.objectName())
        elif event.type() == QtCore.QEvent.Leave:
            print("mouse leaved %s" % obj.objectName())    
        return super(window_b, self).eventFilter(obj, event)

如果您只需要更改样式,则只需在样式表中使用伪状态“:hover”(来自设计器,或者使用self.setStyleSheet的构造函数):

QPushButton {
     border: 1px solid black;   
     padding: 5px;
}
QPushButton:hover {   
    border: 1px solid black;
    border-radius: 5px;   
    background-color:#66c0ff;
}