使用QAbstractItemModel将2D C ++游戏板暴露给QML

时间:2016-09-26 16:32:42

标签: c++ qt qml qtquick2 qt-quick

我正在用C ++中的游戏板模型编写一个简单的Snake游戏,其中包含二维状态向量(std::vector<std::vector<board::state>>)。现在我想将这个板暴露给QML,这样它基本上是某种可以访问模型状态的网格/棋盘。 我已经阅读了很多关于这个主题的内容,但仍然无法理解足以解决我的问题的机制。将文档,教程和博客条目应用到我的问题是我的障碍。

我为我的游戏板模型子代QAbstractItemModel并实现了必要的功能。现在我想进入QML并在那里使用/显示我的模型的内容。

这是我的代码:

board.h

#pragma once

#include <vector>

#include <QAbstractItemModel>

class board : public QAbstractItemModel
{
  Q_OBJECT

public:
  enum class state
  {
    empty,
    snake,
    fruit
  };

  board(int x, int y);

  state get_state(int x, int y) const;
  void  set_state(int x, int y, state state);

  QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const;
  QModelIndex parent(const QModelIndex& index) const;
  int rowCount(const QModelIndex& parent = QModelIndex()) const;
  int columnCount(const QModelIndex& parent = QModelIndex()) const;
  QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;

private:
  std::vector<std::vector<state>> m_board;
};

Q_DECLARE_METATYPE(board::state)

board.cpp

#include "board.h"

board::board(int x, int y) :
  m_board(x, std::vector<board::state>(y, board::state::empty))
{
}

//----------------------------------------------------------------------------------------------------------------------

board::state board::get_state(int x, int y) const
{
  if((size_t) x >= m_board.size() || x < 0)
    return board::state::empty;

  if((size_t) y >= m_board.at(0).size() || y < 0)
    return board::state::empty;

  return m_board.at(x).at(y);
}

//----------------------------------------------------------------------------------------------------------------------

void board::set_state(int x, int y, state state)
{
  if(get_state(x, y) == state)
    return;

  m_board.at(x).at(y) = state;
}

//----------------------------------------------------------------------------------------------------------------------

QModelIndex board::index(int row, int column, const QModelIndex&) const
{
  if((size_t) row >= m_board.size() || row < 0)
    return QModelIndex();

  if((size_t) column >= m_board.at(0).size() || column < 0)
    return QModelIndex();

  return createIndex(row, column);
}

//----------------------------------------------------------------------------------------------------------------------

QModelIndex board::parent(const QModelIndex& index) const
{
  if((size_t) index.row() >= m_board.size() || index.row() < 0)
    return QModelIndex();

  if((size_t) index.column() >= m_board.at(0).size() || index.column() < 0)
    return QModelIndex();

  return createIndex(index.row(), index.column());
}

//----------------------------------------------------------------------------------------------------------------------

int board::rowCount(const QModelIndex&) const
{
  return m_board.size();
}

//----------------------------------------------------------------------------------------------------------------------

int board::columnCount(const QModelIndex&) const
{
  return m_board.at(0).size();
}

//----------------------------------------------------------------------------------------------------------------------

QVariant board::data(const QModelIndex& index, int role) const
{
  if(!index.isValid())
    return QVariant();

  if(role != Qt::DisplayRole)
    return QVariant();

  if((size_t) index.row() >= m_board.size() || index.row() < 0)
    return QVariant();

  if((size_t) index.column() >= m_board.at(0).size() || index.column() < 0)
    return QVariant();

  return qVariantFromValue(get_state(index.row(), index.column()));
}

的main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QQuickView>

#include <board.h>

int main(int argc, char *argv[])
{
  QGuiApplication app(argc, argv);



  board game_board(10, 10);
  game_board.set_state(4, 9, board::state::snake);
  game_board.set_state(3, 10, board::state::fruit);

  QQuickView view;
  view.setResizeMode(QQuickView::SizeRootObjectToView);
  QQmlContext *ctxt = view.rootContext();
  ctxt->setContextProperty("myGameBoard", &game_board);

  QQmlApplicationEngine engine;
  engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

  return app.exec();
}

main.qml

import QtQuick 2.6
import QtQuick.Window 2.2

Window {
  visible: true

  MouseArea {
    anchors.fill: parent
    onClicked: {
      Qt.quit();
    }
  }

  Text {
    text: qsTr("Hello World")
    anchors.centerIn: parent
  }

  GridView {
    model: myGameBoard
    delegate: Rectangle {
      width: 30
      height: 30
      color: blue
    }
  }
}

我确信有很多东西我不知道或者只是公然错了。另外我知道将C ++模型暴露给QML经常被问到并且被很好地覆盖,但我仍然无法管理。

说明一些更具体的问题:

  • 如何在QML中显示模型中的数据?我已经看到这是使用角色名称完成的,但我的行没有列的角色名称
  • 我的模型是否正确实施?
  • 我需要使用什么QML组件才能拥有磁贴/棋盘?如果我需要自定义组件,那么从模型中读取数据需要哪些属性?

感谢您一看!

2 个答案:

答案 0 :(得分:2)

  1. QtQuick是使用QML的主要UI框架,它基本上只处理列表模型,因此使用角色来模拟表格,例如使用TableView

  2. parent()方法错误,因为它基本上会再次返回相同的索引。这不会导致你的情况有任何问题,因为你有一张桌子而不是一棵树。

  3. 建议:如果您只需要一个表格模型,请从QAbstractTableModel派生并让它照顾index()parent()

    1. 没有可以处理表模型的标准QtQuick元素,因此您必须构建自己的或使用列表模型,只需在网格中排列“列表项”。
    2. 如果是自定义项目,您可以构建一个适用于您的模型的项目,甚至可以直接处理数据,而无需模型。

      如果你使用模型并希望从QML实例化模型,那么你需要一个属性“指向你的模型类”或“指向QAbstractItemModel的指针。

      如果您不想使用模型或不需要从QML实例化它,那么您根本不需要任何特定属性。

      在任何一种情况下,您的自定义项都可以使用以下方法之一:

      1. 它可以自己绘制所有东西,即瓷砖网格和瓷砖本身
      2. 只提供网格并使用委托来绘制不同类型的图块,例如ListView允许为列表元素,页眉,页脚等设置委托。

答案 1 :(得分:1)

我有一个适合我的解决方案。这是我做的和一些代码:

  • 我使用Q_ENUM作为状态枚举,使其在QML中可用
  • 将rootContext连接到QML引擎
  • 写了一个自定义QML组件,该组件由一个包含带转发器的行的转发器的列组成
  • 保存外部转发器和内部转发器的索引以编译用于访问数据的索引
  • 一些清理

<强>代码

<强> Board.qml

import QtQuick 2.0

Column {
  Repeater {
    model: myGameBoard.columnCount()

    Row {
      property int y_pos: index

      Repeater {
        id: repeatr
        model: myGameBoard.rowCount()

        Cell {
          x_cord: index
          y_cord: y_pos

          size: 20
        }
      } //Repeater
    } //Row
  } //Repeater
} //Column

<强> Cell.qml

import QtQuick 2.0

Rectangle {
  id: cell
  property int x_cord: 0
  property int y_cord: 0
  property int size: 10

  width: size
  height: size

  color: getCorrectColor()

  Connections {
    target: myGameBoard
    onDataChanged: {
      cell.color = cell.getCorrectColor()
    }
  }

  function getCorrectColor() {
    switch(myGameBoard.data(myGameBoard.index(cell.x_cord, cell.y_cord)) + 0) {
    case 0 :
      return "honeydew"
    case 1 :
      return "black"
    case 2 :
      return "orangered"
    default:
      return "yellow"
    }
  }
}

除了在board.h上的状态枚举上使用Q_ENUM之外,C ++方面基本保持不变。

感谢您对转发器的帮助和提示!