send 2d array integer data from c++ to qml

2020-07-27 16:05发布

问题:

Ive been searching whole day, but this questions bothers me so much.

Im creating a game (similar to "Lines") and im attempting to save the grid state (0 - if clear, > 0 - if stored some ball). I have a slot in my class:

int Game::getGridMap() {
    return gameGridArray[9][9];
}

and then:

onPressed: {
                buttonStart.color = "#222333"

                handleGame.initGame();
                var aRect = handleGame.getGridMap();
            }

but it returns "undefined" or smth like that.

what am i doing wrong? is that a better way to store these data?

回答1:

I've found a solution!

First, i created:

QList<int> getGridMap();

and then created a list from a 2 dimentional array:

for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
            oChildList.append(gameGridArray[i][j]);
        }
    }

This values can be easely passed to QML. and then just turned it again in qml:

var aRect = create2DArray(9);
var aString = handleGame.getGridMap();

aRect = listToArray(aString);

function listToArray(arr) {
    var arr2d = new create2DArray(9);

    for (var i = 0; i < 9; i++) {
        for (var j = 0; j < 9; j++) {
            arr2d[i][j] = arr[i*9+j];
        }
    }

    return arr2d;
}

function create2DArray(rows) {
  var arr = [];

  for (var i=0;i<rows;i++) {
     arr[i] = [];
  }

  return arr;
}


回答2:

You need to put "Q_INVOCABLE" before definition of getGridMap() in Game class header file.

For example,

Q_INVOCABLE int getGridMap();



标签: c++ qt qml