将参数传递给QT设计器构建的slot函数

Pass arguments to slot function built by QT Designer

本文关键字:构建 slot 函数 参数传递 QT      更新时间:2023-10-16

我是GUI设计的新手,开始使用QT Designer 4.8.6。我正在使用信号插槽机制连接按钮以发挥作用。

以下是pyuic4util为创建GUI脚本生成的一些连接:

QtCore.QObject.connect(self.btn_add_codes, QtCore.SIGNAL(_fromUtf8("clicked()")), MainWindow.sel_codes_file)
QtCore.QObject.connect(self.btn_add_xls, QtCore.SIGNAL(_fromUtf8("clicked()")), MainWindow.sel_excel_file)

我的主python文件中的相关函数(path_codespath_excel是QLineEdit小部件):

class MainDialog(QtGui.QMainWindow, gui_v1.Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainDialog, self).__init__(parent)
        self.setupUi(self)
    def sel_codes_file(self):
        self.path_codes.setText(QtGui.QFileDialog.getOpenFileName())
    def sel_excel_file(self):
        self.path_excel.setText(QtGui.QFileDialog.getOpenFileName())

我想为所有按钮使用一个通用函数,这些按钮的操作是搜索文件并在LineEdit小部件中显示路径。我在MainDialog类中添加了这个函数:

def select_file(self, textbox):
        self.textbox.setText(QtGui.QFileDialog.getOpenFileName())

我将连接修改为:

QtCore.QObject.connect(self.btn_add_codes, QtCore.SIGNAL(_fromUtf8("clicked()")), MainWindow.select_file(textbox=self.path_codes)

它不起作用。主窗口没有显示此代码,我收到此错误:AttributeError: 'MainDialog' object has no attribute 'textbox'

是否可以将参数传递给插槽连接函数?如果是,我做错了什么?谢谢

这个lambda工作吗?至少在使用C++时,我是这样使用Qt的。

self.btn_add_codes.clicked.connect(lambda codes=self.path_codes: MainWindow.select_file(codes))