简体   繁体   English

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

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

I'm having trouble with an application that creates a grid of QComboBox widgets (see picture below). 我在创建QComboBox小部件网格的应用程序时遇到麻烦(请参见下图)。 I use a for loop to create the elements of the grid. 我使用for循环创建网格的元素。

QComboBox grid layout QComboBox网格布局

I would like to be able to treat each QComboBox separately. 我希望能够分别对待每个QComboBox。 Here is the code without attempts to do so: 这是没有尝试的代码:

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

Here is my attempt, and the point at which I am currently stuck: 这是我的尝试,也是我目前遇到的问题:

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')

The print() method only ever returns the last position in the list (in this case, the (3, 4) tuple. print()方法仅返回列表中的最后一个位置(在这种情况下,为(3,4)元组。

As the position variable changes this is overwritten by it only prints the last one, if you want it not to be overwritten you must pass it as an argument to the lambda function, besides. 当position变量更改时,此变量将被覆盖,仅打印最后一个变量,如果不希望覆盖,则必须将其作为参数传递给lambda函数。 And for this you must also pass as an argument the variable that sends the signal, in your case use the following: 为此,您还必须将发送信号的变量作为参数传递,在您的情况下,请使用以下命令:

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