【发布时间】:2020-05-21 18:12:45
【问题描述】:
基本上,我有一个我正在开发的项目,它应该是井字游戏的图形游戏,并且从主程序调用一个名为“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
游戏.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)
}
}
}
//...
}
//...
【问题讨论】: