![](/img/trans.png)
[英]How to detect mouse click on images displayed in GUI created using PySide
[英]How to detect any mouse click on PySide Gui?
我正在嘗試實現一個功能,當在gui上單擊鼠標時,會觸發一個功能
下面是我的鼠標點擊檢測,當我點擊gui的任何部分時,它不起作用
from PySide.QtCore import *
from PySide.QtGui import *
import sys
class Main(QWidget):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
layout = QHBoxLayout(self)
layout.addWidget(QLabel("this is the main frame"))
layout.gui_clicked.connect(self.anotherSlot)
def anotherSlot(self, passed):
print passed
print "now I'm in Main.anotherSlot"
class MyLayout(QHBoxLayout):
gui_clicked = Signal(str)
def __init__(self, parent=None):
super(MyLayout, self).__init__(parent)
def mousePressEvent(self, event):
print "Mouse Clicked"
self.gui_clicked.emit("emit the signal")
a = QApplication([])
m = Main()
m.show()
sys.exit(a.exec_())
這是我的目標
Mouseclick.gui_clicked.connect(do_something)
任何意見,將不勝感激
在Main
定義mousePressEvent
:
from PySide.QtCore import *
from PySide.QtGui import *
import sys
class Main(QWidget):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
layout = QHBoxLayout(self)
layout.addWidget(QLabel("this is the main frame"))
def mousePressEvent(self, QMouseEvent):
#print mouse position
print QMouseEvent.pos()
a = QApplication([])
m = Main()
m.show()
sys.exit(a.exec_())
根據您的需要,這可能會變得復雜。 簡而言之,解決方案是在應用程序上安裝eventFilter
。 這將聽取整個應用程序的事件。 問題是“事件傳播”。 如果窗口小部件不處理事件,它將被傳遞給父窗口(依此類推)。 你會多次看到這些事件。 在您的情況下,例如QLabel
對鼠標按下事件沒有任何作用,因此父(您的主窗口)獲取它。
如果您實際過濾了事件(即您不希望原始窗口小部件響應事件),您將不會遇到該問題。 但是,我懷疑這是你的意圖。
一個簡單的監控示例:
import sys
from PySide import QtGui, QtCore
class MouseDetector(QtCore.QObject):
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.MouseButtonPress:
print 'mouse pressed', obj
return super(MouseDetector, self).eventFilter(obj, event)
class MainWindow(QtGui.QWidget):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
layout = QtGui.QHBoxLayout()
layout.addWidget(QtGui.QLabel('this is a label'))
layout.addWidget(QtGui.QPushButton('Button'))
self.setLayout(layout)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
mouseFilter = MouseDetector()
app.installEventFilter(mouseFilter)
main = MainWindow()
main.show()
sys.exit(app.exec_())
你可以看到,點擊QLabel
會給你一些類似的東西:
mouse pressed <PySide.QtGui.QLabel object at 0x02B92490>
mouse pressed <__main__.MainWindow object at 0x02B92440>
因為, QLabel
收到事件,因為它沒有對它做任何事情,它被忽略並傳遞給父( MainWindow
)。 它再次被過濾器/監視器捕獲。
單擊QPushButton
沒有任何問題,因為它使用該事件而不傳遞給父項。
PS: 另請注意,由於您正在檢查應用程序中的每個事件,因此可能會導致性能問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.