0

I can't get the text data out of the PyQt5 label class. my goal is given an array of labels if I press one I must return the text value contained. it only returns the last label of the array.

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

def clickable(widget):
    class Filter(QObject): 
        clicked = pyqtSignal()
        def eventFilter(self, obj, event):
            if obj == widget:
                if event.type() == QEvent.MouseButtonRelease:
                    if obj.rect().contains(event.pos()):
                        self.clicked.emit()
                        # The developer can opt for .emit(obj) to get the object within the slot.
                        return True
            return False
    filter = Filter(widget)
    widget.installEventFilter(filter)
    return filter.clicked

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent = None):
        QWidget.__init__(self, parent)
        self.setIU()


    def setIU(self):
        self.setCentralWidget(QtWidgets.QWidget(self))
        self.gridLayout = QtWidgets.QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        label = []
        for y in range(4):
            label.insert(y,QLabel())
            label[y].setMinimumSize(QtCore.QSize(160, 0))
            label[y].setMaximumSize(QtCore.QSize(160, 95))
            label[y].setStyleSheet("background-color:white;")
            label[y].setText(str(y))
            label[y].setObjectName("label"+str(y))
            clickable(label[y]).connect(lambda: self.showText1(label[y]))
            self.gridLayout.addWidget(label[y])

        self.centralWidget().setLayout(self.gridLayout)
        self.show()

    def showText1(self,_hit):
        num = _hit.text()
        #Terminal Print
        print ("Label "+num+" clicked")
        #MessageBox          
        mes =QtWidgets.QMessageBox()
        mes.setWindowTitle("Return")
        mes.setText("Label "+num+" clicked")
        mes.setIcon(QtWidgets.QMessageBox.Information)
        mes.setStandardButtons(QtWidgets.QMessageBox.Ok)
        mes.exec_()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

when I run the program: this is the window generated at startup

when I click the number 1 label but it returns: when I click the label

what the Terminal returns: Terminal returns

Alex536ITA
  • 11
  • 3

1 Answers1

0

You only need to change the lambda function definition:

clickable(label[y]).connect(lambda y=y: self.showText1(label[y]))
Maximouse
  • 4,170
  • 1
  • 14
  • 28