find parent of mousepress event of multiple randomly created widgets(like QLabel,QPushButton etc.) in PyQt5

Viewed 164

I have created multiple QLabels using for loop with same variables.Now i need to know that from where/which Lable,MousePress event is triggered.Is there any way like

event.parent() OR event.widget()

I also tried installEventFilter but its not working,It is because i am created the Qlabels in another class . If i create those labels in the same class it is working,but i need this working also on Another class. Here is my code:-

from PyQt5.QtWidgets import *
import sys

class Reader(QFrame):
    def __init__(self,parent):
        super().__init__(parent=parent)
        self.parent=parent
        self.parent.setCentralWidget(self)
        self.vbox=QVBoxLayout()
        self.setLayout(self.vbox)
        for i in range (1,6):
            obj=QLabel("Click")
            obj.mousePressEvent=self.onmousepress
            #obj.installEventFilter(self.parent)
            self.vbox.addWidget(obj)
    def onmousepress(self,event) :
        print('where  did it came from?') 
    def eventFilter(self, source, event):
        #Nothing Worked Here
        print(source,event) 
        return super().eventFilter(source, event)         
class MainWindow(QMainWindow):
   def __init__(self):
        super().__init__()
        self.resize(400,200)
        self.reader=Reader(self)
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())

Where i did wrong?

1 Answers

You need to install event filter for each label then you can know which label is pressed:

for i in range (1,6):
    obj=QLabel(f"Click {i}")
    obj.installEventFilter(self)

And:

def eventFilter(self, source, event):
    if event.type() == QEvent.MouseButtonPress: # from PyQt5.QtCore import QEvent
        print(source.text())
    return super().eventFilter(source, event)       

Output:

Click 1
Click 2
Click 3
Click 4
Click 5  
Related