gpt4 book ai didi

c++ - 继承QObject的类中的方法在调用时被标识为属性,而不运行方法

转载 作者:行者123 更新时间:2023-12-02 10:36:29 25 4
gpt4 key购买 nike

基本上,我有一个正在处理的项目,该项目应该是井字游戏的图形游戏,并且从主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)
}
}
}
//...

}
//...

最佳答案

您已经将Game注册为一种类型,因此您需要做的是创建该类型的对象,错误指出了该问题:

// ...
Window {
visible: true
width: 600
height: 600
title: qsTr("TicTacToe")
Game {
id: game
}


// ...
Item {
// ...
MouseArea {
id: mouseArea1
anchors.fill: parent
onClicked: {
game.takeTurn(0,0)
}
}
}
// ...

关于c++ - 继承QObject的类中的方法在调用时被标识为属性,而不运行方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60082423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com