我无法从PyQt5标签类中获取文本数据。我的目标是给一个标签数组,如果我按一个,则必须返回包含的文本值。它只返回数组的最后一个标签。
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_())
当我运行程序时:this is the window generated at startup
当我单击数字1标签时,它返回: when I click the label
终端返回的内容:Terminal returns
答案 0 :(得分:0)
您只需要更改lambda函数定义:
clickable(label[y]).connect(lambda y=y: self.showText1(label[y]))