pythonfor-looppyside2qtwidgetsqgridlayout

Python/pyside2 how to iterate 5 times, then add a row and then iterate again?


I'm populating a QtWidgets.QGridLayout from a large list and I'm trying to create a loop that will add one row with 5 columns, over and over again, until I run out of things in a list.

Here is a example of what my broken brain is struggling with...

mylist =['thing001', 'thing002', 'thing003', 'thing004', 'thing005', 'thing006', 'thing007', 'thing008', 'thing009', 'thing010']

rowCount=0
colCount=0

def start():
   
    for each in mylist:
        i=0
        myThing = (str('btn_'+ each ))
        colCount=0
        rowCount=0
    
        #add a column until it reaches 5, then make a new row?
        for i in range(0,5):
            colCount += 1
            i+=1
            print ('Making Thing: ' + myThing +' | '+(str(rowCount)+':'+(str(colCount))))

        else:
            print('New Row!!!!!!!!!!!!!!!!!!!')
            colCount = 0
            rowCount += 1
            i+=1
                
start()

which gives me this...

Making Thing: btn_thing001 | 0:1
Making Thing: btn_thing001 | 0:2
Making Thing: btn_thing001 | 0:3
Making Thing: btn_thing001 | 0:4
Making Thing: btn_thing001 | 0:5
New Row!!!!!!!!!!!!!!!!!!!
Making Thing: btn_thing002 | 0:1
Making Thing: btn_thing002 | 0:2
Making Thing: btn_thing002 | 0:3
Making Thing: btn_thing002 | 0:4
Making Thing: btn_thing002 | 0:5
New Row!!!!!!!!!!!!!!!!!!!

which I would like to be...

Making Thing: btn_thing001 | 0:1
Making Thing: btn_thing002 | 0:2
Making Thing: btn_thing003 | 0:3
Making Thing: btn_thing004 | 0:4
Making Thing: btn_thing005 | 0:5
New Row!!!!!!!!!!!!!!!!!!!
Making Thing: btn_thing006 | 1:1
Making Thing: btn_thing007 | 1:2
Making Thing: btn_thing008 | 1:3
Making Thing: btn_thing009 | 1:4
Making Thing: btn_thing010 | 1:5
New Row!!!!!!!!!!!!!!!!!!!

How do I structure the loops to spit out what I need?


Solution

  • This is very easy to do using the python built-in function divmod

    mylist = ['thing001', 'thing002', 'thing003', 'thing004', 'thing005', 'thing006', 'thing007', 'thing008', 'thing009', 'thing010']
    COLUMNS = 5
    
    for i, item in enumerate(mylist):
        row, column = divmod(i, COLUMNS)
        print(item, row, column)
    

    print output:

    thing001 0 0
    thing002 0 1
    thing003 0 2
    thing004 0 3
    thing005 0 4
    thing006 1 0
    thing007 1 1
    thing008 1 2
    thing009 1 3
    thing010 1 4