gpt4 book ai didi

c++ - 具有返回值的信号/插槽不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 14:03:36 24 4
gpt4 key购买 nike

我在 Qt 中创建了一个信号槽,程序运行时没有关于我创建的连接的错误或警告。问题是当我想使用信号槽时,它总是返回 NULL。

main.cpp

int main(int argc, char *argv[])
{
QApplication a(argc, argv);


Game* game = new Game;

Scrabble mainWindow;
mainWindow.show();

QObject::connect(&mainWindow,SIGNAL(getTurn()),game,SLOT(giveTurn()));

return a.exec();
}

游戏.h

class Game: public QObject
{
Q_OBJECT
public:
Game(QObject *parent = 0);
~Game();
private:
int m_turn;
public slots:
int giveTurn();

};

游戏.cpp

Game::Game(QObject *parent)
:QObject(parent)
{
m_turn = 1;
}
Game::~Game()
{

}

int Game::giveTurn()
{
return m_turn;
}

拼字游戏.h

class Scrabble : public QMainWindow
{
Q_OBJECT

public:
explicit Scrabble(QWidget *parent = 0);
~Scrabble();

private:
Ui::Scrabble *ui;
signals:
int getTurn();

};

当我在 Scrabble.cpp 中使用 int turn = emit getTurn(); 时,turn 将变为 0 而不是 1。有谁知道我做错了什么?

最佳答案

您错误地使用了信号和槽。信号不能返回值。查看Signals & Slots文档页面:

Signals are automatically generated by the moc and must not be implemented in the .cpp file. They can never have return types (i.e. use void).

正确使用 Qt 功能时,不需要从信号返回值。也许您应该提出另一个问题并描述您想做什么以及为什么需要这种联系。你肯定做错了什么。

关于c++ - 具有返回值的信号/插槽不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18043112/

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