我正在尝试创建基于 QQuickWidget 的应用程序。
我正在尝试做的事情:
A 类(game.h)和 B 类(gamestate.h)是前向声明的。 A 类是带有方法的主要 QQuickWidget 类。 B类QObject派生类包含信号、槽、变量和方法。
B 类变量值可以从 A 类设置 -- 工作
当变量值改变时应该发出信号——工作
当发出信号时,应该在类 B 中调用槽方法——工作
B 类应该调用 A 类中的方法——工作
A 类应该创建另一个 qquickwidget -- NOT WORKING (没有编译错误。应用程序在加载时崩溃)
我尝试从类 A 调用并且 showIntro() 函数工作正常。但是当试图从 B 类调用时它不起作用。
游戏.h
#ifndef GAME_H
#define GAME_H
#include <QQuickWidget>
class GameState;
class Game: public QQuickWidget
{
Q_OBJECT
public:
Game();
GameState *gameState;
void showIntro();
public slots:
void onStatusChanged(QQuickWidget::Status);
};
#endif // GAME_H
游戏.cpp
#include "game.h"
#include <QQuickWidget>
#include <QDebug>
#include "gamestate.h"
Game::Game(): QQuickWidget()
{
gameState = new GameState(this);
mainScreen = new QQuickWidget();
connect(this, SIGNAL(statusChanged(QQuickWidget::Status)), this, SLOT(onStatusChanged(QQuickWidget::Status)));
setFixedSize(450, 710);
setSource(QUrl("qrc:/EmptyScreen.qml"));
}
void Game::onStatusChanged(QQuickWidget::Status status)
{
switch(status)
{
case QQuickWidget::Ready:
qDebug() << "hi";
gameState->setValue(1);
//showIntro();
break;
case QQuickWidget::Error:
qDebug() << "Error";
break;
}
}
void Game::showIntro()
{
mainScreen->setSource(QUrl("qrc:/MainScreen.qml"));
mainScreen->setAttribute(Qt::WA_TranslucentBackground);
mainScreen->setParent(this);
}
这是我的Gamestate.h
#ifndef GAMESTATE_H
#define GAMESTATE_H
#include <QObject>
class Game;
class GameState : public QObject
{
Q_OBJECT
public:
explicit GameState(QObject *parent = 0);
int value() const {return m_value; }
Game *game;
signals:
void valueChanged(int newValue);
public slots:
void setValue(int value);
void stateChanged(int value);
private:
int m_value;
};
#endif // GAMESTATE_H
游戏状态.cpp
#include "gamestate.h"
#include "game.h"
GameState::GameState(QObject *parent) : QObject(parent)
{
m_value = 0;
connect(this,SIGNAL(valueChanged(int)), this, SLOT(stateChanged(int)));
}
void GameState::setValue(int value)
{
if(value != m_value)
{
m_value = value;
emit valueChanged(value);
}
}
void GameState::stateChanged(int value)
{
if(value == 1)
{
game->showIntro();
}
}
和我最后的 main.cpp
#include <QApplication>
#include <QQmlApplicationEngine>
#include "game.h"
Game *game;
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
game = new Game();
game->show();
return app.exec();
}
请告诉我可能是什么问题。
最佳答案
GameState
类的成员变量 Game* game
未初始化,因此在尝试取消引用 GameState::stateChanged()< 中的指针时程序崩溃
.
将 GameState
的构造函数更改为以下内容:
// in gamestate.h
explicit GameState(Game *parent = 0);
// in gamestate.cpp
GameState::GameState(Game *parent) : QObject(parent), game(parent)
{
m_value = 0;
connect(this,SIGNAL(valueChanged(int)), this, SLOT(stateChanged(int)));
}
关于c++ - QT c++ 在使用信号和槽从另一个类调用类的方法时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31847498/