问题描述
希望你没事。
我用图像填充了一个表格,它在大多数情况下表现得像我想要的,除非我将单元格连接到 cellClicked 信号。
假设我有这个功能
def print_cell (column,row):
print(column,row)
...
table.cellClicked.connect(print_cell)
这按预期工作,在单击单元格时打印一个(列,行)对,但我需要的不止于此。我的预期功能需要的不仅仅是列和行对。
我需要这样的东西:
def print_cell(column,row,max_column_count)
print(row*max_column_count + column) #I need to convert to array to load files.
我不明白这是怎么做到的,因为 cellClicked 只给我列和行。我已经尝试了不止几件事,但似乎没有任何效果,我希望您提供干净的建议,因为我可能理解错误。
编辑:提供更多的最小代码。
# import
# The imports we are using are custom made except for os,sys and math,but they include everything we need. I will use the name custom_module when instancing this classes,but they are basic a shortcut to PySide2 stuff.
def count_files(*args):
pass
#This counts the number of files given name prefix or extension inside a defined folder. It returns a unsigned integer with the total.
def print_cell(row,column):
print(row,column) #this is the function I want to improve.
class PyDialog(custom_module.QDialog,custom_module.QMainWindow):
def __init__(self,path,parent=None):
super(PyDialog,self).__init__(parent)
ext = '.png'
path = 'files'
prefix = 'icon'
file_count = count_files(path,ext)
max_column_count = 4 #This is hardcoded at the moment as this number will depend of other factors.
row_count = math.ceil(float(file_count)/float(max_column_count))
self.window=custom_module.dotui.load_ui(path,self)
table = self.window.img_table
table.setColumnCount(max_column_count)
table.setRowCount(row_count)
for index in range(file_count):
column,row = divmod(index,max_column_count)
icon_label = custom_module.QLabel()
icon_pixmap =custom_module.QPixmap(path+prefix+str(index)+ext)
icon_label.setPixmap(icon_pixmap)
table.setCellWidget(column,icon_label)
table.cellClicked.connect(print_cell)
self.window.show()
if __name__ == '__main__':
dialog = PyDialog('path')
一些进一步的评论:
是的,正如评论中指出的那样,目前外部函数不是类的一部分。
我从许多与表格外观相关的功能中剥离了代码,但这可能足以诊断问题。
非常感谢。
解决方法
您不需要通过信号传递更多参数。一般来说,附加信息应该可以通过类成员访问。在您的特定情况下,您有两个选择:
- 使用硬编码的
max_column_count
,例如print(row*self.max_column_count + column)
或
- (首选)获取
table
的列数,例如print(row*self.table.rowCount() + column)
您可以使用 lambda
或 functools.partial
传递额外数据:
def print_cell(table,row,column):
columnCount = table.columnCount()
print(row * columnCount + column)
拉姆达:
table.cellClicked.connect(lambda row,column: print_cell(table,column))
部分:
table.cellClicked.connect(functools.partial(print_cell,table))