方法一:lambda表达式传递参数
from PyQt5.QtCore import *
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
import sys
class LambdaSlotArg(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("使用Lambda表达式为槽函数传递参数")
self.resize(800, 500)
button1 = QPushButton("按钮1")
button2 = QPushButton("按钮2")
layout = QHBoxLayout()
layout.addWidget(button1)
layout.addWidget(button2)
mainFrame = QWidget()
mainFrame.setLayout(layout)
self.setCentralWidget(mainFrame)
button1.clicked.connect(lambda: self.onButtonClick(10, 20))
button2.clicked.connect(lambda: self.onButtonClick(40, -20))
def onButtonClick(self, m, n):
print("m+n=", m+n)
QMessageBox.information(self, "结果=", str(m+n))
if __name__ == '__main__':
app = QApplication(sys.argv)
main_win = LambdaSlotArg()
main_win.show()
sys.exit(app.exec_())
方法二:
使用Partial对象为槽函数传递参数
from PyQt5.QtCore import *
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
from functools import partial
import sys
class PartialSlotSlotArg(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("使用Lambda表达式为槽函数传递参数")
self.resize(800, 500)
button1 = QPushButton("按钮1")
button2 = QPushButton("按钮2")
x = 20
y = -123
layout = QHBoxLayout()
layout.addWidget(button1)
layout.addWidget(button2)
mainFrame = QWidget()
mainFrame.setLayout(layout)
self.setCentralWidget(mainFrame)
# 方法二
button1.clicked.connect(partial(self.onButtonClick, 10, 20))
button2.clicked.connect(partial(self.onButtonClick, x, y))
def onButtonClick(self, m, n):
print("m+n=", m+n)
QMessageBox.information(self, "结果=", str(m+n))
if __name__ == '__main__':
app = QApplication(sys.argv)
main_win = PartialSlotSlotArg()
main_win.show()
sys.exit(app.exec_())
标签:__,layout,函数,self,PyQT5,mainFrame,PyQt5,import,之为
From: https://www.cnblogs.com/jackchen28/p/18238664