我正在尝试使用lambda函数连接到一个函数。 在这里我想与func CreateInsertLabel(self,qframe)连接 这样,每当我单击按钮时,它都会返回一个标签。
这是最小的代码:
from PyQt5 import QtCore, QtGui, QtWidgets
#call this class to create a label
class CreateLabel(QtWidgets.QLabel):
def __init__(self, qframe,x,y,h,w,font):
super().__init__(qframe)
self.state = 2
self.setFont(font)
self.move(0,-1000)
self.setGeometry(x,y,h,w)
self.setAlignment(QtCore.Qt.AlignCenter)
self.setObjectName("welcomeMessage")
self.setText('Insert succeeded!')
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.buttonlabel = QtWidgets.QPushButton(self.centralwidget)
self.buttonlabel.setGeometry(QtCore.QRect(350, 370, 97, 27))
self.buttonlabel.setObjectName("buttonlabel")
#-------------------------------------------
#The problem here
self.buttonlabel.clicked.connect(lambda state, x = self.centralwidget: self.CreateInsertLabel(x))
# This is working as expected
#self.label_txt = self.CreateInsertLabel(self.centralwidget)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 25))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.buttonlabel.setText(_translate("MainWindow", "Insert"))
def CreateInsertLabel(self, qframe):
font = QtGui.QFont()
font.setPointSize(15)
font.setBold(False)
font.setWeight(20)
self.label_tour = CreateLabel(qframe, 220, 280, 431, 20,font)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
如果我使用
可以正常工作self.label_txt = self.CreateInsertLabel(self.centralwidget)
在我之前的人有相同的问题(Qt - Connect slot with argument using lambda)和(Using lambda expression to connect slots in pyqt),但这些解决方案对我不起作用。 任何帮助将不胜感激。