如何在两个类之间连接函数

how to connect function between two classes

本文关键字:两个 之间 连接 函数      更新时间:2023-10-16

我在两个文件中有两个不同的类:

class Game: public QGraphicsView()
class Window: public QMainWindow()
{
 public: Window(); 
              Game *game;
 public slots: void test() {game = new Game();};
}

Window.cpp我使用 test() 函数启动一个新游戏:

Window::Window() {test();}

现在在Game.cpp我创建了一个带有两个QPushButtonQMessageBox

    QMessageBox *box= new QMessageBox();
    QPushButton *btYES = box->addButton(tr("YES"),QMessageBox::ActionRole);
    QPushButton *btNO = box->addButton(tr("NO"),QMessageBox::ActionRole);
    box->exec();
    if (box->clickedButton() == btYES) {Window::test();}
    if (box->clickedButton() == btNO) {close();}

如您所见,我想将函数test()连接到Game.cpp内部的btYES,但该功能位于Window.cpp内部,其功能是启动新游戏。

可以这样做吗?

QPushButton 在按下/释放时会发出事件

因此,您可以将释放的信号连接到插槽:

connect(button, SIGNAL(released()), windowClass, SLOT(handleButton()));

在您的情况下,您需要跨类发送它,因此您可能需要分两步完成。

在游戏中:

// connect the button to a local slot
connect(btYES, SIGNAL(released()), this, SLOT(handleYesButton()));
// in the slot emit a signal - declare the signal in the header
game::handleYesButton()
{
   emit userChoiceYes();
}

在窗口中

// connect the signal in game to a your slot:
connect(game, SIGNAL(userChoiceYes()), this, SLOT(test()));

然后,当 btnYes 被按下/释放时,释放的信号被发出 - 你在handleYesButton()中拾取它并发出你自己的信号,你的窗口类连接到该信号并在test()中处理它

基于@code_fodder答案,但你甚至不需要另一个插槽,加上 QPushButton 的基本信号是 clicked() .这是文档:

按钮在被 鼠标、空格键或通过键盘快捷键。连接到此信号 以执行按钮的操作。按钮也提供较少 常用信号,例如 pressed()release()。

首先,无需在类Game中添加另一个插槽,只需将按钮的信号clicked()连接到另一个信号

connect(btYES, SIGNAL(clicked()), this, SIGNAL(btYesClicked()));

现在,当您按下按钮 btYes 时,会发出来自类Game的信号。现在,您只需将此信号连接到类Window中的插槽test()

connect(game, SIGNAL(btYesClicked()), this, SLOT(test()));