简体   繁体   中英

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). I use a for loop to create the elements of the grid.

QComboBox grid layout

I would like to be able to treat each QComboBox separately. 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.

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. 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)]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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