2

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?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Rajkumar
  • 530
  • 4
  • 9
  • 3
    If you install the event filter on the parent, you obviously are not using the object's filter. Use `obj.installEventFilter(self)`. Also, avoid overwriting `self.parent` since the existing `self.parent()` should be always preferred. – musicamante Dec 13 '20 at 15:16

1 Answers1

1

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  
Asocia
  • 5,935
  • 2
  • 21
  • 46