我是Qt(PyQt - PySide)的新手。
我正在尝试构建一个自定义小部件,这是一个菜单。然而,我走上了艰难的道路,似乎无法将自己排除在外。我已经阅读了文档,但我认为没有鼠标状态可以验证鼠标光标是否在给定的小部件上。
我在mouseReleaseEvent
的{{1}}上调用了一个函数。
例:
QWidget
当触发此事件时,我必须知道鼠标是否实际位于窗口小部件之外或之外(触发此事件的窗口小部件)。
def mouseReleaseEvent(self, e):
我怎样才能做到这一点?我需要做什么?
非常感谢!
答案 0 :(得分:13)
如果您想跟踪鼠标何时进入或离开小部件,您可以使用以下内容:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtCore, QtGui
class mainwindow(QtGui.QWidget):
def __init__(self, parent=None):
super(mainwindow, self).__init__(parent)
def enterEvent(self, event):
print "Mouse Entered"
return super(mainwindow, self).enterEvent(event)
def leaveEvent(self, event):
print "Mouse Left"
return super(mainwindow, self).enterEvent(event)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
main = mainwindow()
main.show()
sys.exit(app.exec_())
如果您只是想检查鼠标是否在窗口小部件上,您可以使用QWidget::underMouse ()
功能:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtCore, QtGui
class mainwindow(QtGui.QWidget):
def __init__(self, parent=None):
super(mainwindow, self).__init__(parent)
self.button = QtGui.QPushButton("Check Mouse in 3 seconds")
self.button.clicked.connect(self.on_button_clicked)
self.layout = QtGui.QHBoxLayout(self)
self.layout.addWidget(self.button)
def mouseReleaseEvent(self, event):
if self.underMouse():
print "Do something"
return super(mainwindow, self).mouseReleaseEvent(event)
@QtCore.pyqtSlot()
def on_button_clicked(self):
QtCore.QTimer.singleShot(3000, self.checkMouse)
def checkMouse(self):
print "Under Mouse: {0}".format(self.underMouse())
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
main = mainwindow()
main.show()
sys.exit(app.exec_())
另一种方法是检查鼠标的位置是否在窗口小部件的内部几何图形内:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtCore, QtGui
class mainwindow(QtGui.QWidget):
def __init__(self, parent=None):
super(mainwindow, self).__init__(parent)
self.setMouseTracking(True)
def mouseReleaseEvent(self, event):
posMouse = event.pos()
if self.rect().contains(posMouse):
print "Under Mouse"
return super(mainwindow, self).mouseReleaseEvent(event)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
main = mainwindow()
main.show()
main.resize(200, 200)
sys.exit(app.exec_())
答案 1 :(得分:6)
underMouse()用于确定鼠标是否在窗口小部件上
Usage: widget.underMouse()
http://pyqt.sourceforge.net/Docs/PyQt4/qwidget.html#underMouse