【发布时间】:2021-05-20 00:31:42
【问题描述】:
单击时,我试图在小部件上获取鼠标位置。似乎有多种方法可以做到这一点。 underMouse 功能似乎是最受欢迎的功能。我不知道我做错了什么。我尝试了所有可能的技术。下面是我的python代码,除此之外我还有一个ui文件。
from PyQt5 import QtWidgets, uic, QtCore, QtGui
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QPixmap, QMovie
import pyqtgraph as qwt_plot
import sys
class Ui(QtWidgets.QMainWindow):
def __init__(self):
super(Ui, self).__init__() # Call the inherited classes __init__ method
uic.loadUi('stupid.ui', self) # Load the .ui file
self.show() # Show the GUI
self.frame = None
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.run)
self.track = QtGui.QWidget(self.widget)
self.setMouseTracking(True)
self.track.mouseReleaseEvent = self.gig
def gig(self, event):
print ("Method 1 worked")
def mouseReleaseEvent(self, event):
posMouse = event.pos()
#print("%d, %d" % (posMouse.x(), posMouse.y()))
#print (self.track.geometry())
if self.track.geometry().contains(posMouse):
print "Under Mouse"
if self.track.underMouse():
print ("phew")
def run(self):
# Do nothing
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv) # Create an instance of QtWidgets.QApplication
window = Ui() # Create an instance of our class
window.setWindowTitle('Mouse Position GUI')
app.exec_() # Start the application
ui 文件:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>932</width>
<height>546</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<property name="windowIcon">
<iconset>
<normaloff>icon.png</normaloff>icon.png</iconset>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QWidget" name="widget" native="true">
<property name="geometry">
<rect>
<x>110</x>
<y>0</y>
<width>631</width>
<height>511</height>
</rect>
</property>
</widget>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>932</width>
<height>22</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
【问题讨论】:
-
请注意formatting 和缩进,并始终检查预览和发布的结果。