繁体   English   中英

使用PyQt5在for循环中使QComboBox小部件可区分

[英]Making QComboBox widgets distinguishable in a for loop using PyQt5

我在创建QComboBox小部件网格的应用程序时遇到麻烦(请参见下图)。 我使用for循环创建网格的元素。

QComboBox网格布局

我希望能够分别对待每个QComboBox。 这是没有尝试的代码:

grid = QGridLayout()
combos = [
'1', '1', '1', '', '1', 
'1', '1', '1', '', '1',
'1', '1', '1', '', '1',
'1', '1', '1', '', '1']

positions = [(i,j) for i in range(5) for j in range(5)]
for position, dcombo in zip(positions, combos):
    if dcombo == '':
        continue
    combo = QComboBox()

    for x in range(0, 30):
        combo.addItem(QIcon("/icons/%d.PNG" % x),"")

    combo.setFixedSize(120,100)
    combo.setIconSize(QSize(100,100))
    grid.addWidget(combo, *position)

    comboList['combo{0}'.format(position)] = position

这是我的尝试,也是我目前遇到的问题:

grid = QGridLayout()
combos = [
'1', '1', '1', '', '1', 
'1', '1', '1', '', '1',
'1', '1', '1', '', '1',
'1', '1', '1', '', '1']

comboList = {}

positions = [(i,j) for i in range(5) for j in range(5)]
for position, drawcombo in zip(positions, combos):
    if drawcombo == '':
        continue
    combo = QComboBox()

    for x in range(0, 30): #
        combo.addItem(QIcon("absolver deck reviewer/icons/%d.PNG" % x),"")

    combo.setFixedSize(120,100)
    combo.setIconSize(QSize(100,100))
    grid.addWidget(combo, *position)

    comboList['combo{0}'.format(position)] = position
    combo.currentIndexChanged.connect(lambda: self.logChange(comboList['combo{0}'.format(position)]))

def logChange(self, currentCombo):
    sender = self.sender()
    print(str(currentCombo) + ' was changed')

print()方法仅返回列表中的最后一个位置(在这种情况下,为(3,4)元组。

当position变量更改时,此变量将被覆盖,仅打印最后一个变量,如果不希望覆盖,则必须将其作为参数传递给lambda函数。 为此,您还必须将发送信号的变量作为参数传递,在您的情况下,请使用以下命令:

combo.currentIndexChanged.connect(
    lambda ix, p=position: self.logChange(comboList['combo{0}'.format(p)]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM