How to detect any mouse click on PySide Gui?

I try to implement such a function that when I click on gui, the function starts

Below is my mouse click detection, it does not work when I click on any part of 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_())

It is my goal

Mouseclick.gui_clicked.connect(do_something)

Any advice would be appreciated.

+4
source share
2 answers

Define mousePressEventinside Main:

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_())
+2
source

. , 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: , , .

+2

Source: https://habr.com/ru/post/1542696/


All Articles