首页 > 解决方案 > 带有传递函数参数的方法调用

问题描述

我目前正在开发基于 Qt、pyqt 和 Python 作为我的语言的 UI。我想知道是否有任何方法可以定义一个方法,我可以交出一个稍后在函数调用中使用的变量。目前我正在这样解决它:

def loader(self, filePath, id):
#firstTable, secondTable and thirdTable are three different Table Widgets in the UI
    if id == "1":
        tab = self.ui.firstTable
    elif id == "2":
        tab = self.ui.secondTable
    elif id == "3":
        tab = self.ui.thirdTable

    tab.clearContents()
    with open(filePath, "r", encoding="utf-8") as file:
        rowCount = tab.rowCount()
        columnCount = tab.columnCount()
        csvReader = csv.reader(file, delimiter=",", quotechar="'")
        for row in csvReader:
            if csvReader.line_num > rowCount:
                tab.insertRow(csvReader.line_num - 1)
            for i in range(0, columnCount):
                tab.setItem((csvReader.line_num - 1), i, QtWidgets.QTableWidgetItem(row[i]))
    tab.sortItems(1)

我想像这样解决它,但我只是不知道该怎么做,并且在研究这个问题时没有找到任何解决方案:

def loader(self, filePath, widget):
#variabel widget would be the corresponding object name I want to adress, like firstTable, secondTable, thirdTable
#...
    self.ui.widget.clearContents()
#...
    self.ui.widget.rowCount()

我希望我能正确解释我的问题,并且有人可以帮助我。谢谢!

编辑:这是我当前调用加载程序的方式:

 self.loader("file.csv", "1")

标签: pythonpyqtwidgetpyqt5

解决方案


如果小部件是某个类 cl 中的方法,则可以像这样调用 loader:

ld = cl.loader(filePath, cl.widget)

然后在加载程序中使用它:

widget.clearcontents(self)

等等

请记住,方法只是一个带有隐含第一个参数的函数——类引用。


推荐阅读