По сути, у меня есть проект, над которым я работаю, который должен быть графической игрой Ti c -Ta c -Toe, и вызовы методов для класса с именем "Game" (и любые вызовы методов вообще) из основного файла qml не работают. Возвращается эта ошибка:
TypeError: Property 'takeTurn' of object [object Object] is not a function
Я унаследовал QObject в этом классе, а также включил макрос Q_OBJECT и пометил метод как Q_INVOKABLE.
Код прекрасно компилируется и связывается, это ошибка во время выполнения.
Вот соответствующий код, чтобы помочь:
Game.hpp:
#define GAME_HPP
#include "Board.hpp"
#include <ostream>
#include <QObject>
class Game : public QObject
{
Q_OBJECT;
public:
//...
Q_INVOKABLE void takeTurn(int x, int y);
Q_INVOKABLE bool checkWin();
friend std::ostream& operator<<(std::ostream&, const Game&);
private:
char player_;
int turns_;
Board board_;
};
std::ostream& operator<<(std::ostream&, const Game&);
#endif // GAME_HPP
Game. cpp:
#include <iostream>
#include <QObject>
#include <QApplication>
using std::cout;
using std::endl;
//...
void Game::takeTurn(int x, int y)
{
QWindow* app = QApplication::topLevelWindows()[0];
cout << app << endl;
board_.setTile(x, y, player_);
player_ == 'X' ? player_ = 'O' : player_ = 'X';
turns_++;
}
//...
main. cpp:
#include "Game.hpp"
#include <iostream>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
using std::cout;
using std::endl;
Q_DECL_EXPORT int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
qmlRegisterType<Game>("com.myself", 1, 0, "Game");
qmlRegisterType<Board>("com.myself", 1, 0, "Board");
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
main.qml:
import QtQuick.Window 2.12
import com.myself 1.0
Window {
visible: true
width: 600
height: 600
title: qsTr("TicTacToe")
Item {
//...
MouseArea {
id: mouseArea1
anchors.fill: parent
onClicked: {
Game.takeTurn(0,0)
}
}
}
//...
}
//...