【问题标题】:Pass arguments to slot function built by QT Designer将参数传递给 QT Designer 构建的槽函数
【发布时间】:2016-09-05 13:41:00
【问题描述】:

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

以下是 pyuic4 工具生成的一些用于创建 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'

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

【问题讨论】:

    标签: python c++ qt user-interface qt-designer


    【解决方案1】:

    这个 lambda 有效吗?至少我在使用 C++ 时使用 Qt 是这样的。

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

    【讨论】:

    • 感谢您的回答,但它不起作用。我遇到了同样的错误:“MainDialog”对象没有属性“文本框”
    • 好的,那是因为您的 MainDialog 确实没有文本框。它与connect 行无关。首先在你的班级中声明它:self.textbox = QtGui.QLineEdit()(或者它应该是的任何类型......)
    猜你喜欢
    • 2022-01-10
    • 2011-05-08
    • 2020-06-26
    • 2013-11-11
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    相关资源
    最近更新 更多