将二维数组整数数据从 C++ 发送到 qml

2022-01-19 00:00:00 qt qml c++

我已经搜索了一整天,但是这个问题让我很困扰.

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

我正在创建一个游戏(类似于Lines")并尝试保存网格状态(0 - 如果清除,> 0 - 如果存储了一些球).我的班级有一个空位:

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];
}

然后:

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?

推荐答案

我找到了解决方案!

首先,我创建了:

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]);
        }
    }

这些值可以很容易地传递给 QML.然后在qml中再次打开它:

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;
}

相关文章