Important: Please read the Qt Code of Conduct -

[SOLVED] Creating 2D array of custom widgets in for loops

  • Edit: I don't know how to remove a thread, but just letting you know it was because I had used i instead of j in the second for loop. Silly me.

    Hi, I have a custom widget named Die, which overrides paintEvent to display a rectangle.

    I can create a number of these one by one to form a grid. At the moment I'm trying to make it just 4 by 4 Die.

    I've got that working with the following code:

    @ Die *die11 = new Die(ui->dieMap,0,0,2);
    ui->dieLayout->addWidget(die11, 0, 0, 1, 1);

    Die *die12 = new Die(ui->dieMap,0,0,3);
    ui->dieLayout->addWidget(die12, 80, 0, 1, 1);
    Die *die13 = new Die(ui->dieMap,0,0,2);
    ui->dieLayout->addWidget(die13, 160, 0, 1, 1);
    Die *die14 = new Die(ui->dieMap,0,0,3);
    ui->dieLayout->addWidget(die14, 240, 0, 1, 1);@

    Note: dieLayout is the layout of the frame which I have created in mainwindow.ui.
    That's just the code I have for column1. It creates 4 rectangles in one column.

    I now want to create the die using for loops and an array. I get rid of all of the individual entries, and replace it with the code below:

    @Die *dieArray[4][4];

    for(int i = 0;i<4;i++){
    for(int j = 0;i<4;j++){
    dieArray[i][j] = new Die(ui->dieMap,0,0,2);
    ui->dieLayout->addWidget(dieArray[i][j], i80, j80, 1, 1);

    I want dieArray to hold the Die objects.

    When I try to run it, I get the error:

    @The program has unexpectedly finished.@

    I do not understand why this error is occuring.

    Any suggestions/help appreciated.

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    It's because you didn't allocate your two dimensional array before using it

Log in to reply